@promptdriven/runtime-client 1.0.0 → 1.1.1

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.
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: f41d7f574a23051c271d1138f976cc7dfc5662eb961142d4355f4210945f104f).
1
+ // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: e4f44576c9130a890ca3b7c16284bcabb7a9c42788e097f636419ed7f1ddabd2).
2
2
  import { markdownLinks, markdownDefinitions, markdownSectionText } from './runtime-markdown.mjs';
3
3
  import { buildBindingPlan, runtimeBoundary } from './runtime-binding-plan.mjs';
4
4
  import { createHash } from 'node:crypto';
@@ -7,7 +7,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, rea
7
7
  import { basename, join, posix, isAbsolute, relative, resolve, sep } from 'node:path';
8
8
  import { isDeepStrictEqual } from 'node:util';
9
9
  import { expandSource } from './contract-refs.mjs';
10
- import { exactValue, parseScenarioJson, roundedNumberTokens, stringifyScenarioJson } from './scenario-json.mjs';
10
+ import { checkDerivation, exactValue, parseScenarioJson, roundedNumberTokens, stringifyScenarioJson } from './scenario-json.mjs';
11
11
  import {loadRuntimeWorkspace as loadWorkspacePolicy,allowsRuntimePath,requireRuntimePath as requireWorkspacePath} from './runtime-workspace.mjs';
12
12
 
13
13
  function workspaceError(error){if(error?.code?.startsWith('workspace-'))throw Object.assign(new PreflightError(4,error.message),{code:error.code});throw error;}
@@ -26,6 +26,15 @@ const OPTIONAL_STEP_KEYS = ['expected_error', 'simulation_overrides', 'model'];
26
26
  const STEP_KEYS = new Set([...REQUIRED_STEP_KEYS, ...OPTIONAL_STEP_KEYS]);
27
27
  const RULE_OPS = new Set(['at_most', 'at_least', 'lt', 'lte', 'gt', 'gte', 'not_contains', 'all_in', 'equals_ignore_case']);
28
28
  const EXACT_OPS = new Set(['equals', 'not_equals', 'one_of', 'count', 'integer_relation', ...RULE_OPS]);
29
+ const CHECK_OPS = new Set([...EXACT_OPS, 'exists', 'contains']);
30
+ const CALLS_OPS = new Set(['count', 'equals', 'not_equals', 'one_of']);
31
+ const ERROR_OPS = new Set(['count', 'equals', 'exists', 'not_equals', 'one_of']);
32
+ const CHECK_KEYS = new Set(['criterion_id', 'target', 'path', 'op', 'value', 'json_path', 'html', 'measure',
33
+ 'ref_target', 'ref_path', 'ref_json_path', 'derivation']);
34
+ const hasCheckRef = check => isObject(check) && (
35
+ Object.hasOwn(check, 'ref_target') || Object.hasOwn(check, 'ref_path') || Object.hasOwn(check, 'ref_json_path')
36
+ || (isObject(check.value) && (Object.hasOwn(check.value, 'ref_target') || Object.hasOwn(check.value, 'ref_path')))
37
+ );
29
38
  const SCHEMA_RULES = new Set(['type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'oneOf',
30
39
  'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'pattern',
31
40
  'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties']);
@@ -371,6 +380,21 @@ const exactSchemaValue = (holder, key) => {
371
380
  : isObject(value) ? Object.fromEntries(Object.keys(value).map(name => [name, exactSchemaValue(value, name)])) : value;
372
381
  };
373
382
  const sameValue = (a, b) => isDeepStrictEqual(exactValue(a), exactValue(b));
383
+ // JSON Schema equality is recursive and numeric: -0 equals 0, while exact
384
+ // integer tokens remain distinct even when their Number representations round.
385
+ function sameJsonValue(a, b) {
386
+ if (numeric(a) && numeric(b)) {
387
+ if (typeof a === typeof b) return a === b;
388
+ const whole = typeof a === 'number' ? a : b, exact = typeof a === 'bigint' ? a : b;
389
+ return Number.isInteger(whole) && BigInt(whole) === exact;
390
+ }
391
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b)
392
+ && a.length === b.length && a.every((item, index) => sameJsonValue(item, b[index]));
393
+ if (isObject(a) || isObject(b)) return isObject(a) && isObject(b)
394
+ && Object.keys(a).length === Object.keys(b).length
395
+ && Object.keys(a).every(key => Object.hasOwn(b, key) && sameJsonValue(a[key], b[key]));
396
+ return a === b;
397
+ }
374
398
  const article = type => /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
375
399
 
376
400
  function unknownKeyword(schema) {
@@ -397,16 +421,16 @@ function portablePattern(source, value) {
397
421
  if (/\\(?:[1-9bBAZzGkpPuU]|x|c)|\(\?|[\s\S]*[\u0080-\uffff]/u.test(source)) return null;
398
422
  try { return new RegExp(source, 'u'); } catch { return null; }
399
423
  }
400
- function schemaRun(value, schema, tokens) {
424
+ function schemaRun(value, schema, tokens, equality = null) {
401
425
  const problems = [], warnings = [], evidence = { miss: false, unknown: false };
402
- schemaProblems(value, schema, tokens, problems, warnings, evidence);
426
+ schemaProblems(value, schema, tokens, problems, warnings, evidence, equality);
403
427
  return { problems, warnings, state: problems.length || evidence.miss ? 'miss' : evidence.unknown ? 'unknown' : 'match' };
404
428
  }
405
- function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss: false, unknown: false }) {
429
+ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss: false, unknown: false }, equality = null) {
406
430
  const at = rule => out.push({ tokens, rule });
407
431
  if (!isObject(schema)) return;
408
432
  if (Array.isArray(schema.oneOf)) {
409
- const runs = schema.oneOf.map(variant => schemaRun(value, variant, tokens));
433
+ const runs = schema.oneOf.map(variant => schemaRun(value, variant, tokens, equality));
410
434
  const fits = runs.filter(run => run.state === 'match').length;
411
435
  if (fits > 1) return at(`fits more than one of the allowed shapes (oneOf). Make the shapes exclusive.`);
412
436
  if (fits === 1) {
@@ -426,8 +450,9 @@ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss:
426
450
  if (!types.some(type => typeMatches(value, type))) return at(`is ${show(value)}. The prompt wants ${types.map(article).join(' or ')}.`);
427
451
  }
428
452
  const wanted = exactSchemaValue(schema, 'const'), choices = Array.isArray(schema.enum) ? schema.enum.map((_, index) => exactSchemaValue(schema.enum, index)) : null;
429
- if (Object.hasOwn(schema, 'const') && !sameValue(value, wanted)) at(`is ${show(value)}. The prompt wants ${show(wanted)}.`);
430
- if (choices && !choices.some(choice => sameValue(choice, value))) at(`is ${show(value)}. The prompt allows ${either(choices.map(show))}.`);
453
+ const equal = equality ?? sameValue;
454
+ if (Object.hasOwn(schema, 'const') && !equal(value, wanted)) at(`is ${show(value)}. The prompt wants ${show(wanted)}.`);
455
+ if (choices && !choices.some(choice => equal(choice, value))) at(`is ${show(value)}. The prompt allows ${either(choices.map(show))}.`);
431
456
  if (numeric(value)) {
432
457
  const [minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf] = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'].map(key => schemaValue(schema, key));
433
458
  if ((minimum !== undefined && value < minimum) || (maximum !== undefined && value > maximum)) at(`is ${show(value)}. The prompt allows ${range(minimum, maximum)}.`);
@@ -463,8 +488,8 @@ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss:
463
488
  if ((schema.minItems !== undefined && value.length < schema.minItems) || (schema.maxItems !== undefined && value.length > schema.maxItems)) {
464
489
  at(`has ${plural(value.length, 'item')}. The prompt allows ${range(schema.minItems, schema.maxItems, 'item')}.`);
465
490
  }
466
- if (schema.uniqueItems === true && value.some((item, index) => value.findIndex(other => isDeepStrictEqual(other, item)) !== index)) at('has the same item twice. The prompt wants unique items.');
467
- if (isObject(schema.items)) for (const [index, item] of value.entries()) schemaProblems(item, schema.items, [...tokens, String(index)], out, warnings, evidence);
491
+ if (schema.uniqueItems === true && value.some((item, index) => value.findIndex(other => (equality ?? isDeepStrictEqual)(other, item)) !== index)) at('has the same item twice. The prompt wants unique items.');
492
+ if (isObject(schema.items)) for (const [index, item] of value.entries()) schemaProblems(item, schema.items, [...tokens, String(index)], out, warnings, evidence, equality);
468
493
  }
469
494
  if (isObject(value)) {
470
495
  const count = Object.keys(value).length;
@@ -474,9 +499,9 @@ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss:
474
499
  for (const key of Array.isArray(schema.required) ? schema.required : []) if (!Object.hasOwn(value, key)) at(`has no ${show(key)}. The prompt requires it.`);
475
500
  const properties = isObject(schema.properties) ? schema.properties : {};
476
501
  for (const [key, child] of Object.entries(value)) {
477
- if (Object.hasOwn(properties, key)) schemaProblems(child, properties[key], [...tokens, key], out, warnings, evidence);
502
+ if (Object.hasOwn(properties, key)) schemaProblems(child, properties[key], [...tokens, key], out, warnings, evidence, equality);
478
503
  else if (schema.additionalProperties === false) at(`has ${show(key)}. The prompt does not allow it.`);
479
- else if (isObject(schema.additionalProperties)) schemaProblems(child, schema.additionalProperties, [...tokens, key], out, warnings, evidence);
504
+ else if (isObject(schema.additionalProperties)) schemaProblems(child, schema.additionalProperties, [...tokens, key], out, warnings, evidence, equality);
480
505
  }
481
506
  }
482
507
  }
@@ -622,6 +647,12 @@ export const schemaKeywordWarningLines = prompt => (isObject(prompt?.interface)
622
647
  .filter(item => item.code === 'graph-schema-unsupported-keyword').map(item => `Warning: ${prompt.path} ${item.pointer} ${item.code}: ${item.rule}`);
623
648
  const validCliImplementation = impl => isObject(impl) && Object.keys(impl).length === 2 && impl.kind === 'cli'
624
649
  && typeof impl.command === 'string' && Boolean(impl.command.trim()) && !/[\n\r;|&<>`$\\'"(){}*?\[\]]/.test(impl.command);
650
+ const validCallImplementation = impl => isObject(impl) && Reflect.ownKeys(impl).length === 3
651
+ && ['kind', 'command', 'symbol'].every(key => Object.hasOwn(impl, key)) && impl.kind === 'call'
652
+ && Array.isArray(impl.command) && impl.command.length > 0
653
+ && Array.from(impl.command).every(item => typeof item === 'string' && !item.includes('\0')) && Boolean(impl.command[0].trim())
654
+ && typeof impl.symbol === 'string' && Boolean(impl.symbol.trim()) && !impl.symbol.includes('\0');
655
+ const validLocalImplementation = impl => validCliImplementation(impl) || validCallImplementation(impl);
625
656
  const isCliEntry = (iface, index) => index >= 0 && Array.isArray(iface?.conventions)
626
657
  && ['input_schema', 'result_schema'].every(key => iface.conventions.some(item => isObject(item) && item.path === `/entries/${index}/${key}` && item.convention === 'cli'));
627
658
  export function interfaceSchemaProblems(iface) {
@@ -631,8 +662,8 @@ export function interfaceSchemaProblems(iface) {
631
662
  if (Array.isArray(iface?.draft_gaps) && iface.draft_gaps.length) out.push({code:'interface-draft-incomplete',pointer:'/draft_gaps',rule:iface.draft_gaps.join('; ')});
632
663
  for (const [index, entry] of (Array.isArray(iface?.entries) ? iface.entries : []).entries()) {
633
664
  for (const key of ['input_schema', 'result_schema']) if (isObject(entry) && Object.hasOwn(entry, key)) schemaRules(entry[key], `/entries/${index}/${key}`, out);
634
- if (isObject(entry) && Object.hasOwn(entry, 'implementation') && !validCliImplementation(entry.implementation)) {
635
- out.push({ code: 'interface-implementation-invalid', pointer: `/entries/${index}/implementation`, rule: 'must declare {"kind": "cli", "command": "..."} with whitespace-separated argv and no shell syntax.' });
665
+ if (isObject(entry) && Object.hasOwn(entry, 'implementation') && !validLocalImplementation(entry.implementation)) {
666
+ out.push({ code: 'interface-implementation-invalid', pointer: `/entries/${index}/implementation`, rule: 'must declare {"kind": "cli", "command": "..."} with whitespace-separated argv and no shell syntax, or exactly {"kind": "call", "command": ["executable", "argument", "..."], "symbol": "operation"} with NUL-free strings and nonblank executable and symbol.' });
636
667
  }
637
668
  }
638
669
  for (const [index, resource] of (Array.isArray(iface?.resources) ? iface.resources : []).entries()) {
@@ -765,14 +796,138 @@ function discoveryPromptPaths(root) {
765
796
  return [...discoveryVisibleFiles({ root, excludeFixtureProjects: true })].filter(path => path.endsWith('.prompt.md')).sort();
766
797
  }
767
798
 
799
+ export function readAppMapScreens(root, visible, workspace = loadRuntimeWorkspace({ root })) {
800
+ const mapPath = ['app-map.json', 'app/app-map.json'].find(candidate => visible.has(candidate));
801
+ if (!mapPath) return [];
802
+ try {
803
+ const raw = sourceFilePort(root, visible, workspace).read({ path: mapPath }).content;
804
+ const doc = JSON.parse(raw);
805
+ return Array.isArray(doc?.screens) ? doc.screens.filter(isObject) : [];
806
+ } catch {
807
+ return [];
808
+ }
809
+ }
810
+
811
+ export function analyzePromptSelectorWords(prompt, { appMapScreens = [] } = {}) {
812
+ const empty = { kinds: [], items: [], duplicates: [], collisions: [], tableLines: [], warnings: [], programName: null };
813
+ if (!isObject(prompt?.interface) || prompt.interface.kind === 'native-only') return empty;
814
+ const iface = prompt.interface;
815
+ const entries = Array.isArray(iface.entries) ? iface.entries : [];
816
+ const conventions = Array.isArray(iface.conventions) ? iface.conventions : [];
817
+ const rawText = String(prompt.text ?? '');
818
+ const proseText = rawText.replace(INTERFACE, '');
819
+ const heading = rawText.match(/^#\s+(.+?)\s*$/m)?.[1]?.replace(/^`([^`]+)`$/, '$1')?.trim() ?? '';
820
+ const programName = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(heading) ? heading : null;
821
+
822
+ const items = [];
823
+ const kinds = new Set();
824
+ let hasHttp = iface.kind === 'http' || Boolean(iface.http) || (Array.isArray(iface.routes) && iface.routes.length > 0);
825
+ let hasScreen = Boolean(iface.screen) || Boolean(iface.app)
826
+ || appMapScreens.some(screen => screen?.prompt_path === prompt.path);
827
+
828
+ for (const [index, entry] of entries.entries()) {
829
+ if (!isObject(entry)) continue;
830
+ const entryIsCli = isCliEntry(iface, index)
831
+ || (Array.isArray(entry.conventions) && entry.conventions.includes('cli'))
832
+ || Object.hasOwn(entry.input_schema?.properties ?? {}, 'argv')
833
+ || Object.hasOwn(entry.output_schema?.properties ?? {}, 'exit_code')
834
+ || Object.hasOwn(entry.result_schema?.properties ?? {}, 'exit_code');
835
+ const entryIsHttp = Boolean(entry.http) || Boolean(entry.route)
836
+ || (typeof entry.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title))
837
+ || (Array.isArray(entry.conventions) && entry.conventions.includes('http'))
838
+ || conventions.some(c => isObject(c) && typeof c.path === 'string' && c.path.startsWith(`/entries/${index}/`) && c.convention === 'http');
839
+ const entryIsScreen = Boolean(entry.screen)
840
+ || (Array.isArray(entry.conventions) && entry.conventions.includes('screen'))
841
+ || conventions.some(c => isObject(c) && typeof c.path === 'string' && c.path.startsWith(`/entries/${index}/`) && c.convention === 'screen');
842
+ const screenBoundOp = typeof entry.operation === 'string'
843
+ && appMapScreens.some(screen => (screen?.source ?? 'operation') === 'operation' && screen.prompt_path === prompt.path && (screen.operation ?? 'render') === entry.operation);
844
+
845
+ if (entryIsCli) {
846
+ kinds.add('cli');
847
+ items.push({ kind: 'cli', word: programName, label: programName ? `CLI "${programName}"` : 'CLI', isDefault: true });
848
+ } else if (entryIsHttp) {
849
+ hasHttp = true;
850
+ } else if (entryIsScreen || screenBoundOp) {
851
+ hasScreen = true;
852
+ } else if (typeof entry.operation === 'string' && entry.operation.trim()) {
853
+ const word = entry.operation.trim();
854
+ kinds.add('typed');
855
+ items.push({ kind: 'typed', word, label: `typed operation "${word}"`, isDefault: false });
856
+ }
857
+ }
858
+
859
+ if (hasHttp) {
860
+ kinds.add('http');
861
+ items.push({ kind: 'http', word: 'serve', label: 'HTTP routes', isDefault: false });
862
+ }
863
+ if (hasScreen) {
864
+ kinds.add('screen');
865
+ items.push({ kind: 'screen', word: 'app', label: 'Screen app', isDefault: false });
866
+ }
867
+
868
+ const byWord = new Map();
869
+ for (const item of items) {
870
+ if (!item.word) continue;
871
+ if (!byWord.has(item.word)) byWord.set(item.word, []);
872
+ byWord.get(item.word).push(item.label);
873
+ }
874
+ const duplicates = [];
875
+ for (const [word, labels] of byWord.entries()) {
876
+ if (labels.length > 1) duplicates.push({ word, labels });
877
+ }
878
+
879
+ const collisions = [];
880
+ const warnings = [];
881
+ if (kinds.has('cli') && programName) {
882
+ const escapedProg = programName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
883
+ const seenWords = new Set();
884
+ for (const item of items) {
885
+ if (!item.word || item.word === programName || seenWords.has(item.word)) continue;
886
+ seenWords.add(item.word);
887
+ const escapedWord = item.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
888
+ const pattern = new RegExp(`(?<![A-Za-z0-9_.-])${escapedProg}[ \\t]+${escapedWord}(?![A-Za-z0-9_.-])`);
889
+ if (pattern.test(proseText)) {
890
+ collisions.push({ programName, word: item.word, label: item.label });
891
+ warnings.push(`Warning: ${prompt.path}: CLI prompt text names "${programName} ${item.word}" as a subcommand, which collides with the "${item.word}" selector word (${item.label}). Use "pdd ${prompt.path} ${programName} ${item.word}" or rename the selector.`);
892
+ }
893
+ }
894
+ }
895
+
896
+ const tableLines = [];
897
+ if (kinds.size >= 2) {
898
+ const rows = items.map(item => {
899
+ const cmd = item.kind === 'cli'
900
+ ? `pdd ${prompt.path} [ARGS]`
901
+ : `pdd ${prompt.path} ${item.word}`;
902
+ const desc = item.kind === 'cli'
903
+ ? `CLI ${programName ? `"${programName}" ` : ''}(default; no ARGS opens a shell)`
904
+ : item.label;
905
+ return { cmd, desc };
906
+ });
907
+ const width = Math.max(...rows.map(row => row.cmd.length));
908
+ tableLines.push(`${prompt.path}: ${kinds.size} kinds`);
909
+ for (const row of rows) tableLines.push(` ${row.cmd.padEnd(width + 4)}${row.desc}`);
910
+ }
911
+
912
+ return { kinds: [...kinds], items, duplicates, collisions, tableLines, warnings, programName };
913
+ }
914
+
768
915
  export function interfaceFindings({ root, paths = discoveryPromptPaths(root) }) {
769
916
  const visible = new Set(gitFiles(root));
917
+ const appMapScreens = readAppMapScreens(root, visible);
770
918
  return paths.flatMap(path => {
771
919
  try {
772
920
  const prompt = readPrompt(root, visible, path), problem = promptRefusal(prompt, 'interface');
773
921
  if (!prompt.interface) return [{ ...problem, path }];
774
922
  const schema = interfaceSchemaProblems(prompt.interface).map(item => ({ code: item.code, path, section: item.pointer, message: `${path} ${item.pointer} ${item.rule}` }));
775
- return problem && !schema.some(item => item.code === problem.code) ? [{ ...problem, path }, ...schema] : schema;
923
+ const selectorDupes = analyzePromptSelectorWords(prompt, { appMapScreens }).duplicates.map(({ word, labels }) => ({
924
+ code: 'duplicate-selector-word',
925
+ path,
926
+ section: '/entries',
927
+ message: `${path} /entries duplicate-selector-word: Selector word ${JSON.stringify(word)} is used by multiple kinds or operations (${labels.join(' and ')}). Give each kind and operation its own selector word.`,
928
+ }));
929
+ const all = [...schema, ...selectorDupes];
930
+ return problem && !all.some(item => item.code === problem.code) ? [{ ...problem, path }, ...all] : all;
776
931
  } catch (error) {
777
932
  return [{ code: error.code ?? 'interface-unreadable', path, message: error.message }];
778
933
  }
@@ -785,7 +940,7 @@ export function runtimeCoverage({ root, paths = discoveryPromptPaths(root), allo
785
940
  for (const path of paths) {
786
941
  try {
787
942
  const prompt = readPrompt(root, visible, path);
788
- if (allowMissingInterfaces && prompt.error === 'interface-missing') { checkable++; continue; }
943
+ if (prompt.error === 'interface-missing') continue;
789
944
  if (promptRefusal(prompt, 'interface') || interfaceSchemaProblems(prompt.interface).length) continue;
790
945
  if (prompt.interface.kind === 'native-only') native_only++;
791
946
  else if (Array.isArray(prompt.interface.entries) && prompt.interface.entries.length && prompt.interface.entries.every(entry => typeof entry?.operation === 'string' && entry.operation.trim() && entry.input_schema && entry.result_schema)) checkable++;
@@ -887,9 +1042,91 @@ export function numberWarnings(doc, { testPath, testSha, reviews = [] } = {}) {
887
1042
  return [...warnings];
888
1043
  }
889
1044
 
1045
+ export const LAZY_INTERFACE_SYNTHESIS_CALLS = 2;
1046
+ const LAZY_INTERFACE_SYNTHESIS_HEADROOM = 4;
1047
+ const CALL_GRAPH_FANOUT_PER_PROMPT = 5;
1048
+ const CALL_GRAPH_EXECUTION_HEADROOM = 1.75;
1049
+
1050
+ export const hasSimulationBindings = (doc, step = null) =>
1051
+ (typeof doc?.$simulation === 'string' && doc.$simulation.trim().length > 0)
1052
+ || (isObject(doc?.simulation) && Object.keys(doc.simulation).length > 0)
1053
+ || (isObject(step?.simulation_overrides) && Object.keys(step.simulation_overrides).length > 0);
1054
+
1055
+ export function analyzeStepCallCost(entryPath, {
1056
+ getPrompt,
1057
+ visible,
1058
+ allowMissingInterfaces = false,
1059
+ hasSimulationPorts = false,
1060
+ onProblem = null,
1061
+ missingInterfaces = null,
1062
+ reachablePrompts = null,
1063
+ }) {
1064
+ const walk = (path, stack = new Set(), proseOnly = false) => {
1065
+ if (stack.has(path)) {
1066
+ if (!proseOnly && onProblem) onProblem('recursive-call-bound', path, '/calls');
1067
+ return 0;
1068
+ }
1069
+ const prompt = getPrompt(path);
1070
+ const iface = prompt?.interface;
1071
+ if (!iface) {
1072
+ if (allowMissingInterfaces && prompt?.error === 'interface-missing') {
1073
+ missingInterfaces?.add(path);
1074
+ reachablePrompts?.add(path);
1075
+ const next = new Set([...stack, path]);
1076
+ const targets = [...new Set(promptMarkdownTargets(prompt.text, path, visible))];
1077
+ const activeChildren = [];
1078
+ for (const target of targets) {
1079
+ const nested = walk(target, next, true);
1080
+ if (nested > 0) activeChildren.push(nested);
1081
+ }
1082
+ const ownBase = hasSimulationPorts || activeChildren.length > 0 || stack.size > 0 ? 2 : 1;
1083
+ return ownBase + activeChildren.reduce((sum, nested) => sum + nested + 1, 0);
1084
+ }
1085
+ if (onProblem) onProblem(prompt?.error ?? 'interface-missing', path, '/interface');
1086
+ return 0;
1087
+ }
1088
+ if (iface.kind === 'native-only') return 0;
1089
+ reachablePrompts?.add(path);
1090
+ if ((!Number.isSafeInteger(iface.limits?.max_model_calls) || iface.limits.max_model_calls < 1) && onProblem) {
1091
+ onProblem('undefined-call-bound', path, '/limits/max_model_calls');
1092
+ }
1093
+ const next = new Set([...stack, path]);
1094
+ let count = 1 + (Array.isArray(iface.resources) ? iface.resources : []).reduce(
1095
+ (sum, resource) => sum + (Array.isArray(resource.operations) ? resource.operations.length : 0),
1096
+ 0,
1097
+ );
1098
+ for (const [index, call] of (Array.isArray(iface.calls) ? iface.calls : []).entries()) {
1099
+ if ((!Number.isSafeInteger(call?.max_calls) || call.max_calls < 1) && onProblem) {
1100
+ onProblem('undefined-call-bound', path, `/calls/${index}/max_calls`);
1101
+ }
1102
+ const nested = walk(call?.target, next, false);
1103
+ if (Number.isSafeInteger(call?.max_calls) && call.max_calls >= 1 && nested > 0) {
1104
+ count += call.max_calls * (nested + 1);
1105
+ }
1106
+ }
1107
+ return count;
1108
+ };
1109
+ return walk(entryPath, new Set(), false);
1110
+ }
1111
+
890
1112
  const stepCount = doc => Array.isArray(doc?.steps) ? doc.steps.length : 0;
1113
+ const positiveInt = value => Number.isSafeInteger(value) && value > 0 ? value : 0;
891
1114
  // Leave room for the whole call graph; the budget is a ceiling, not a charge.
892
- export const defaultMaxCalls = doc => Math.min(1000, Math.max(18, stepCount(doc) * 12));
1115
+ export function defaultMaxCalls(doc, closure = null) {
1116
+ const steps = stepCount(doc);
1117
+ const baseline = Math.max(18, steps * 12);
1118
+ if (steps === 0 || !isObject(closure)) return Math.min(1000, baseline);
1119
+ const estimatedStepCalls = positiveInt(closure.estimatedStepCalls);
1120
+ const missingInterfaces = positiveInt(closure.missingInterfaceCount);
1121
+ const stepPromptCount = positiveInt(closure.stepPromptCount);
1122
+ const perStepNodes = positiveInt(closure.maxChainFanOut) || positiveInt(closure.promptCount);
1123
+ const fanOutBudget = stepPromptCount > 0
1124
+ ? stepPromptCount * CALL_GRAPH_FANOUT_PER_PROMPT
1125
+ : perStepNodes > 0 ? steps * perStepNodes * CALL_GRAPH_FANOUT_PER_PROMPT : 0;
1126
+ const graphBudget = Math.max(Math.ceil(estimatedStepCalls * CALL_GRAPH_EXECUTION_HEADROOM), fanOutBudget)
1127
+ + missingInterfaces * LAZY_INTERFACE_SYNTHESIS_HEADROOM;
1128
+ return Math.min(1000, Math.max(baseline, graphBudget));
1129
+ }
893
1130
 
894
1131
  function firstDifference(testTexts, storyTexts) {
895
1132
  const left = [...storyTexts];
@@ -904,7 +1141,7 @@ function firstDifference(testTexts, storyTexts) {
904
1141
  // Coverage is structural. A negative assertion with an exact calls/world check is checkable.
905
1142
  const exactCheck = check => EXACT_OPS.has(check?.op) || (isObject(check) && Object.hasOwn(check, 'html') && check.op === 'exists');
906
1143
  const ordinaryInexactCheck = check => isObject(check) && ['exists','contains'].includes(check.op)
907
- && ['result','world','calls','error'].includes(check.target) && typeof check.path === 'string'
1144
+ && ['result','world','calls','error','input'].includes(check.target) && typeof check.path === 'string'
908
1145
  && (check.path === '' || check.path.startsWith('/')) && !/~(?![01])/.test(check.path)
909
1146
  && (check.op !== 'contains' || Object.hasOwn(check,'value'));
910
1147
  function criterionPlan(doc, story) {
@@ -979,32 +1216,31 @@ export function promptMarkdownTargets(text, fromPath, visible) {
979
1216
 
980
1217
  // The schema rules of a prompt and of the prompts it calls, all at once (cached per prompt).
981
1218
  export function promptSchemaRefusals(root, found, prompt, prompts, seen = new Set(), { allowMissingInterfaces = false } = {}) {
982
- if (!prompt || seen.has(prompt.path)) return [];
983
- seen.add(prompt.path);
984
- if (prompt.error) {
985
- if (allowMissingInterfaces && prompt.error === 'interface-missing') {
986
- return promptMarkdownTargets(prompt.text, prompt.path, found.visible).flatMap(target => {
987
- if (!prompts.has(target)) prompts.set(target, readPrompt(root, found.visible, target, found.workspace));
988
- return promptSchemaRefusals(root, found, prompts.get(target), prompts, seen, { allowMissingInterfaces });
989
- });
990
- }
991
- return [{ ...promptRefusal(prompt, 'interface'), path: prompt.path }];
992
- }
993
- if (!prompt.interface) return [];
994
- prompt.schemaIssues ??= interfaceSchemaProblems(prompt.interface).map(problem =>
995
- refusal(problem.code, problem.pointer, `${prompt.path} ${problem.pointer} ${problem.rule}`, {path:prompt.path, ...(problem.hint ? {hint:problem.hint} : {})}));
996
- const called = [
997
- ...(Array.isArray(prompt.interface.calls) ? prompt.interface.calls : []).map(call => call?.target).filter(target => typeof target === 'string'),
998
- ...(prompt.frontmatter ? promptMarkdownTargets(prompt.text, prompt.path, found.visible) : []),
999
- ];
1000
- const ownRefusal = prompt.frontmatter || !['draft', 'approved'].includes(prompt.interface.status)
1001
- ? promptRefusal(prompt, 'interface')
1002
- : null;
1003
- const statusProblems = ownRefusal ? [{ ...ownRefusal, path: prompt.path }] : [];
1004
- return [...statusProblems, ...prompt.schemaIssues, ...called.flatMap(target => {
1005
- if (!prompts.has(target)) prompts.set(target, readPrompt(root, found.visible, target,found.workspace));
1006
- return promptSchemaRefusals(root, found, prompts.get(target), prompts, seen, { allowMissingInterfaces });
1007
- })];
1219
+ const visit = (current, contextOnly = false) => {
1220
+ if (!current) return [];
1221
+ const identity = contextOnly ? `context:${current.path}` : current.path;
1222
+ if (seen.has(identity)) return [];
1223
+ seen.add(identity);
1224
+ const load = target => {
1225
+ if (!prompts.has(target)) prompts.set(target, readPrompt(root, found.visible, target, found.workspace));
1226
+ return prompts.get(target);
1227
+ };
1228
+ if (current.error && !(current.error === 'interface-missing' && (contextOnly || allowMissingInterfaces))) {
1229
+ return [{ ...promptRefusal(current, 'interface'), path: current.path }];
1230
+ }
1231
+ const contexts = promptMarkdownTargets(current.text, current.path, found.visible)
1232
+ .flatMap(target => visit(load(target), true));
1233
+ if (!current.interface) return contexts;
1234
+ current.schemaIssues ??= interfaceSchemaProblems(current.interface).map(problem =>
1235
+ refusal(problem.code, problem.pointer, `${current.path} ${problem.pointer} ${problem.rule}`, {path:current.path, ...(problem.hint ? {hint:problem.hint} : {})}));
1236
+ const ownRefusal = current.frontmatter || !['draft', 'approved'].includes(current.interface.status)
1237
+ ? promptRefusal(current, 'interface') : null;
1238
+ const statusProblems = ownRefusal ? [{ ...ownRefusal, path: current.path }] : [];
1239
+ const called = (Array.isArray(current.interface.calls) ? current.interface.calls : [])
1240
+ .flatMap(call => typeof call?.target === 'string' ? visit(load(call.target), contextOnly) : []);
1241
+ return [...statusProblems, ...current.schemaIssues, ...called, ...contexts];
1242
+ };
1243
+ return visit(prompt);
1008
1244
  }
1009
1245
 
1010
1246
  // A refusal that discovery alone proves: a conflict, an unreadable or invalid file, a file over the upload limit,
@@ -1087,6 +1323,329 @@ function stepProblem(step) {
1087
1323
  return null;
1088
1324
  }
1089
1325
  const checkShape = check => isObject(check) && ['criterion_id','target','path','op'].every(key=>Object.hasOwn(check,key));
1326
+ const checkTargets = new Set(['result', 'world', 'calls', 'error', 'input']);
1327
+
1328
+ // Reject only paths whose absence is established by every schema alternative.
1329
+ function resultPathPossible(schema, path) {
1330
+ if (typeof path !== 'string' || path !== '' && (!path.startsWith('/') || /~(?![01])/u.test(path))) return false;
1331
+ const tokens = path === '' ? [] : path.slice(1).split('/').map(token => token.replace(/~1/g, '/').replace(/~0/g, '~'));
1332
+ const literals = node => {
1333
+ if (!isObject(node)) return null;
1334
+ if (Object.hasOwn(node, 'const')) return [exactSchemaValue(node, 'const')];
1335
+ if (Array.isArray(node.enum)) return node.enum.map((_, index) => exactSchemaValue(node.enum, index));
1336
+ if (!Array.isArray(node.oneOf)) return null;
1337
+ const alternatives = node.oneOf.map(literals);
1338
+ return alternatives.every(values => values !== null) ? alternatives.flat() : null;
1339
+ };
1340
+ const together = states => states.includes('miss') ? 'miss' : states.includes('unknown') ? 'unknown' : 'match';
1341
+ // schemaRun handles supported scalar/container constraints. Check oneOf
1342
+ // separately so its early return cannot hide sibling or nested constraints.
1343
+ const membership = (value, node) => {
1344
+ if (!isObject(node)) return 'match';
1345
+ if (unknownKeyword(node)) return 'unknown';
1346
+ let own = node;
1347
+ if (Array.isArray(node.oneOf)) {
1348
+ own = {...node}; delete own.oneOf;
1349
+ if (numberSources.has(node)) numberSources.set(own, numberSources.get(node));
1350
+ }
1351
+ const states = [schemaRun(value, own, [], sameJsonValue).state];
1352
+ if (Array.isArray(node.oneOf)) {
1353
+ const alternatives = node.oneOf.map(variant => membership(value, variant));
1354
+ const fits = alternatives.filter(state => state === 'match').length;
1355
+ states.push(fits > 1 ? 'miss' : alternatives.includes('unknown') ? 'unknown' : fits === 1 ? 'match' : 'miss');
1356
+ }
1357
+ if (Array.isArray(value) && isObject(node.items)) for (const item of value) states.push(membership(item, node.items));
1358
+ if (isObject(value)) for (const [key, child] of Object.entries(value)) {
1359
+ const childSchema = Object.hasOwn(node.properties ?? {}, key) ? node.properties[key] : node.additionalProperties;
1360
+ states.push(membership(child, childSchema));
1361
+ }
1362
+ return together(states);
1363
+ };
1364
+ const addresses = (value, at) => {
1365
+ if (at === tokens.length) return true;
1366
+ const token = tokens[at];
1367
+ if (Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(token)) return false;
1368
+ return value !== null && typeof value === 'object' && Object.hasOwn(value, token) && addresses(value[token], at + 1);
1369
+ };
1370
+ // Prove branch coverage from constraints, never from a sampled value. A
1371
+ // pointer makes each property on its route present. This can make otherwise
1372
+ // distinct optional/required branches overlap for every addressed result.
1373
+ const guaranteed = (nodes, target, at) => {
1374
+ nodes = nodes.filter(isObject);
1375
+ if (!isObject(target)) return true;
1376
+ if (unknownKeyword(target) || Array.isArray(target.oneOf) || typeof target.pattern === 'string') return false;
1377
+ const candidates = nodes.map(literals).find(values => values !== null);
1378
+ if (candidates !== undefined) return candidates.every(value => nodes.some(node => membership(value, node) === 'miss')
1379
+ || !addresses(value, at) || membership(value, target) === 'match');
1380
+ const type = nodes.find(node => typeof node.type === 'string')?.type;
1381
+ if (target.type && type !== target.type && !(type === 'integer' && target.type === 'number')) return false;
1382
+ const lower = key => nodes.reduce((bound,node) => numeric(schemaValue(node,key)) && schemaValue(node,key) > bound ? schemaValue(node,key) : bound, 0);
1383
+ const upper = key => nodes.reduce((bound,node) => numeric(schemaValue(node,key)) && schemaValue(node,key) < bound ? schemaValue(node,key) : bound, Infinity);
1384
+ const objects = nodes.filter(node => node.type === 'object');
1385
+ const required = new Set([...nodes.flatMap(node => node.required ?? []), ...(at < tokens.length && type === 'object' ? [tokens[at]] : [])]);
1386
+ let allowed = null;
1387
+ for (const node of objects) if (node.additionalProperties === false) {
1388
+ const keys = Object.keys(node.properties ?? {});
1389
+ allowed = allowed === null ? new Set(keys) : new Set(keys.filter(key => allowed.has(key)));
1390
+ }
1391
+ // Required fields and the pointer leave no optional key when all object
1392
+ // slots are occupied. This also bounds additionalProperties coverage.
1393
+ if (required.size >= upper('maxProperties')) {
1394
+ allowed = new Set([...required].filter(key => allowed === null || allowed.has(key)));
1395
+ }
1396
+ const childNodes = key => objects.map(node => Object.hasOwn(node.properties ?? {}, key) ? node.properties[key] : node.additionalProperties);
1397
+ for (const [key, value] of Object.entries(target)) {
1398
+ if (SCHEMA_NOTES.has(key) || key === 'type') continue;
1399
+ if (['minLength','minItems','minProperties'].includes(key)) {
1400
+ let minimum = lower(key);
1401
+ if (key === 'minProperties' && required.size > minimum) minimum = required.size;
1402
+ if (key === 'minItems' && at < tokens.length && /^(0|[1-9][0-9]*)$/.test(tokens[at])) {
1403
+ const addressed = BigInt(tokens[at]) + 1n;
1404
+ if (addressed > minimum) minimum = addressed;
1405
+ }
1406
+ if (minimum < schemaValue(target,key)) return false;
1407
+ } else if (['maxLength','maxItems','maxProperties'].includes(key)) {
1408
+ let maximum = upper(key);
1409
+ if (key === 'maxProperties' && allowed !== null && allowed.size < maximum) maximum = allowed.size;
1410
+ if (maximum > schemaValue(target,key)) return false;
1411
+ } else if (key === 'required') {
1412
+ if (value.some(name => !required.has(name))) return false;
1413
+ } else if (key === 'properties') {
1414
+ for (const [name, child] of Object.entries(value)) {
1415
+ if (allowed !== null && !allowed.has(name)) continue;
1416
+ if (!guaranteed(childNodes(name), child, at < tokens.length && tokens[at] === name ? at + 1 : tokens.length)) return false;
1417
+ }
1418
+ } else if (key === 'additionalProperties') {
1419
+ const declared = new Set(Object.keys(target.properties ?? {}));
1420
+ if (value === false) {
1421
+ if (allowed === null || [...allowed].some(name => !declared.has(name))) return false;
1422
+ } else if (isObject(value)) {
1423
+ if (allowed === null && !guaranteed(objects.map(node => node.additionalProperties), value, tokens.length)) return false;
1424
+ const keys = allowed ?? new Set(objects.flatMap(node => Object.keys(node.properties ?? {})));
1425
+ for (const name of keys) if (!declared.has(name) && !guaranteed(childNodes(name), value, tokens.length)) return false;
1426
+ }
1427
+ } else if (key === 'items') {
1428
+ const itemAt = at < tokens.length && tokens[at] === '0' && upper('maxItems') <= 1 ? at + 1 : tokens.length;
1429
+ if (upper('maxItems') !== 0 && !guaranteed(nodes.map(node => node.items), value, itemAt)) return false;
1430
+ } else if (key === 'uniqueItems') {
1431
+ if (value && upper('maxItems') > 1 && !nodes.some(node => node.uniqueItems === true)) return false;
1432
+ } else if (!nodes.some(node => Object.hasOwn(node, key) && sameJsonValue(exactSchemaValue(node,key), exactSchemaValue(target,key)))) return false;
1433
+ }
1434
+ return true;
1435
+ };
1436
+ const visit = (nodes, at, expanded = new Set()) => {
1437
+ nodes = nodes.filter(isObject);
1438
+ if (nodes.some(node => Object.keys(node).some(key => !SCHEMA_RULES.has(key) && !SCHEMA_NOTES.has(key)))) return true;
1439
+ const values = nodes.map(literals).find(candidates => candidates !== null);
1440
+ if (values !== undefined) return values.some(value => nodes.every(node => membership(value, node) !== 'miss') && addresses(value, at));
1441
+ const union = nodes.find(node => Array.isArray(node.oneOf) && !expanded.has(node));
1442
+ if (union) return union.oneOf.some((variant, index) => {
1443
+ const selected = [...nodes, variant];
1444
+ return !union.oneOf.some((other, otherIndex) => index !== otherIndex && guaranteed(selected, other, at))
1445
+ && visit(selected, at, new Set([...expanded, union]));
1446
+ });
1447
+ // Reaching the end of a pointer still requires a value. Intersect known
1448
+ // bounds before accepting a terminal scalar or using it as a sibling/item.
1449
+ if (nodes.some(node => node.type === 'string')) {
1450
+ let minimum = 0, maximum = Infinity;
1451
+ for (const node of nodes) {
1452
+ const lower = schemaValue(node, 'minLength'), upper = schemaValue(node, 'maxLength');
1453
+ if (numeric(lower) && lower > minimum) minimum = lower;
1454
+ if (numeric(upper) && upper < maximum) maximum = upper;
1455
+ }
1456
+ if (minimum > maximum) return false;
1457
+ }
1458
+ if (nodes.some(node => node.type === 'integer' || node.type === 'number')) {
1459
+ let minimum = -Infinity, maximum = Infinity, lowerOpen = false, upperOpen = false;
1460
+ for (const node of nodes) for (const [key, lower, open] of [
1461
+ ['minimum', true, false], ['exclusiveMinimum', true, true],
1462
+ ['maximum', false, false], ['exclusiveMaximum', false, true]
1463
+ ]) {
1464
+ const bound = schemaValue(node, key);
1465
+ if (!numeric(bound)) continue;
1466
+ if (lower) {
1467
+ if (bound > minimum) { minimum = bound; lowerOpen = open; }
1468
+ else if (sameJsonValue(bound, minimum)) lowerOpen ||= open;
1469
+ } else {
1470
+ if (bound < maximum) { maximum = bound; upperOpen = open; }
1471
+ else if (sameJsonValue(bound, maximum)) upperOpen ||= open;
1472
+ }
1473
+ }
1474
+ if (minimum > maximum || sameJsonValue(minimum, maximum) && (lowerOpen || upperOpen)) return false;
1475
+ const multiples = nodes.map(node => schemaValue(node, 'multipleOf')).filter(step => numeric(step) && step > 0);
1476
+ // Safe JSON integers arrive as Numbers. Larger whole values can also
1477
+ // arrive as exact integer tokens; retain every representable spelling.
1478
+ const candidatePossible = value => {
1479
+ let candidates = [value];
1480
+ if (typeof value === 'bigint') {
1481
+ const number = Number(value);
1482
+ if (Number.isSafeInteger(number)) candidates = [number];
1483
+ else if (Number.isFinite(number) && BigInt(number) === value) candidates.push(number);
1484
+ } else if (Number.isInteger(value) && !Number.isSafeInteger(value)) candidates.push(BigInt(value));
1485
+ return candidates.some(candidate => nodes.every(node => membership(candidate, node) !== 'miss'));
1486
+ };
1487
+ if (nodes.some(node => node.type === 'integer')) {
1488
+ const endpoint = (bound, lower, open) => {
1489
+ if (typeof bound === 'number' && !Number.isFinite(bound)) return bound;
1490
+ const whole = typeof bound === 'bigint' ? bound : BigInt(lower ? Math.ceil(bound) : Math.floor(bound));
1491
+ return open && (typeof bound === 'bigint' || Number.isInteger(bound)) ? whole + (lower ? 1n : -1n) : whole;
1492
+ };
1493
+ const first = endpoint(minimum, true, lowerOpen), last = endpoint(maximum, false, upperOpen);
1494
+ if (first > last) return false;
1495
+ // Bound the proof cost. Wider/unbounded domains remain unproven.
1496
+ if (multiples.length && typeof first === 'bigint' && typeof last === 'bigint' && last - first < 1024n) {
1497
+ let possible = false;
1498
+ for (let value = first; value <= last; value += 1n) if (candidatePossible(value)) { possible = true; break; }
1499
+ if (!possible) return false;
1500
+ }
1501
+ } else if (multiples.length) {
1502
+ if (sameJsonValue(minimum, maximum)) {
1503
+ if ((typeof minimum === 'bigint' || Number.isFinite(minimum)) && !candidatePossible(minimum)) return false;
1504
+ } else if (typeof minimum === 'number' && typeof maximum === 'number'
1505
+ && minimum >= Number.MIN_SAFE_INTEGER && maximum <= Number.MAX_SAFE_INTEGER) {
1506
+ // For ordinary Numbers, division is monotone. Widen its quotient
1507
+ // interval by the existing membership tolerance and rounding slack.
1508
+ // Include open endpoints: an overapproximation can prove absence.
1509
+ for (const step of multiples) if (typeof step === 'number' && Number.isFinite(step)) {
1510
+ const first = minimum / step, last = maximum / step;
1511
+ if (!Number.isFinite(first) || !Number.isFinite(last)) continue;
1512
+ const slack = 1e-9 + 8 * Number.EPSILON * Math.max(1, Math.abs(first), Math.abs(last));
1513
+ if (Math.ceil(first - slack) > Math.floor(last + slack)) return false;
1514
+ }
1515
+ }
1516
+ }
1517
+ }
1518
+ const token = tokens[at], children = [];
1519
+ if (nodes.some(node => node.type === 'object')) {
1520
+ // The addressed property consumes one slot alongside every required
1521
+ // sibling. All selected oneOf and sibling constraints apply together.
1522
+ const required = new Set([...(at < tokens.length ? [token] : []), ...nodes.flatMap(node => node.required ?? [])]);
1523
+ let minimum = required.size, maximum = Infinity, allowed = null;
1524
+ for (const node of nodes) {
1525
+ const lower = schemaValue(node, 'minProperties'), upper = schemaValue(node, 'maxProperties');
1526
+ if (numeric(lower) && lower > minimum) minimum = lower;
1527
+ if (numeric(upper) && upper < maximum) maximum = upper;
1528
+ if (node.additionalProperties === false) {
1529
+ const keys = new Set(Object.keys(node.properties ?? {}));
1530
+ allowed = allowed === null ? keys : new Set([...allowed].filter(key => keys.has(key)));
1531
+ }
1532
+ }
1533
+ if (allowed !== null && ([...required].some(key => !allowed.has(key)) || minimum > allowed.size)) return false;
1534
+ if (minimum > maximum) return false;
1535
+ const objects = nodes.filter(node => node.type === 'object');
1536
+ const propertyPossible = key => {
1537
+ const schemas = [];
1538
+ for (const node of objects) {
1539
+ if (Object.hasOwn(node.properties ?? {}, key)) schemas.push(node.properties[key]);
1540
+ else if (node.additionalProperties === false) return false;
1541
+ else schemas.push(node.additionalProperties);
1542
+ }
1543
+ return visit(schemas, tokens.length);
1544
+ };
1545
+ // Required siblings need values even when the pointer follows another
1546
+ // field. Optional fields supply capacity only when their values can exist.
1547
+ if ([...required].some(key => !propertyPossible(key))) return false;
1548
+ if (allowed === null && !visit(objects.map(node => node.additionalProperties), tokens.length)) {
1549
+ allowed = new Set(objects.flatMap(node => Object.keys(node.properties ?? {})));
1550
+ }
1551
+ if (allowed !== null && minimum > required.size) {
1552
+ let capacity = required.size;
1553
+ for (const key of allowed) if (!required.has(key) && propertyPossible(key)) {
1554
+ capacity += 1;
1555
+ if (capacity >= minimum) break;
1556
+ }
1557
+ if (capacity < minimum) return false;
1558
+ }
1559
+ }
1560
+ if (nodes.some(node => node.type === 'array')) {
1561
+ let minimum = 0, maximum = Infinity;
1562
+ for (const node of nodes) {
1563
+ const lower = schemaValue(node, 'minItems'), upper = schemaValue(node, 'maxItems');
1564
+ if (numeric(lower) && lower > minimum) minimum = lower;
1565
+ if (numeric(upper) && upper < maximum) maximum = upper;
1566
+ }
1567
+ if (at < tokens.length) {
1568
+ if (!/^(0|[1-9][0-9]*)$/.test(token)) return false;
1569
+ const addressed = BigInt(token) + 1n;
1570
+ if (addressed > minimum) minimum = addressed;
1571
+ }
1572
+ if (minimum > maximum) return false;
1573
+ const items = nodes.map(node => node.items).filter(isObject);
1574
+ if (minimum > 0 && !visit(items, tokens.length)) return false;
1575
+ if (nodes.some(node => node.uniqueItems === true) && !items.some(node => unknownKeyword(node))) {
1576
+ const candidates = items.map(literals).find(values => values !== null);
1577
+ if (candidates !== undefined) {
1578
+ // This is an upper capacity: unknown membership keeps a candidate.
1579
+ // Numeric equality includes signed zero and exact integer tokens.
1580
+ const possible = candidates.filter(value => items.every(node => membership(value, node) !== 'miss'));
1581
+ const distinct = possible.filter((value, index) => possible.findIndex(other => sameJsonValue(value, other)) === index);
1582
+ if (minimum > distinct.length) return false;
1583
+ }
1584
+ }
1585
+ }
1586
+ if (at === tokens.length) return true;
1587
+ for (const node of nodes) {
1588
+ if (node.type === 'object') {
1589
+ if (isObject(node.properties) && Object.hasOwn(node.properties, token)) children.push(node.properties[token]);
1590
+ else if (node.additionalProperties === false) return false;
1591
+ else children.push(node.additionalProperties);
1592
+ } else if (node.type === 'array') {
1593
+ if (!/^(0|[1-9][0-9]*)$/.test(token)) return false;
1594
+ if (numeric(schemaValue(node, 'maxItems')) && BigInt(token) >= schemaValue(node, 'maxItems')) return false;
1595
+ children.push(node.items);
1596
+ } else if (['null', 'boolean', 'string', 'integer', 'number'].includes(node.type)) return false;
1597
+ }
1598
+ return visit(children, at + 1);
1599
+ };
1600
+ return visit([schema], 0);
1601
+ }
1602
+
1603
+ function computeBindingRefusal(doc, step, index, prompts, storySource) {
1604
+ const plan = buildBindingPlan({test:{path:'',storyPath:doc.story_path,doc:{...doc,steps:[step]}}, storyText:storySource,
1605
+ // Source capture has not validated the Story boundary yet. Mandatory
1606
+ // compute admission follows actual entry/call reachability independently.
1607
+ boundaryState:{boundary:null,notes:[]},
1608
+ prompts:new Map([...prompts].map(([path, prompt]) => [path, prompt.interface]))});
1609
+ // Binding advice is conservative for called modules. Admission follows the
1610
+ // operations actually invoked, including multiple operations of one module.
1611
+ const required = new Map(), seen = new Set(), pending = [[step.entry_path, step.operation]];
1612
+ for (let at = 0; at < pending.length; at++) {
1613
+ const [path, operation] = pending[at], identity = JSON.stringify([path, operation]);
1614
+ if (seen.has(identity)) continue;
1615
+ seen.add(identity);
1616
+ const iface = prompts.get(path)?.interface;
1617
+ if (!iface) continue;
1618
+ const entries = Array.isArray(iface.entries) ? iface.entries : [];
1619
+ const declared = new Set((iface.resources ?? []).flatMap(resource => (resource.operations ?? [])
1620
+ .map(member => `${resource.name}.${member.name}`)));
1621
+ const selected = entries.filter(entry => entry.operation === operation);
1622
+ const complete = selected.length === 1 && entries.every(entry => typeof entry.operation === 'string' && entry.operation
1623
+ && Array.isArray(entry.resource_operations) && entry.resource_operations.every(key => declared.has(key))
1624
+ && new Set(entry.resource_operations).size === entry.resource_operations.length)
1625
+ && new Set(entries.map(entry => entry.operation)).size === entries.length
1626
+ && new Set(entries.flatMap(entry => entry.resource_operations)).size === declared.size;
1627
+ const active = complete ? selected[0].resource_operations : null;
1628
+ if (active === null) required.set(path, null);
1629
+ else if (!required.has(path)) required.set(path, new Set(active));
1630
+ else if (required.get(path) !== null) for (const key of active) required.get(path).add(key);
1631
+ for (const call of iface.calls ?? []) if (typeof call.target === 'string') pending.push([call.target, call.target_operation]);
1632
+ }
1633
+ const simulation = {...(isObject(doc.simulation) ? doc.simulation : {})};
1634
+ if (Array.isArray(step.simulation_overrides)) {
1635
+ for (const row of step.simulation_overrides) if (typeof row?.operation === 'string') simulation[row.operation] = row.binding;
1636
+ } else if (isObject(step.simulation_overrides)) Object.assign(simulation, step.simulation_overrides);
1637
+ for (const edge of plan.edges) {
1638
+ if (!required.has(edge.prompt_path) || required.get(edge.prompt_path) !== null && !required.get(edge.prompt_path).has(edge.key)) continue;
1639
+ const resource = prompts.get(edge.prompt_path)?.interface?.resources?.find(item => item?.name === edge.resource);
1640
+ if (resource?.kind !== 'compute') continue;
1641
+ const binding = Object.hasOwn(simulation, edge.key) ? simulation[edge.key] : null;
1642
+ if (isObject(binding) && binding.action === 'compute') continue;
1643
+ return refusal(binding == null ? 'simulation-binding-missing' : 'invalid-simulation-binding', `steps[${index}].simulation`,
1644
+ `${edge.prompt_path} requires a simulation binding for ${edge.key} with action "compute".`,
1645
+ {step:index + 1,path:edge.prompt_path,hint:`Add or repair simulation["${edge.key}"] with action "compute", or its effective step override.`});
1646
+ }
1647
+ return null;
1648
+ }
1090
1649
  function appMapsRefusal(doc) {
1091
1650
  if (!Object.hasOwn(doc,'app_maps')) return null;
1092
1651
  if (!Array.isArray(doc.app_maps)) return refusal('invalid-app-maps','app_maps','app_maps must be a list of repository-relative paths.');
@@ -1113,6 +1672,16 @@ function documentRefusal(doc, path, { allowOmittedCriteria = false } = {}) {
1113
1672
  return appMapsRefusal(doc);
1114
1673
  }
1115
1674
 
1675
+ export function scenarioDerivationRefusal(doc) {
1676
+ for (const [index, step] of (Array.isArray(doc?.steps) ? doc.steps : []).entries()) {
1677
+ for (const [at, check] of (Array.isArray(step?.checks) ? step.checks : []).entries()) {
1678
+ const problem = checkDerivation(check);
1679
+ if (problem) return refusal(problem.code, `steps[${index}].checks[${at}].derivation`, problem.message, { step: index + 1 });
1680
+ }
1681
+ }
1682
+ return null;
1683
+ }
1684
+
1116
1685
  export function scenarioShapeRefusal(doc,path) {
1117
1686
  const broken=documentRefusal(doc,path);if(broken)return broken;
1118
1687
  if (!Array.isArray(doc.criteria)||!doc.criteria.length) return refusal('invalid-criterion','criteria','The test has no criteria.');
@@ -1134,10 +1703,187 @@ export function scenarioShapeRefusal(doc,path) {
1134
1703
  if(!ids.has(check.criterion_id))return refusal('unknown-criterion',`${section}.checks[${at}]`,`The check names ${show(check.criterion_id)}, which is not a criterion ID.`);
1135
1704
  }
1136
1705
  }
1706
+ return scenarioDerivationRefusal(doc);
1707
+ }
1708
+
1709
+ // A diagnostic projection changes effective inputs only; authored files keep their identity.
1710
+ function selectDiagnosticSteps(doc, stepIds) {
1711
+ if (!Array.isArray(doc.steps) || !doc.steps.length) return {refusal:refusal('missing-steps', 'steps', 'The test has no steps.')};
1712
+ const available = (Array.isArray(doc.steps) ? doc.steps : []).map(step => step?.step_id).filter(id => typeof id === 'string');
1713
+ const requested = new Set(stepIds), unknown = [...requested].filter(id => !available.includes(id));
1714
+ if (unknown.length) return { refusal: refusal('step-unknown', 'steps', `Unknown step_id: ${unknown.join(', ')}. Available step_id values: ${available.join(', ')}.`) };
1715
+ if (new Set(available).size !== available.length) return { refusal: refusal('invalid-step', 'steps', 'Diagnostic selection requires unique step_id values.') };
1716
+ const steps = doc.steps.filter(step => requested.has(step?.step_id));
1717
+ const selected = new Set(steps.map(step => step.step_id));
1718
+ const stateful = [doc.initial_world, doc.simulation, doc.$simulation].some(value => value && typeof value === 'object' && Object.keys(value).length > 0);
1719
+ const last = Math.max(...steps.map(step => doc.steps.indexOf(step)));
1720
+ if (stateful && doc.steps.slice(0, last).some(step => !selected.has(step?.step_id))) {
1721
+ return { refusal: refusal('step-prerequisite-omitted', 'steps', 'Selected steps use world or simulation data; include every earlier step explicitly.') };
1722
+ }
1723
+ let omitted = null;
1724
+ const visit = value => {
1725
+ if (!value || typeof value !== 'object') return;
1726
+ const reference = value.$step_result;
1727
+ if (isObject(value) && Object.keys(value).length === 1 && isObject(reference)
1728
+ && Object.keys(reference).length === 2 && typeof reference.step_id === 'string' && typeof reference.path === 'string') {
1729
+ if (!selected.has(reference.step_id)) omitted ??= reference.step_id;
1730
+ return;
1731
+ }
1732
+ for (const item of Object.values(value)) visit(item);
1733
+ };
1734
+ for (const step of steps) visit(step.input);
1735
+ if (omitted !== null) return { refusal: refusal('step-prerequisite-omitted', 'steps', `Selected steps reference omitted step_id ${omitted}. Include that prerequisite explicitly.`) };
1736
+ const criterionIds = new Set(steps.flatMap(step => Array.isArray(step.checks) ? step.checks.map(check => check?.criterion_id) : []));
1737
+ return { doc: { ...doc, steps, criteria: doc.criteria.filter(item => criterionIds.has(item.id)) } };
1738
+ }
1739
+
1740
+ function diagnosticStoryText(source, criteria) {
1741
+ const retained = new Map(), heading = AC_HEADING.exec(source);
1742
+ for (const item of criteria) retained.set(item.text, (retained.get(item.text) ?? 0) + 1);
1743
+ const offset = heading ? heading.index + heading[0].length : 0, body = source.slice(offset);
1744
+ if (!numberedStoryCriteria(source).length) {
1745
+ if (!heading) return source;
1746
+ const nextHeading = NEXT_HEADING.exec(body), end = nextHeading?.index ?? body.length;
1747
+ const section = body.slice(0, end);
1748
+ const items = [...section.matchAll(BULLET_ITEM)];
1749
+ const trailingBoundary = /^```pdd-boundary\r?\n[\s\S]*?^```(?=\r?$)/m.exec(section);
1750
+ // Bullet admission can include trailing authority in the final criterion.
1751
+ // Keep that exact text when selected, or move its complete authored tail
1752
+ // beyond the acceptance terminator when omitted. Never duplicate a marker.
1753
+ if (trailingBoundary && trailingBoundary.index >= items.at(-1)?.index && runtimeBoundary('', source)) {
1754
+ const prefix = source.slice(0, offset) + section.slice(0, items[0].index);
1755
+ let fence = null;
1756
+ for (const line of prefix.split(/\r?\n/)) {
1757
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1758
+ if (!fence && match) fence = match[1];
1759
+ else if (fence && match && match[1][0] === fence[0] && match[1].length >= fence.length && !match[2].trim()) fence = null;
1760
+ }
1761
+ let projected = '', removedFences = '', omittedTail = '', cursor = items[0].index;
1762
+ let retainedTail = false;
1763
+ for (const item of items) {
1764
+ projected += section.slice(cursor, item.index);
1765
+ cursor = item.index + item[0].length;
1766
+ const tailAt = trailingBoundary.index - item.index;
1767
+ const hasTail = tailAt >= 0 && tailAt < item[0].length;
1768
+ const head = hasTail ? item[0].slice(0, tailAt) : item[0];
1769
+ const tail = hasTail ? item[0].slice(tailAt) : '';
1770
+ const text = pyWords(item[1]);
1771
+ if (retained.get(text) > 0) {
1772
+ retained.set(text, retained.get(text) - 1);
1773
+ // Continuation indentation does not change bullet criterion text.
1774
+ // Prevent its example delimiters from enclosing the real declaration.
1775
+ projected += head + tail;
1776
+ retainedTail ||= hasTail;
1777
+ } else {
1778
+ projected += item[0].match(/\s*$/)[0];
1779
+ removedFences += [...head.matchAll(/^ {0,3}(?:`{3,}|~{3,})[^\r\n]*/gm)].map(match => match[0] + '\n').join('');
1780
+ omittedTail += tail;
1781
+ }
1782
+ }
1783
+ const guard = '~'.repeat([...removedFences.matchAll(/~+/g)].reduce((length, match) => Math.max(length, match[0].length + 1), 3));
1784
+ const tailAt = retainedTail ? projected.indexOf(trailingBoundary[0]) : projected.length;
1785
+ const head = projected.slice(0, tailAt), tail = projected.slice(tailAt);
1786
+ const html = [...head.matchAll(/<(?:[!?]|\/?[A-Za-z])/g)].at(-1);
1787
+ // Protect literal HTML as authored code. When the final criterion also
1788
+ // contains the boundary, its existing closer must end the protection:
1789
+ // inserting another closer there would change the exact criterion text.
1790
+ const closer = html && retainedTail
1791
+ ? [...head.matchAll(/^ {0,3}(`{3,}|~{3,})[ \t]*(?=\r?$)/gm)].findLast(match => match.index > html.index)
1792
+ : null;
1793
+ const enclosure = html ? closer?.[1] ?? '~'.repeat([...head.matchAll(/~+/g)].reduce((length, match) => Math.max(length, match[0].length + 1), 3)) : '';
1794
+ projected = head.replace(/^ {0,3}(?:`{3,}|~{3,})[^\r\n]*/gm, (line, at) => at === closer?.index ? line : ' ' + line) + tail;
1795
+ return prefix + (fence ? '\n' + fence + '\n\n' : '') + (enclosure ? enclosure + '\n' : '') + projected
1796
+ + '\n\n## Diagnostic acceptance boundary\n\n' + (enclosure && !retainedTail ? enclosure + '\n\n' : '')
1797
+ + (removedFences ? guard + '\n' + removedFences + guard + '\n\n' : '') + omittedTail + body.slice(end);
1798
+ }
1799
+ let projected = '', cursor = 0, removedFences = '';
1800
+ for (const match of section.matchAll(BULLET_ITEM)) {
1801
+ projected += section.slice(cursor, match.index);
1802
+ const text = pyWords(match[1]);
1803
+ if (retained.get(text) > 0) {
1804
+ retained.set(text, retained.get(text) - 1);
1805
+ projected += match[0];
1806
+ } else {
1807
+ projected += match[0].match(/\s*$/)[0];
1808
+ for (const line of match[0].matchAll(/^ {0,3}(?:`{3,}|~{3,})[^\r\n]*/gm)) {
1809
+ const start = match.index + line.index, finish = start + line[0].length;
1810
+ const before = section.slice(start - 2, start) === '\r\n' ? '\r\n' : '\n';
1811
+ const after = section.slice(finish, finish + 2) === '\r\n' ? '\r\n' : section[finish] === '\n' ? '\n' : '';
1812
+ removedFences += before + line[0] + after;
1813
+ }
1814
+ }
1815
+ cursor = match.index + match[0].length;
1816
+ }
1817
+ // A numbered terminator would suppress the engine's bullet fallback.
1818
+ const acceptance = projected + section.slice(cursor) + '\n\n## Diagnostic acceptance boundary\n\n';
1819
+ if (!removedFences) return source.slice(0, offset) + acceptance + body.slice(end);
1820
+ // A retained declaration inside the parsed criterion must keep its own
1821
+ // top-level context; do not put that declaration inside a new fence.
1822
+ if (/[`~]{3,}[ \t]*pdd-boundary\b/.test(section)) {
1823
+ return source.slice(0, offset) + acceptance + removedFences + '\n' + body.slice(end);
1824
+ }
1825
+ // Bullet parsing consumes delimiter lines as criterion text. Retain removed
1826
+ // delimiters after its terminator and isolate the projected section, then
1827
+ // restore the authored fence state before the untouched supporting context.
1828
+ const fenceAfter = text => {
1829
+ let fence = null;
1830
+ for (const line of text.split(/\r?\n/)) {
1831
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1832
+ if (!fence && match) fence = match[1];
1833
+ else if (fence && match && match[1][0] === fence[0] && match[1].length >= fence.length && !match[2].trim()) fence = null;
1834
+ }
1835
+ return fence;
1836
+ };
1837
+ const prefix = source.slice(0, offset), before = fenceAfter(prefix), after = fenceAfter(prefix + section);
1838
+ const guard = '~'.repeat([...section.matchAll(/~+/g)].reduce((length, match) => Math.max(length, match[0].length + 1), 3));
1839
+ return prefix + '\n\n' + (before ? before + '\n\n' : '') + guard + '\n'
1840
+ + acceptance + removedFences + '\n' + guard + '\n\n' + (after ? after + '\n\n' : '') + body.slice(end);
1841
+ }
1842
+ // Numbered criteria use Python splitlines even when the LF-only heading
1843
+ // pattern falls back to scanning the whole Story. Keep each authored ending.
1844
+ const lines = body.match(/[^\n\r\v\f\x1c-\x1e\x85\u2028\u2029]*(?:\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029]|$)/g).filter(Boolean);
1845
+ const lineText = line => line.replace(/(?:\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029])$/, '');
1846
+ let next = 1, seen = 1, boundary = 0;
1847
+ for (let index = 0; index < lines.length; index++) {
1848
+ const match = NUMBERED_ITEM.exec(lineText(lines[index]));
1849
+ if (!match || Number(match[1]) !== seen) {
1850
+ if (match && seen > 1) break;
1851
+ continue;
1852
+ }
1853
+ seen += 1;
1854
+ let end = index + 1;
1855
+ while (end < lines.length && pyStrip(lineText(lines[end])) && !lineText(lines[end]).startsWith('#') && !NUMBERED_ITEM.test(lineText(lines[end]))) end += 1;
1856
+ // Later criteria can follow prose; the trailing authored suffix starts here.
1857
+ boundary = end;
1858
+ const text = [match[2], ...lines.slice(index + 1, end).map(lineText)].map(pyStrip).join(' ');
1859
+ if (retained.get(text) > 0) {
1860
+ retained.set(text, retained.get(text) - 1);
1861
+ lines[index] = lines[index].replace(/^[1-9][0-9]*/, String(next++));
1862
+ }
1863
+ else for (let at = index; at < end; at++) {
1864
+ const authored = lineText(lines[at]);
1865
+ // A criterion can end inside a fence whose remaining lines are authored
1866
+ // context. Keep its delimiters and line separation so that context and
1867
+ // a later boundary retain their original fence state.
1868
+ if (!/^ {0,3}(?:`{3,}|~{3,})/.test(authored)) lines[at] = lines[at].slice(authored.length);
1869
+ }
1870
+ index = end - 1;
1871
+ }
1872
+ // The engine's sequential-number parser needs an explicit mismatch to stop
1873
+ // before numbered examples without changing authored fence or HTML state.
1874
+ const terminator = '\n\n1. End of diagnostic acceptance criteria.\n\n';
1875
+ return source.slice(0, offset) + lines.slice(0, boundary).join('') + terminator + lines.slice(boundary).join('');
1876
+ }
1877
+
1878
+ function diagnosticStoryProjectionRefusal(path, source, projected) {
1879
+ const boundary = runtimeBoundary(path, source);
1880
+ if (boundary !== null && !isDeepStrictEqual(runtimeBoundary(path, projected), boundary)) {
1881
+ return refusal('step-story-projection', 'story_path', `${path}: selected criteria cannot preserve their exact text and authored Runtime boundary. Put supporting context and the boundary after a separate heading, or include the criterion that supplies the required fence closer.`);
1882
+ }
1137
1883
  return null;
1138
1884
  }
1139
1885
 
1140
- function checkTest(root, found, test, prompts, { allowMissingInterfaces = false } = {}) {
1886
+ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false, executablePaths = new Set(prompts.keys()), localLint = false, stepIds = [] } = {}) {
1141
1887
  let doc = test.doc;
1142
1888
  if (!test.error && isObject(doc)) {
1143
1889
  const prepared = preparedText(root,found.visible,test.path,readText(root,test.path),'scenario');
@@ -1147,6 +1893,8 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1147
1893
  if (test.error) return done(discoveryRefusal(test));
1148
1894
  const shape = documentRefusal(doc, test.path, { allowOmittedCriteria: true });
1149
1895
  if (shape) return done(shape);
1896
+ const derivation = scenarioDerivationRefusal(doc);
1897
+ if (derivation) return done(derivation);
1150
1898
  if (typeof doc.story_path !== 'string' || !doc.story_path) return done(refusal('pdd-no-story', 'story_path', 'The test has no story_path. Name its story, for example "user_stories/<story>.md".'));
1151
1899
  if (!found.visible.has(doc.story_path)) return done(refusal('story-missing', 'story_path', `${doc.story_path} is not a Git-visible file.`));
1152
1900
  if (test.storyPath && doc.story_path !== test.storyPath) return done(discoveryRefusal({ ...test, doc }));
@@ -1155,12 +1903,20 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1155
1903
  const resolved = resolveScenarioCriteria(doc, storySource);
1156
1904
  if (resolved.refusal) return done(resolved.refusal);
1157
1905
  doc = resolved.doc;
1158
- const ids = new Set(doc.criteria.map(item => item.id));
1159
- const story = storyCriteria(storySource);
1906
+ let story = storyCriteria(storySource);
1160
1907
  if (!story.length) return done(refusal('story-criteria-missing', 'story_path', `${doc.story_path} has no numbered "## Acceptance criteria" list.`), story);
1161
1908
  const testTexts = doc.criteria.map(item => item.text).sort(), storyTexts = [...story].sort();
1162
1909
  if (!isDeepStrictEqual(testTexts, storyTexts) && !criterionPlan(doc, story)) return done(refusal('story-criterion-mismatch', 'criteria', firstDifference(testTexts, storyTexts)), story);
1163
1910
  if (!Array.isArray(doc.steps) || !doc.steps.length) return done(refusal('missing-steps', 'steps', 'The test has no steps.'), story);
1911
+ if (stepIds.length) {
1912
+ const selection = selectDiagnosticSteps(doc, stepIds);
1913
+ if (selection.refusal) return done(selection.refusal, story);
1914
+ const projectionIssue = diagnosticStoryProjectionRefusal(doc.story_path, storySource, diagnosticStoryText(storySource, selection.doc.criteria));
1915
+ if (projectionIssue) return done(projectionIssue, story);
1916
+ doc = selection.doc;
1917
+ story = doc.criteria.map(item => item.text);
1918
+ }
1919
+ const ids = new Set(doc.criteria.map(item => item.id));
1164
1920
  const exact = new Set(), inputIssues = [];
1165
1921
  for (const [index, step] of doc.steps.entries()) {
1166
1922
  const section = `steps[${index}]`, at = { step: index + 1 };
@@ -1176,28 +1932,100 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1176
1932
  const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
1177
1933
  const broken = lazyMissing ? null : promptRefusal(prompt, section);
1178
1934
  if (broken) return done({ ...broken, ...at }, story);
1179
- const schemaIssues = promptSchemaRefusals(root, found, prompt, prompts, new Set(), { allowMissingInterfaces });
1935
+ const schemaIssues = promptSchemaRefusals(root, found, prompt, prompts, new Set(), { allowMissingInterfaces })
1936
+ .filter(problem => !localLint || !problem.code?.startsWith('graph-schema-'));
1180
1937
  if (schemaIssues.length) return done(schemaIssues, story);
1181
1938
  const entry = lazyMissing ? null : (Array.isArray(prompt.interface.entries) ? prompt.interface.entries : []).find(item => item?.operation === step.operation);
1182
- const native = [...prompts.values()].some(item => item.interface?.kind === 'native-only');
1939
+ const native = [...executablePaths].some(path => prompts.get(path)?.interface?.kind === 'native-only');
1183
1940
  if (!lazyMissing && !entry && !native) return done(refusal('entry-operation-missing', section, `${step.entry_path} has no operation "${step.operation}".`, at), story);
1184
1941
  const errorStep = Object.hasOwn(step, 'expected_error');
1185
1942
  if (!lazyMissing && !native && errorStep && !(Array.isArray(entry.errors) && entry.errors.includes(step.expected_error))) {
1186
1943
  return done(refusal('pdd-unknown-error', `${section}.expected_error`, `"${step.expected_error}" is not in the errors of ${step.operation} in ${step.entry_path}.`, at), story);
1187
1944
  }
1188
1945
  if (!Array.isArray(step.checks)) return done(refusal('invalid-check', `${section}.checks`, 'checks must be a list.', at), story);
1189
- let errorChecks = 0;
1946
+ let errorChecks = 0, resultWithErrorRefusal = null;
1190
1947
  for (const [checkIndex, check] of step.checks.entries()) {
1191
1948
  if (!checkShape(check)) {
1192
1949
  return done(refusal('invalid-check', `${section}.checks[${checkIndex}]`, 'A check has criterion_id, target, path and op.', at), story);
1193
1950
  }
1194
- if (!ids.has(check.criterion_id)) return done(refusal('unknown-criterion', `${section}.checks[${checkIndex}]`, `The check names ${show(check.criterion_id)}, which is not a criterion ID.`, at), story);
1951
+ const checkSection = `${section}.checks[${checkIndex}]`;
1952
+ const extraKeys = Object.keys(check).filter(key => !CHECK_KEYS.has(key)).sort();
1953
+ if (extraKeys.length) {
1954
+ const isPredicate = typeof check.op === 'string' && (RULE_OPS.has(check.op) || check.op === 'integer_relation');
1955
+ return done(refusal(
1956
+ isPredicate ? 'invalid-predicate' : 'invalid-check',
1957
+ checkSection,
1958
+ isPredicate
1959
+ ? `The check predicate has unsupported keys: ${extraKeys.map(show).join(', ')}.`
1960
+ : `The check has unknown keys: ${extraKeys.map(show).join(', ')}.`,
1961
+ at,
1962
+ ), story);
1963
+ }
1964
+ if (typeof check.target !== 'string' || !checkTargets.has(check.target)) {
1965
+ const message = check.target === 'output'
1966
+ ? 'A check target must be "result", "world", "calls", "error" or "input". Use target "result" to check a step\'s returned output.'
1967
+ : 'A check target must be "result", "world", "calls", "error" or "input".';
1968
+ return done(refusal('invalid-check', checkSection, message, at), story);
1969
+ }
1970
+ if (typeof check.op !== 'string' || !CHECK_OPS.has(check.op)) {
1971
+ return done(refusal(
1972
+ 'unsupported-check',
1973
+ checkSection,
1974
+ `Unsupported check op ${show(check.op)}. Supported ops: ${[...CHECK_OPS].sort().join(', ')}.`,
1975
+ at,
1976
+ ), story);
1977
+ }
1978
+ if (check.target === 'calls' || check.target === 'error') {
1979
+ const allowed = [...(check.target === 'calls' ? CALLS_OPS : ERROR_OPS)].join(', ');
1980
+ if (hasCheckRef(check)) {
1981
+ return done(refusal(
1982
+ 'unsupported-check',
1983
+ checkSection,
1984
+ `Cross-path reference checks (ref_target/ref_path) apply only to "result", "world", and "input" targets, not "${check.target}".`,
1985
+ { ...at, hint: `Check target "result", "world", or "input", or use a literal value with an op supported for "${check.target}" (${allowed}).` },
1986
+ ), story);
1987
+ }
1988
+ if (RULE_OPS.has(check.op) || check.op === 'integer_relation') {
1989
+ return done(refusal(
1990
+ 'unsupported-check',
1991
+ checkSection,
1992
+ `Check op "${check.op}" applies only to "result", "world", and "input" targets; target "${check.target}" supports ${allowed}.`,
1993
+ { ...at, hint: `Change target to "result", "world", or "input", or use a supported op for "${check.target}" (${allowed}).` },
1994
+ ), story);
1995
+ }
1996
+ if (check.op === 'contains') {
1997
+ return done(refusal(
1998
+ 'invalid-contains',
1999
+ checkSection,
2000
+ `Check op "contains" applies only to "result", "world", and "input" targets, not "${check.target}".`,
2001
+ { ...at, hint: `Change target to "result", "world", or "input", or use a supported op for "${check.target}" (${allowed}).` },
2002
+ ), story);
2003
+ }
2004
+ if (check.target === 'calls' && check.op === 'exists') {
2005
+ return done(refusal(
2006
+ 'invalid-call-check',
2007
+ checkSection,
2008
+ 'Target "calls" does not support op "exists"; it supports count, equals, not_equals, and one_of.',
2009
+ { ...at, hint: 'Use "equals" with an integer call count (including 0) on /internal/<id> or /resources/<id>, or "count" on /internal or /resources.' },
2010
+ ), story);
2011
+ }
2012
+ }
2013
+ if (check.target === 'result' && errorStep) resultWithErrorRefusal ??= refusal('invalid-check', checkSection, 'A step with expected_error cannot check a successful result. Check the error instead.', at);
2014
+ if (check.target === 'result' && entry?.result_schema && !resultPathPossible(entry.result_schema, check.path)) {
2015
+ return done(refusal('invalid-check', `${checkSection}.path`, `${show(check.path)} cannot address a value in the result schema of ${step.operation} in ${step.entry_path}.`, at), story);
2016
+ }
2017
+ if (typeof check.criterion_id !== 'string' || !ids.has(check.criterion_id)) return done(refusal('unknown-criterion', `${section}.checks[${checkIndex}]`, `The check names ${show(check.criterion_id)}, which is not a criterion ID.`, at), story);
1195
2018
  if (EXACT_OPS.has(check.op) || (Object.hasOwn(check, 'html') && check.op === 'exists')) exact.add(check.criterion_id);
1196
2019
  if (check.target === 'error' && check.path === '/code' && check.op === 'equals' && check.value === step.expected_error) errorChecks += 1;
1197
2020
  }
1198
2021
  if (errorStep && errorChecks === 0) {
1199
2022
  return done(refusal('missing-error-check', `${section}.checks`, `An error step needs one check: target "error", path "/code", op "equals", value "${step.expected_error}".`, at), story);
1200
2023
  }
2024
+ if (resultWithErrorRefusal) return done(resultWithErrorRefusal, story);
2025
+ if (!native) {
2026
+ const bindingIssue = computeBindingRefusal(doc, step, index, prompts, storySource);
2027
+ if (bindingIssue) return done(bindingIssue, story);
2028
+ }
1201
2029
  if (!lazyMissing && !native) inputIssues.push(...checkInput(step.input, entry.input_schema, index).refusals);
1202
2030
  }
1203
2031
  if (inputIssues.length) return done(inputIssues, story);
@@ -1210,29 +2038,68 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1210
2038
  return done(null, story);
1211
2039
  }
1212
2040
 
2041
+ function summarizePromptClosure(doc, { prompts, visible, root, workspace, allowMissingInterfaces }) {
2042
+ const steps = Array.isArray(doc?.steps) ? doc.steps : [];
2043
+ if (!steps.length) return null;
2044
+ const getPrompt = path => {
2045
+ if (typeof path !== 'string' || !path) return { error: 'entry-missing' };
2046
+ if (!prompts.has(path)) {
2047
+ try { prompts.set(path, readPrompt(root, visible, path, workspace)); }
2048
+ catch { prompts.set(path, { error: 'interface-unavailable' }); }
2049
+ }
2050
+ return prompts.get(path);
2051
+ };
2052
+ const allPrompts = new Set(), missingInterfaces = new Set();
2053
+ let estimatedStepCalls = 0, stepPromptCount = 0, maxChainFanOut = 0;
2054
+ for (const step of steps) {
2055
+ const stepPrompts = new Set();
2056
+ estimatedStepCalls += analyzeStepCallCost(step?.entry_path, {
2057
+ getPrompt,
2058
+ visible,
2059
+ allowMissingInterfaces,
2060
+ hasSimulationPorts: hasSimulationBindings(doc, step),
2061
+ missingInterfaces,
2062
+ reachablePrompts: stepPrompts,
2063
+ });
2064
+ for (const path of stepPrompts) allPrompts.add(path);
2065
+ stepPromptCount += stepPrompts.size;
2066
+ if (stepPrompts.size > maxChainFanOut) maxChainFanOut = stepPrompts.size;
2067
+ }
2068
+ return {
2069
+ estimatedStepCalls,
2070
+ promptCount: allPrompts.size,
2071
+ stepPromptCount,
2072
+ maxChainFanOut,
2073
+ missingInterfaceCount: missingInterfaces.size,
2074
+ };
2075
+ }
2076
+
1213
2077
  // Rules P1-P10 for the selected tests. Returns rows and warnings; never throws for a test problem.
1214
- export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false }) {
2078
+ export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false, localLint = false, stepIds = [] }) {
1215
2079
  found={...found,workspace};for(const test of selected)requireRuntimePath(workspace,{path:test.path,from:'Selected test'});
1216
2080
  const warnings = [];
1217
2081
  const reviews = numericReviews(root, found, warnings);
1218
2082
  const rows = selected.map(test => {
1219
- const prompts = new Map();
2083
+ const prompts = new Map(), executablePaths = new Set(), visited = new Set();
1220
2084
  // Discover identity independently of validation: an early criterion error or
1221
2085
  // stale caller must not make a reachable native-only declaration executable.
1222
- const visit = path => {
1223
- if (typeof path !== 'string' || prompts.has(path)) return;
1224
- const prompt = readPrompt(root, found.visible, path, workspace);
1225
- prompts.set(path, prompt);
1226
- for (const call of Array.isArray(prompt.interface?.calls) ? prompt.interface.calls : []) visit(call?.target);
1227
- if ((allowMissingInterfaces && prompt.error === 'interface-missing') || prompt.frontmatter) {
1228
- for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) visit(target);
1229
- }
2086
+ const visit = (path, executable = true) => {
2087
+ if (typeof path !== 'string') return;
2088
+ const identity = `${executable ? 'call' : 'context'}:${path}`;
2089
+ if (visited.has(identity)) return;
2090
+ visited.add(identity);
2091
+ if (executable) executablePaths.add(path);
2092
+ if (!prompts.has(path)) prompts.set(path, readPrompt(root, found.visible, path, workspace));
2093
+ const prompt = prompts.get(path);
2094
+ for (const call of Array.isArray(prompt.interface?.calls) ? prompt.interface.calls : []) visit(call?.target, executable);
2095
+ for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) visit(target, false);
1230
2096
  };
1231
2097
  let refused, plan, testSha = null, effectiveDoc = test.doc;
1232
2098
  try {
1233
- for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) visit(step?.entry_path);
1234
- const checked = checkTest(root, found, test, prompts, { allowMissingInterfaces });
2099
+ for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) if (!stepIds.length || stepIds.includes(step?.step_id)) visit(step?.entry_path);
2100
+ const checked = checkTest(root, found, test, prompts, { allowMissingInterfaces, executablePaths, localLint, stepIds });
1235
2101
  refused = checked.refusal;
2102
+ if (stepIds.length && selected.length !== 1) refused = refusal('step-scenario-ambiguous', 'steps', 'Diagnostic --step selection requires one unambiguous scenario file. Select its path.');
1236
2103
  effectiveDoc = checked.doc;
1237
2104
  const nativeProblems = [...prompts.values()].filter(prompt => prompt.interface?.kind === 'native-only')
1238
2105
  .map(prompt => promptRefusal(prompt,'interface')).filter(Boolean);
@@ -1246,11 +2113,13 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
1246
2113
  refused = refusal(error.code ?? 'source-unavailable', 'source', error.message,
1247
2114
  {hint:'Restore the named dependency, make it readable, or correct its declared path.'});
1248
2115
  }
2116
+ const closure = summarizePromptClosure(effectiveDoc, { prompts, visible: found.visible, root, workspace, allowMissingInterfaces });
1249
2117
  const row = { test: test.path, story: test.story, title: test.title, refusals: refused ? [refused].flat() : [], warnings: numberWarnings(effectiveDoc, { testPath: test.path, testSha, reviews }),
1250
- max_calls: defaultMaxCalls(effectiveDoc), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
2118
+ ...(stepIds.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:(effectiveDoc?.steps ?? []).filter(step=>stepIds.includes(step?.step_id)).map(step=>step.step_id)} : {}),
2119
+ max_calls: defaultMaxCalls(effectiveDoc, closure), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
1251
2120
  criteria_total: plan?.criteria.length ?? (Array.isArray(effectiveDoc?.criteria) ? effectiveDoc.criteria.length : 0),
1252
2121
  ...(plan?.not_checked.length ? {not_checked:plan.not_checked} : {}), draft: false };
1253
- row.native_only = [...prompts.values()].filter(item => item.interface?.kind === 'native-only').map(item => ({path:item.path,reason:item.interface.reason}));
2122
+ row.native_only = [...executablePaths].map(path => prompts.get(path)).filter(item => item?.interface?.kind === 'native-only').map(item => ({path:item.path,reason:item.interface.reason}));
1254
2123
  row.draft = row.steps.some(step => prompts.get(step?.entry_path)?.interface?.status === 'draft');
1255
2124
  for (const [index, step] of row.steps.entries()) {
1256
2125
  const prompt = prompts.get(step?.entry_path), entries = Array.isArray(prompt?.interface?.entries) ? prompt.interface.entries : [];
@@ -1307,7 +2176,7 @@ export function missingCliImplementationWarnings({ root, found, selected, worksp
1307
2176
  return warnings;
1308
2177
  }
1309
2178
 
1310
- // Keep PDD's declaration classification and CLI implementation binding local.
2179
+ // Keep PDD's declaration classification and local implementation bindings local.
1311
2180
  // Token offsets preserve all other JSON spellings; parsing and stringifying would round numbers.
1312
2181
  export function executableInterfaceText(text) {
1313
2182
  const blocks = interfaceBlocks(text);
@@ -1318,8 +2187,8 @@ export function executableInterfaceText(text) {
1318
2187
  if (!isObject(value) || (Object.hasOwn(value, 'kind') && !['full', 'partial'].includes(value.kind))) return text;
1319
2188
  const hasLocalKind = Object.hasOwn(value, 'kind');
1320
2189
  const entries = Array.isArray(value.entries) ? value.entries : [];
1321
- if (entries.some(entry => isObject(entry) && Object.hasOwn(entry, 'implementation') && !validCliImplementation(entry.implementation))) return text;
1322
- const hasImplementation = entries.some(entry => isObject(entry) && validCliImplementation(entry.implementation));
2190
+ if (entries.some(entry => isObject(entry) && Object.hasOwn(entry, 'implementation') && !validLocalImplementation(entry.implementation))) return text;
2191
+ const hasImplementation = entries.some(entry => isObject(entry) && validLocalImplementation(entry.implementation));
1323
2192
  if (!hasLocalKind && !hasImplementation) return text;
1324
2193
  const tokens = [...body.matchAll(/"(?:[^"\\]|\\[\s\S])*"|[{}\[\],:]|[^\s{}\[\],:"]+/g)];
1325
2194
  const skipValue = pos => {
@@ -1678,7 +2547,7 @@ function contextPath(raw, from, visible) {
1678
2547
  if (target.startsWith('/') || target.includes('\\')) throw sourceProblem(from, raw, 'must stay inside this repository.');
1679
2548
  const relative = posix.normalize(posix.join(posix.dirname(from), target));
1680
2549
  const path = visible.has(relative) ? relative : visible.has(target.replace(/^\.\//, '')) ? target.replace(/^\.\//, '') : relative;
1681
- return sourcePath(path, from);
2550
+ return sourcePath(path === '.' ? './' : path, from);
1682
2551
  }
1683
2552
 
1684
2553
  // Read only a section name, never rewritten HTML. Ambiguous markup retains context.
@@ -1745,6 +2614,7 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1745
2614
  let unstable = false;
1746
2615
  root = realpathSync(root);
1747
2616
  const observations = new Map();
2617
+ const dependencyRepair = ' List required files explicitly, or move navigation-only links outside ## Dependencies.';
1748
2618
  const changed = () => { unstable = true; throw unstableSource; };
1749
2619
  function observe(path) {
1750
2620
  const stat = statOf(join(root, path));
@@ -1773,6 +2643,7 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1773
2643
  observe('');
1774
2644
  function inspectRaw(path, from, allowMissing = false, noLinks = false, control = false, presenceOnly = false) {
1775
2645
  path = sourcePath(path, from);
2646
+ const repair = from === 'Source' ? '' : dependencyRepair;
1776
2647
  if(!control)requireRuntimePath(workspace,{path,from});
1777
2648
  if (isSecretPath(path)) {
1778
2649
  // Refusal is already decided. Enrich it only along non-following metadata
@@ -1795,11 +2666,17 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1795
2666
  if (noLinks && file.target) throw sourceProblem(from, path, ': symbolic links are not allowed for prepared output.');
1796
2667
  return file;
1797
2668
  }
1798
- let pending = path.split('/').map(part => ({part, context:null})), resolved = [], lastLink = null, firstLink = null, linkedVisible = false, authored = true;
2669
+ let pending = path.split('/').filter(Boolean).map(part => ({part, context:null})), resolved = [], lastLink = null, firstLink = null, linkedVisible = false, authored = true;
1799
2670
  const seen = new Set(), observed = new Set(['']);
1800
2671
  const refuse = (reason, context = lastLink, plain = false) => {
1801
2672
  throw sourceProblem(from, path, context ? `: link ${context.path} -> ${context.link}: ${reason}` : `${plain ? '' : ': '}${reason}`);
1802
2673
  };
2674
+ const refuseDirectory = (current, context = lastLink) => {
2675
+ const prefix = current ? `${current}/` : '';
2676
+ const directory = [...diskVisible].some(file => file.startsWith(prefix))
2677
+ ? 'is a Git-visible directory, not a regular file.' : 'is a directory that is not Git-visible, not a regular file.';
2678
+ refuse(directory + dependencyRepair, context, !lastLink);
2679
+ };
1803
2680
  // Resolve components individually: an ancestor link must be checked before any
1804
2681
  // descendant is inspected. No host lookup follows an unchecked link.
1805
2682
  while (pending.length) {
@@ -1839,19 +2716,22 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1839
2716
  if (isSecretPath(current) || (!pending.length && isSecretPath(path))) refuse('the name looks like a secret. pdd never sends it.', context ?? lastLink);
1840
2717
  if (!stat) {
1841
2718
  if (lastLink) refuse('broken link: target does not exist.', context ?? lastLink);
1842
- if (!allowMissing) refuse('is not a Git-visible file on disk. Restore it or correct the declared dependency.', null, true);
2719
+ if (!allowMissing) refuse('is not a Git-visible file on disk. Restore it or correct the declared dependency.' + repair, null, true);
1843
2720
  const file = { path, stat: null, size: 0, observed }; snapshots.set(path, file); return file;
1844
2721
  }
1845
2722
  if (pending.length && !stat.isDirectory()) refuse(`${lastLink ? 'non-directory ancestor' : 'has a non-directory ancestor'} (${current}).`, context ?? lastLink, !lastLink);
1846
2723
  if (!pending.length) {
1847
- if (!stat.isFile()) refuse('a submodule, folder or other non-regular file. pdd sends only regular files.', context ?? lastLink);
1848
- if (!diskVisible.has(path) && !linkedVisible && firstLink) refuse('link itself is not a Git-visible file. Add it to Git or correct the declared dependency.', firstLink);
1849
- if (!presenceOnly && !diskVisible.has(current)) refuse(`${lastLink ? 'target is not' : 'is not'} a Git-visible file. Add it to Git or correct the declared dependency.`, context ?? lastLink, !lastLink);
2724
+ if (stat.isDirectory()) {
2725
+ refuseDirectory(current, context ?? lastLink);
2726
+ }
2727
+ if (!stat.isFile()) refuse('a submodule or other non-regular file. pdd sends only regular files.', context ?? lastLink);
2728
+ if (!diskVisible.has(path) && !linkedVisible && firstLink) refuse('link itself is not a Git-visible file. Add it to Git or correct the declared dependency.' + repair, firstLink);
2729
+ if (!presenceOnly && !diskVisible.has(current)) refuse(`${lastLink ? 'target is not' : 'is not'} a Git-visible file. Add it to Git or correct the declared dependency.${repair}`, context ?? lastLink, !lastLink);
1850
2730
  const file = { path, stat, size: Number(stat.size), observed, ...(presenceOnly && !diskVisible.has(current) ? {presenceOnly:true} : {}), ...(lastLink ? { target: current } : {}) };
1851
2731
  snapshots.set(path, file); return file;
1852
2732
  }
1853
2733
  }
1854
- refuse('a folder or other non-regular file.');
2734
+ refuseDirectory(resolved.join('/'));
1855
2735
  }
1856
2736
  function bytes(file) {
1857
2737
  if (file.bytes) return file.bytes;
@@ -1905,13 +2785,13 @@ function preparedText(root, visible, path, text, format,workspace) {
1905
2785
  }
1906
2786
  }
1907
2787
 
1908
- function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=tests === undefined,validateCriteria=true,allowMissingInterfaces=true }, strict = false, ports = {}) {
2788
+ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=true,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=tests === undefined,validateCriteria=true,allowMissingInterfaces=true,stepIds=[] }, strict = false, ports = {}) {
1909
2789
  const { isStoryPath, matchTests } = requireSelectionPorts(ports);
1910
2790
  const headBefore = gitHead(root);
1911
2791
  const policyBefore=JSON.stringify(loadRuntimeWorkspace({root}));workspace=boundedWorkspace(root,workspace);
1912
2792
  const names = gitFiles(root), visible = new Set(names), overlay = new Map(), payload = new Map(), queue = [], visited = new Set();
1913
2793
  const chains=new Map(),preparationReads=new Set(),referenceReads=new Set();
1914
- const effective = new Map(), provenance = new Map(), edges = new Map(), shared = new Set(), footprintPayload = new Map();
2794
+ const effective = new Map(), provenance = new Map(), edges = new Map(), shared = new Set(), footprintPayload = new Map(), storyContexts = new Map();
1915
2795
  let selecting = true;
1916
2796
  const unavailable = new Map();
1917
2797
  const markUnavailable = (path,error) => unavailable.set(path,{path,cause:String(error.message ?? error).replace(/[\r\n\x00-\x1f\x7f]/g,' ').slice(0,4000)});
@@ -1966,17 +2846,38 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
1966
2846
  {message:`${file.path}: ${authority.message}`,hint:'Restore the Story path selected by the test name, then run the selection again.'});
1967
2847
  if (typeof doc?.story_path === 'string' && !documentRefusal(doc, file.path, { allowOmittedCriteria: true })) {
1968
2848
  add(doc.story_path, file.path, 'story');
1969
- if (validateCriteria) {
2849
+ if (validateCriteria || stepIds.length) {
1970
2850
  const storySource = bytes(inspect(doc.story_path, file.path)).toString('utf8');
1971
2851
  const partial = partialTestRefusal(doc);
1972
- const resolved = partial ? { doc, changed: false, refusal: null } : resolveScenarioCriteria(doc, storySource);
2852
+ let resolved = partial ? { doc, changed: false, refusal: null } : resolveScenarioCriteria(doc, storySource);
2853
+ let checkedStory = storySource;
2854
+ if (stepIds.length && (!tests || tests.includes(file.path)) && !resolved.refusal) {
2855
+ if (partial) throw Object.assign(new PreflightError(4, `${file.path}: ${partial.message}`), partial);
2856
+ const projection = selectDiagnosticSteps(resolved.doc, stepIds);
2857
+ if (projection.refusal) throw Object.assign(new PreflightError(4, `${file.path}: ${projection.refusal.message}`), projection.refusal);
2858
+ storyContexts.set(doc.story_path, storySource);
2859
+ checkedStory = diagnosticStoryText(storySource, projection.doc.criteria);
2860
+ const projectionIssue = diagnosticStoryProjectionRefusal(doc.story_path, storySource, checkedStory);
2861
+ if (projectionIssue) throw Object.assign(new PreflightError(4, `${file.path}: ${projectionIssue.message}`), projectionIssue);
2862
+ // Omitted criterion prose cannot grant scope authority. Keep the
2863
+ // uploaded Story conservative too, even when deleting that prose
2864
+ // removes the reason its authored boundary was rejected.
2865
+ if (runtimeBoundary(doc.story_path, storySource) === null && runtimeBoundary(doc.story_path, checkedStory) !== null) {
2866
+ checkedStory += '\n\n<!-- Diagnostic subset retains authored full dependency closure. -->\n';
2867
+ }
2868
+ const storyFile = inspect(doc.story_path, file.path), storyBytes = Buffer.from(checkedStory, 'utf8');
2869
+ const projected = {...storyFile,bytes:storyBytes,size:storyBytes.length};
2870
+ effective.set(doc.story_path, projected); footprintPayload.set(doc.story_path, projected);
2871
+ if (selecting) payload.set(doc.story_path, projected);
2872
+ resolved = {...resolved,doc:projection.doc,changed:true};
2873
+ }
1973
2874
  if (resolved.refusal && needsCriteriaResolution(doc)) {
1974
2875
  throw Object.assign(new PreflightError(4, `${file.path}: ${resolved.refusal.message}`), resolved.refusal,
1975
2876
  { message: `${file.path}: ${resolved.refusal.message}`, hint: 'Fix the scenario criteria or Story acceptance list, then run the selection again.' });
1976
2877
  }
1977
2878
  if (resolved.changed && !resolved.refusal) content = Buffer.from(stringifyScenarioJson(resolved.doc), 'utf8');
1978
2879
  if (!resolved.refusal && !scenarioShapeRefusal(resolved.doc, file.path)) {
1979
- const plan = capturedCriterionPlan(resolved.doc, storyCriteria(storySource), file.path);
2880
+ const plan = capturedCriterionPlan(resolved.doc, storyCriteria(checkedStory), file.path);
1980
2881
  if (resolved.changed || (plan?.not_checked.length && plan.checked)) {
1981
2882
  content = Buffer.from(stringifyScenarioJson({ ...resolved.doc, criteria: plan.criteria,
1982
2883
  ...(plan?.not_checked.length ? { check_exemptions: plan.not_checked.map(item => ({ criterion_id: item.criterion_id, reason: 'out-of-scope', detail: item.reason })) } : {}) }), 'utf8');
@@ -2022,7 +2923,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2022
2923
  if (output.role !== undefined) {
2023
2924
  if (output.role !== 'app-map' || prepared.filter(file=>file.role==='app-map').length !== 1 || appMap !== null) throw new PreflightError(4,'prepareSource may mark exactly one app-map and cannot override an explicit map.');
2024
2925
  let map;try{map=JSON.parse(Buffer.from(output.bytes).toString('utf8'));}catch{throw new PreflightError(4,'Prepared app-map must be valid JSON.');}
2025
- if(!isObject(map)||map.schema_version!=='prompt-runtime.app-map.v1')throw new PreflightError(4,'Prepared app-map must be a v1 app map.');
2926
+ if(!isObject(map)||(Object.hasOwn(map,'schema_version')&&!['prompt-runtime.app-map.v1','prompt-runtime.app-map.v2'].includes(map.schema_version))||!Array.isArray(map.screens))throw new PreflightError(4,'Prepared app-map must be a valid app map.');
2026
2927
  appMap=path;
2027
2928
  }
2028
2929
  if (overlay.has(path)) throw sourceProblem('prepareSource', path, `duplicates prepared file ${path}.`);
@@ -2034,7 +2935,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2034
2935
  }
2035
2936
  for (const path of overlay.keys()) add(path, 'prepareSource');
2036
2937
  }
2037
- if (visible.has(SOURCE_CONFIG)) {
2938
+ if (sourceIncludes && visible.has(SOURCE_CONFIG)) {
2038
2939
  try {
2039
2940
  const config = overlay.get(SOURCE_CONFIG)??inspectRaw(SOURCE_CONFIG, SOURCE_CONFIG, false, false, true);
2040
2941
  let doc;
@@ -2053,6 +2954,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2053
2954
  const named = matchTests(onDisk.storyFiles, outsideFixtureProjects([...onDisk.visible, ...overlay.keys()], excluded)).tests.filter(test=>!test.problem);
2054
2955
  const allNamed=matchTests(onDisk.storyFiles,discoveryNames).tests.flatMap(test=>(test.files??[test.path]).map(path=>({...test,path})));
2055
2956
  const selected = tests ?? named.map(test=>test.path);
2957
+ if (stepIds.length && selected.length !== 1) throw Object.assign(new PreflightError(4, 'Diagnostic --step selection requires one unambiguous scenario file. Select its path.'), {code:'step-scenario-ambiguous'});
2056
2958
  for (const path of selected) add(path, 'Selected test',path.endsWith('.prompt.md')?'context':isStoryPath(path)?'story':'test');
2057
2959
  if (appMap) { add(appMap, 'App map', 'app-map'); shared.add(sourcePath(appMap,'App map')); }
2058
2960
  const storyTests = new Map(), boundaries = new Map();
@@ -2086,10 +2988,15 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2086
2988
  const mapRefusal=appMapsRefusal(doc);
2087
2989
  if (mapRefusal) throw Object.assign(new PreflightError(4,path+': '+mapRefusal.section+': '+mapRefusal.message),
2088
2990
  {code:mapRefusal.code,section:mapRefusal.section});
2089
- if (typeof doc.story_path === 'string') {
2090
- if (selecting) { if (!storyTests.has(doc.story_path)) storyTests.set(doc.story_path,[]); if (!storyTests.get(doc.story_path).includes(path)) storyTests.get(doc.story_path).push(path); }
2091
- add(doc.story_path, path, 'story');
2991
+ const effectiveStoryPath = typeof doc.story_path === 'string' && doc.story_path
2992
+ ? doc.story_path
2993
+ : (path.endsWith('.json') && visible.has(`user_stories/${basename(path, '.json')}.md`)
2994
+ ? `user_stories/${basename(path, '.json')}.md` : null);
2995
+ if (typeof effectiveStoryPath === 'string') {
2996
+ if (selecting) { if (!storyTests.has(effectiveStoryPath)) storyTests.set(effectiveStoryPath,[]); if (!storyTests.get(effectiveStoryPath).includes(path)) storyTests.get(effectiveStoryPath).push(path); }
2997
+ add(effectiveStoryPath, path, 'story');
2092
2998
  }
2999
+ if (typeof doc.entry_path === 'string' && doc.entry_path) add(doc.entry_path, path);
2093
3000
  addStrings(doc.entry_paths, path);
2094
3001
  addStrings(doc.app_maps, path, 'app-map');
2095
3002
  for (const step of Array.isArray(doc.steps) ? doc.steps : []) if (typeof step?.entry_path === 'string') add(step.entry_path, path);
@@ -2112,7 +3019,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2112
3019
  } else {
2113
3020
  if (role === 'story') {
2114
3021
  const notes=[];
2115
- let boundary=runtimeBoundary(path,text,{notes});
3022
+ let boundary=runtimeBoundary(path,storyContexts.get(path) ?? text,{notes});
2116
3023
  if (boundary) {
2117
3024
  try {
2118
3025
  // Validate all members before admitting any boundary-only source.
@@ -2130,7 +3037,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2130
3037
  boundaries.set(path,{boundary,notes});
2131
3038
  for (const member of boundary ?? []) add(member,path);
2132
3039
  }
2133
- for (const raw of markdownContext(text)) { const context = contextPath(raw, path, visible); if (context) add(context, path); }
3040
+ for (const raw of markdownContext(storyContexts.get(path) ?? text)) { const context = contextPath(raw, path, visible); if (context) add(context, path); }
2134
3041
  if (path.endsWith('.prompt.md')) {
2135
3042
  for (const block of interfaceBlocks(text)) {
2136
3043
  let doc;