@promptdriven/runtime-client 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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: 82c0d4c07385035d6555f688ddda347268bd17777f02d8394079955bc0d7d0c9).
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;}
@@ -371,6 +371,21 @@ const exactSchemaValue = (holder, key) => {
371
371
  : isObject(value) ? Object.fromEntries(Object.keys(value).map(name => [name, exactSchemaValue(value, name)])) : value;
372
372
  };
373
373
  const sameValue = (a, b) => isDeepStrictEqual(exactValue(a), exactValue(b));
374
+ // JSON Schema equality is recursive and numeric: -0 equals 0, while exact
375
+ // integer tokens remain distinct even when their Number representations round.
376
+ function sameJsonValue(a, b) {
377
+ if (numeric(a) && numeric(b)) {
378
+ if (typeof a === typeof b) return a === b;
379
+ const whole = typeof a === 'number' ? a : b, exact = typeof a === 'bigint' ? a : b;
380
+ return Number.isInteger(whole) && BigInt(whole) === exact;
381
+ }
382
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b)
383
+ && a.length === b.length && a.every((item, index) => sameJsonValue(item, b[index]));
384
+ if (isObject(a) || isObject(b)) return isObject(a) && isObject(b)
385
+ && Object.keys(a).length === Object.keys(b).length
386
+ && Object.keys(a).every(key => Object.hasOwn(b, key) && sameJsonValue(a[key], b[key]));
387
+ return a === b;
388
+ }
374
389
  const article = type => /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
375
390
 
376
391
  function unknownKeyword(schema) {
@@ -397,16 +412,16 @@ function portablePattern(source, value) {
397
412
  if (/\\(?:[1-9bBAZzGkpPuU]|x|c)|\(\?|[\s\S]*[\u0080-\uffff]/u.test(source)) return null;
398
413
  try { return new RegExp(source, 'u'); } catch { return null; }
399
414
  }
400
- function schemaRun(value, schema, tokens) {
415
+ function schemaRun(value, schema, tokens, equality = null) {
401
416
  const problems = [], warnings = [], evidence = { miss: false, unknown: false };
402
- schemaProblems(value, schema, tokens, problems, warnings, evidence);
417
+ schemaProblems(value, schema, tokens, problems, warnings, evidence, equality);
403
418
  return { problems, warnings, state: problems.length || evidence.miss ? 'miss' : evidence.unknown ? 'unknown' : 'match' };
404
419
  }
405
- function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss: false, unknown: false }) {
420
+ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss: false, unknown: false }, equality = null) {
406
421
  const at = rule => out.push({ tokens, rule });
407
422
  if (!isObject(schema)) return;
408
423
  if (Array.isArray(schema.oneOf)) {
409
- const runs = schema.oneOf.map(variant => schemaRun(value, variant, tokens));
424
+ const runs = schema.oneOf.map(variant => schemaRun(value, variant, tokens, equality));
410
425
  const fits = runs.filter(run => run.state === 'match').length;
411
426
  if (fits > 1) return at(`fits more than one of the allowed shapes (oneOf). Make the shapes exclusive.`);
412
427
  if (fits === 1) {
@@ -426,8 +441,9 @@ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss:
426
441
  if (!types.some(type => typeMatches(value, type))) return at(`is ${show(value)}. The prompt wants ${types.map(article).join(' or ')}.`);
427
442
  }
428
443
  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))}.`);
444
+ const equal = equality ?? sameValue;
445
+ if (Object.hasOwn(schema, 'const') && !equal(value, wanted)) at(`is ${show(value)}. The prompt wants ${show(wanted)}.`);
446
+ if (choices && !choices.some(choice => equal(choice, value))) at(`is ${show(value)}. The prompt allows ${either(choices.map(show))}.`);
431
447
  if (numeric(value)) {
432
448
  const [minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf] = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'].map(key => schemaValue(schema, key));
433
449
  if ((minimum !== undefined && value < minimum) || (maximum !== undefined && value > maximum)) at(`is ${show(value)}. The prompt allows ${range(minimum, maximum)}.`);
@@ -463,8 +479,8 @@ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss:
463
479
  if ((schema.minItems !== undefined && value.length < schema.minItems) || (schema.maxItems !== undefined && value.length > schema.maxItems)) {
464
480
  at(`has ${plural(value.length, 'item')}. The prompt allows ${range(schema.minItems, schema.maxItems, 'item')}.`);
465
481
  }
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);
482
+ 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.');
483
+ if (isObject(schema.items)) for (const [index, item] of value.entries()) schemaProblems(item, schema.items, [...tokens, String(index)], out, warnings, evidence, equality);
468
484
  }
469
485
  if (isObject(value)) {
470
486
  const count = Object.keys(value).length;
@@ -474,9 +490,9 @@ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss:
474
490
  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
491
  const properties = isObject(schema.properties) ? schema.properties : {};
476
492
  for (const [key, child] of Object.entries(value)) {
477
- if (Object.hasOwn(properties, key)) schemaProblems(child, properties[key], [...tokens, key], out, warnings, evidence);
493
+ if (Object.hasOwn(properties, key)) schemaProblems(child, properties[key], [...tokens, key], out, warnings, evidence, equality);
478
494
  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);
495
+ else if (isObject(schema.additionalProperties)) schemaProblems(child, schema.additionalProperties, [...tokens, key], out, warnings, evidence, equality);
480
496
  }
481
497
  }
482
498
  }
@@ -622,6 +638,12 @@ export const schemaKeywordWarningLines = prompt => (isObject(prompt?.interface)
622
638
  .filter(item => item.code === 'graph-schema-unsupported-keyword').map(item => `Warning: ${prompt.path} ${item.pointer} ${item.code}: ${item.rule}`);
623
639
  const validCliImplementation = impl => isObject(impl) && Object.keys(impl).length === 2 && impl.kind === 'cli'
624
640
  && typeof impl.command === 'string' && Boolean(impl.command.trim()) && !/[\n\r;|&<>`$\\'"(){}*?\[\]]/.test(impl.command);
641
+ const validCallImplementation = impl => isObject(impl) && Reflect.ownKeys(impl).length === 3
642
+ && ['kind', 'command', 'symbol'].every(key => Object.hasOwn(impl, key)) && impl.kind === 'call'
643
+ && Array.isArray(impl.command) && impl.command.length > 0
644
+ && Array.from(impl.command).every(item => typeof item === 'string' && !item.includes('\0')) && Boolean(impl.command[0].trim())
645
+ && typeof impl.symbol === 'string' && Boolean(impl.symbol.trim()) && !impl.symbol.includes('\0');
646
+ const validLocalImplementation = impl => validCliImplementation(impl) || validCallImplementation(impl);
625
647
  const isCliEntry = (iface, index) => index >= 0 && Array.isArray(iface?.conventions)
626
648
  && ['input_schema', 'result_schema'].every(key => iface.conventions.some(item => isObject(item) && item.path === `/entries/${index}/${key}` && item.convention === 'cli'));
627
649
  export function interfaceSchemaProblems(iface) {
@@ -631,8 +653,8 @@ export function interfaceSchemaProblems(iface) {
631
653
  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
654
  for (const [index, entry] of (Array.isArray(iface?.entries) ? iface.entries : []).entries()) {
633
655
  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.' });
656
+ if (isObject(entry) && Object.hasOwn(entry, 'implementation') && !validLocalImplementation(entry.implementation)) {
657
+ 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
658
  }
637
659
  }
638
660
  for (const [index, resource] of (Array.isArray(iface?.resources) ? iface.resources : []).entries()) {
@@ -765,14 +787,138 @@ function discoveryPromptPaths(root) {
765
787
  return [...discoveryVisibleFiles({ root, excludeFixtureProjects: true })].filter(path => path.endsWith('.prompt.md')).sort();
766
788
  }
767
789
 
790
+ export function readAppMapScreens(root, visible, workspace = loadRuntimeWorkspace({ root })) {
791
+ const mapPath = ['app-map.json', 'app/app-map.json'].find(candidate => visible.has(candidate));
792
+ if (!mapPath) return [];
793
+ try {
794
+ const raw = sourceFilePort(root, visible, workspace).read({ path: mapPath }).content;
795
+ const doc = JSON.parse(raw);
796
+ return Array.isArray(doc?.screens) ? doc.screens.filter(isObject) : [];
797
+ } catch {
798
+ return [];
799
+ }
800
+ }
801
+
802
+ export function analyzePromptSelectorWords(prompt, { appMapScreens = [] } = {}) {
803
+ const empty = { kinds: [], items: [], duplicates: [], collisions: [], tableLines: [], warnings: [], programName: null };
804
+ if (!isObject(prompt?.interface) || prompt.interface.kind === 'native-only') return empty;
805
+ const iface = prompt.interface;
806
+ const entries = Array.isArray(iface.entries) ? iface.entries : [];
807
+ const conventions = Array.isArray(iface.conventions) ? iface.conventions : [];
808
+ const rawText = String(prompt.text ?? '');
809
+ const proseText = rawText.replace(INTERFACE, '');
810
+ const heading = rawText.match(/^#\s+(.+?)\s*$/m)?.[1]?.replace(/^`([^`]+)`$/, '$1')?.trim() ?? '';
811
+ const programName = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(heading) ? heading : null;
812
+
813
+ const items = [];
814
+ const kinds = new Set();
815
+ let hasHttp = iface.kind === 'http' || Boolean(iface.http) || (Array.isArray(iface.routes) && iface.routes.length > 0);
816
+ let hasScreen = Boolean(iface.screen) || Boolean(iface.app)
817
+ || appMapScreens.some(screen => screen?.prompt_path === prompt.path);
818
+
819
+ for (const [index, entry] of entries.entries()) {
820
+ if (!isObject(entry)) continue;
821
+ const entryIsCli = isCliEntry(iface, index)
822
+ || (Array.isArray(entry.conventions) && entry.conventions.includes('cli'))
823
+ || Object.hasOwn(entry.input_schema?.properties ?? {}, 'argv')
824
+ || Object.hasOwn(entry.output_schema?.properties ?? {}, 'exit_code')
825
+ || Object.hasOwn(entry.result_schema?.properties ?? {}, 'exit_code');
826
+ const entryIsHttp = Boolean(entry.http) || Boolean(entry.route)
827
+ || (typeof entry.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title))
828
+ || (Array.isArray(entry.conventions) && entry.conventions.includes('http'))
829
+ || conventions.some(c => isObject(c) && typeof c.path === 'string' && c.path.startsWith(`/entries/${index}/`) && c.convention === 'http');
830
+ const entryIsScreen = Boolean(entry.screen)
831
+ || (Array.isArray(entry.conventions) && entry.conventions.includes('screen'))
832
+ || conventions.some(c => isObject(c) && typeof c.path === 'string' && c.path.startsWith(`/entries/${index}/`) && c.convention === 'screen');
833
+ const screenBoundOp = typeof entry.operation === 'string'
834
+ && appMapScreens.some(screen => screen?.source === 'operation' && screen.prompt_path === prompt.path && screen.operation === entry.operation);
835
+
836
+ if (entryIsCli) {
837
+ kinds.add('cli');
838
+ items.push({ kind: 'cli', word: programName, label: programName ? `CLI "${programName}"` : 'CLI', isDefault: true });
839
+ } else if (entryIsHttp) {
840
+ hasHttp = true;
841
+ } else if (entryIsScreen || screenBoundOp) {
842
+ hasScreen = true;
843
+ } else if (typeof entry.operation === 'string' && entry.operation.trim()) {
844
+ const word = entry.operation.trim();
845
+ kinds.add('typed');
846
+ items.push({ kind: 'typed', word, label: `typed operation "${word}"`, isDefault: false });
847
+ }
848
+ }
849
+
850
+ if (hasHttp) {
851
+ kinds.add('http');
852
+ items.push({ kind: 'http', word: 'serve', label: 'HTTP routes', isDefault: false });
853
+ }
854
+ if (hasScreen) {
855
+ kinds.add('screen');
856
+ items.push({ kind: 'screen', word: 'app', label: 'Screen app', isDefault: false });
857
+ }
858
+
859
+ const byWord = new Map();
860
+ for (const item of items) {
861
+ if (!item.word) continue;
862
+ if (!byWord.has(item.word)) byWord.set(item.word, []);
863
+ byWord.get(item.word).push(item.label);
864
+ }
865
+ const duplicates = [];
866
+ for (const [word, labels] of byWord.entries()) {
867
+ if (labels.length > 1) duplicates.push({ word, labels });
868
+ }
869
+
870
+ const collisions = [];
871
+ const warnings = [];
872
+ if (kinds.has('cli') && programName) {
873
+ const escapedProg = programName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
874
+ const seenWords = new Set();
875
+ for (const item of items) {
876
+ if (!item.word || item.word === programName || seenWords.has(item.word)) continue;
877
+ seenWords.add(item.word);
878
+ const escapedWord = item.word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
879
+ const pattern = new RegExp(`(?<![A-Za-z0-9_.-])${escapedProg}[ \\t]+${escapedWord}(?![A-Za-z0-9_.-])`);
880
+ if (pattern.test(proseText)) {
881
+ collisions.push({ programName, word: item.word, label: item.label });
882
+ 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.`);
883
+ }
884
+ }
885
+ }
886
+
887
+ const tableLines = [];
888
+ if (kinds.size >= 2) {
889
+ const rows = items.map(item => {
890
+ const cmd = item.kind === 'cli'
891
+ ? `pdd ${prompt.path} [ARGS]`
892
+ : `pdd ${prompt.path} ${item.word}`;
893
+ const desc = item.kind === 'cli'
894
+ ? `CLI ${programName ? `"${programName}" ` : ''}(default; no ARGS opens a shell)`
895
+ : item.label;
896
+ return { cmd, desc };
897
+ });
898
+ const width = Math.max(...rows.map(row => row.cmd.length));
899
+ tableLines.push(`${prompt.path}: ${kinds.size} kinds`);
900
+ for (const row of rows) tableLines.push(` ${row.cmd.padEnd(width + 4)}${row.desc}`);
901
+ }
902
+
903
+ return { kinds: [...kinds], items, duplicates, collisions, tableLines, warnings, programName };
904
+ }
905
+
768
906
  export function interfaceFindings({ root, paths = discoveryPromptPaths(root) }) {
769
907
  const visible = new Set(gitFiles(root));
908
+ const appMapScreens = readAppMapScreens(root, visible);
770
909
  return paths.flatMap(path => {
771
910
  try {
772
911
  const prompt = readPrompt(root, visible, path), problem = promptRefusal(prompt, 'interface');
773
912
  if (!prompt.interface) return [{ ...problem, path }];
774
913
  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;
914
+ const selectorDupes = analyzePromptSelectorWords(prompt, { appMapScreens }).duplicates.map(({ word, labels }) => ({
915
+ code: 'duplicate-selector-word',
916
+ path,
917
+ section: '/entries',
918
+ 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.`,
919
+ }));
920
+ const all = [...schema, ...selectorDupes];
921
+ return problem && !all.some(item => item.code === problem.code) ? [{ ...problem, path }, ...all] : all;
776
922
  } catch (error) {
777
923
  return [{ code: error.code ?? 'interface-unreadable', path, message: error.message }];
778
924
  }
@@ -785,7 +931,7 @@ export function runtimeCoverage({ root, paths = discoveryPromptPaths(root), allo
785
931
  for (const path of paths) {
786
932
  try {
787
933
  const prompt = readPrompt(root, visible, path);
788
- if (allowMissingInterfaces && prompt.error === 'interface-missing') { checkable++; continue; }
934
+ if (prompt.error === 'interface-missing') continue;
789
935
  if (promptRefusal(prompt, 'interface') || interfaceSchemaProblems(prompt.interface).length) continue;
790
936
  if (prompt.interface.kind === 'native-only') native_only++;
791
937
  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++;
@@ -979,32 +1125,31 @@ export function promptMarkdownTargets(text, fromPath, visible) {
979
1125
 
980
1126
  // The schema rules of a prompt and of the prompts it calls, all at once (cached per prompt).
981
1127
  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
- })];
1128
+ const visit = (current, contextOnly = false) => {
1129
+ if (!current) return [];
1130
+ const identity = contextOnly ? `context:${current.path}` : current.path;
1131
+ if (seen.has(identity)) return [];
1132
+ seen.add(identity);
1133
+ const load = target => {
1134
+ if (!prompts.has(target)) prompts.set(target, readPrompt(root, found.visible, target, found.workspace));
1135
+ return prompts.get(target);
1136
+ };
1137
+ if (current.error && !(current.error === 'interface-missing' && (contextOnly || allowMissingInterfaces))) {
1138
+ return [{ ...promptRefusal(current, 'interface'), path: current.path }];
1139
+ }
1140
+ const contexts = promptMarkdownTargets(current.text, current.path, found.visible)
1141
+ .flatMap(target => visit(load(target), true));
1142
+ if (!current.interface) return contexts;
1143
+ current.schemaIssues ??= interfaceSchemaProblems(current.interface).map(problem =>
1144
+ refusal(problem.code, problem.pointer, `${current.path} ${problem.pointer} ${problem.rule}`, {path:current.path, ...(problem.hint ? {hint:problem.hint} : {})}));
1145
+ const ownRefusal = current.frontmatter || !['draft', 'approved'].includes(current.interface.status)
1146
+ ? promptRefusal(current, 'interface') : null;
1147
+ const statusProblems = ownRefusal ? [{ ...ownRefusal, path: current.path }] : [];
1148
+ const called = (Array.isArray(current.interface.calls) ? current.interface.calls : [])
1149
+ .flatMap(call => typeof call?.target === 'string' ? visit(load(call.target), contextOnly) : []);
1150
+ return [...statusProblems, ...current.schemaIssues, ...called, ...contexts];
1151
+ };
1152
+ return visit(prompt);
1008
1153
  }
1009
1154
 
1010
1155
  // A refusal that discovery alone proves: a conflict, an unreadable or invalid file, a file over the upload limit,
@@ -1087,6 +1232,329 @@ function stepProblem(step) {
1087
1232
  return null;
1088
1233
  }
1089
1234
  const checkShape = check => isObject(check) && ['criterion_id','target','path','op'].every(key=>Object.hasOwn(check,key));
1235
+ const checkTargets = new Set(['result', 'world', 'calls', 'error']);
1236
+
1237
+ // Reject only paths whose absence is established by every schema alternative.
1238
+ function resultPathPossible(schema, path) {
1239
+ if (typeof path !== 'string' || path !== '' && (!path.startsWith('/') || /~(?![01])/u.test(path))) return false;
1240
+ const tokens = path === '' ? [] : path.slice(1).split('/').map(token => token.replace(/~1/g, '/').replace(/~0/g, '~'));
1241
+ const literals = node => {
1242
+ if (!isObject(node)) return null;
1243
+ if (Object.hasOwn(node, 'const')) return [exactSchemaValue(node, 'const')];
1244
+ if (Array.isArray(node.enum)) return node.enum.map((_, index) => exactSchemaValue(node.enum, index));
1245
+ if (!Array.isArray(node.oneOf)) return null;
1246
+ const alternatives = node.oneOf.map(literals);
1247
+ return alternatives.every(values => values !== null) ? alternatives.flat() : null;
1248
+ };
1249
+ const together = states => states.includes('miss') ? 'miss' : states.includes('unknown') ? 'unknown' : 'match';
1250
+ // schemaRun handles supported scalar/container constraints. Check oneOf
1251
+ // separately so its early return cannot hide sibling or nested constraints.
1252
+ const membership = (value, node) => {
1253
+ if (!isObject(node)) return 'match';
1254
+ if (unknownKeyword(node)) return 'unknown';
1255
+ let own = node;
1256
+ if (Array.isArray(node.oneOf)) {
1257
+ own = {...node}; delete own.oneOf;
1258
+ if (numberSources.has(node)) numberSources.set(own, numberSources.get(node));
1259
+ }
1260
+ const states = [schemaRun(value, own, [], sameJsonValue).state];
1261
+ if (Array.isArray(node.oneOf)) {
1262
+ const alternatives = node.oneOf.map(variant => membership(value, variant));
1263
+ const fits = alternatives.filter(state => state === 'match').length;
1264
+ states.push(fits > 1 ? 'miss' : alternatives.includes('unknown') ? 'unknown' : fits === 1 ? 'match' : 'miss');
1265
+ }
1266
+ if (Array.isArray(value) && isObject(node.items)) for (const item of value) states.push(membership(item, node.items));
1267
+ if (isObject(value)) for (const [key, child] of Object.entries(value)) {
1268
+ const childSchema = Object.hasOwn(node.properties ?? {}, key) ? node.properties[key] : node.additionalProperties;
1269
+ states.push(membership(child, childSchema));
1270
+ }
1271
+ return together(states);
1272
+ };
1273
+ const addresses = (value, at) => {
1274
+ if (at === tokens.length) return true;
1275
+ const token = tokens[at];
1276
+ if (Array.isArray(value) && !/^(0|[1-9][0-9]*)$/.test(token)) return false;
1277
+ return value !== null && typeof value === 'object' && Object.hasOwn(value, token) && addresses(value[token], at + 1);
1278
+ };
1279
+ // Prove branch coverage from constraints, never from a sampled value. A
1280
+ // pointer makes each property on its route present. This can make otherwise
1281
+ // distinct optional/required branches overlap for every addressed result.
1282
+ const guaranteed = (nodes, target, at) => {
1283
+ nodes = nodes.filter(isObject);
1284
+ if (!isObject(target)) return true;
1285
+ if (unknownKeyword(target) || Array.isArray(target.oneOf) || typeof target.pattern === 'string') return false;
1286
+ const candidates = nodes.map(literals).find(values => values !== null);
1287
+ if (candidates !== undefined) return candidates.every(value => nodes.some(node => membership(value, node) === 'miss')
1288
+ || !addresses(value, at) || membership(value, target) === 'match');
1289
+ const type = nodes.find(node => typeof node.type === 'string')?.type;
1290
+ if (target.type && type !== target.type && !(type === 'integer' && target.type === 'number')) return false;
1291
+ const lower = key => nodes.reduce((bound,node) => numeric(schemaValue(node,key)) && schemaValue(node,key) > bound ? schemaValue(node,key) : bound, 0);
1292
+ const upper = key => nodes.reduce((bound,node) => numeric(schemaValue(node,key)) && schemaValue(node,key) < bound ? schemaValue(node,key) : bound, Infinity);
1293
+ const objects = nodes.filter(node => node.type === 'object');
1294
+ const required = new Set([...nodes.flatMap(node => node.required ?? []), ...(at < tokens.length && type === 'object' ? [tokens[at]] : [])]);
1295
+ let allowed = null;
1296
+ for (const node of objects) if (node.additionalProperties === false) {
1297
+ const keys = Object.keys(node.properties ?? {});
1298
+ allowed = allowed === null ? new Set(keys) : new Set(keys.filter(key => allowed.has(key)));
1299
+ }
1300
+ // Required fields and the pointer leave no optional key when all object
1301
+ // slots are occupied. This also bounds additionalProperties coverage.
1302
+ if (required.size >= upper('maxProperties')) {
1303
+ allowed = new Set([...required].filter(key => allowed === null || allowed.has(key)));
1304
+ }
1305
+ const childNodes = key => objects.map(node => Object.hasOwn(node.properties ?? {}, key) ? node.properties[key] : node.additionalProperties);
1306
+ for (const [key, value] of Object.entries(target)) {
1307
+ if (SCHEMA_NOTES.has(key) || key === 'type') continue;
1308
+ if (['minLength','minItems','minProperties'].includes(key)) {
1309
+ let minimum = lower(key);
1310
+ if (key === 'minProperties' && required.size > minimum) minimum = required.size;
1311
+ if (key === 'minItems' && at < tokens.length && /^(0|[1-9][0-9]*)$/.test(tokens[at])) {
1312
+ const addressed = BigInt(tokens[at]) + 1n;
1313
+ if (addressed > minimum) minimum = addressed;
1314
+ }
1315
+ if (minimum < schemaValue(target,key)) return false;
1316
+ } else if (['maxLength','maxItems','maxProperties'].includes(key)) {
1317
+ let maximum = upper(key);
1318
+ if (key === 'maxProperties' && allowed !== null && allowed.size < maximum) maximum = allowed.size;
1319
+ if (maximum > schemaValue(target,key)) return false;
1320
+ } else if (key === 'required') {
1321
+ if (value.some(name => !required.has(name))) return false;
1322
+ } else if (key === 'properties') {
1323
+ for (const [name, child] of Object.entries(value)) {
1324
+ if (allowed !== null && !allowed.has(name)) continue;
1325
+ if (!guaranteed(childNodes(name), child, at < tokens.length && tokens[at] === name ? at + 1 : tokens.length)) return false;
1326
+ }
1327
+ } else if (key === 'additionalProperties') {
1328
+ const declared = new Set(Object.keys(target.properties ?? {}));
1329
+ if (value === false) {
1330
+ if (allowed === null || [...allowed].some(name => !declared.has(name))) return false;
1331
+ } else if (isObject(value)) {
1332
+ if (allowed === null && !guaranteed(objects.map(node => node.additionalProperties), value, tokens.length)) return false;
1333
+ const keys = allowed ?? new Set(objects.flatMap(node => Object.keys(node.properties ?? {})));
1334
+ for (const name of keys) if (!declared.has(name) && !guaranteed(childNodes(name), value, tokens.length)) return false;
1335
+ }
1336
+ } else if (key === 'items') {
1337
+ const itemAt = at < tokens.length && tokens[at] === '0' && upper('maxItems') <= 1 ? at + 1 : tokens.length;
1338
+ if (upper('maxItems') !== 0 && !guaranteed(nodes.map(node => node.items), value, itemAt)) return false;
1339
+ } else if (key === 'uniqueItems') {
1340
+ if (value && upper('maxItems') > 1 && !nodes.some(node => node.uniqueItems === true)) return false;
1341
+ } else if (!nodes.some(node => Object.hasOwn(node, key) && sameJsonValue(exactSchemaValue(node,key), exactSchemaValue(target,key)))) return false;
1342
+ }
1343
+ return true;
1344
+ };
1345
+ const visit = (nodes, at, expanded = new Set()) => {
1346
+ nodes = nodes.filter(isObject);
1347
+ if (nodes.some(node => Object.keys(node).some(key => !SCHEMA_RULES.has(key) && !SCHEMA_NOTES.has(key)))) return true;
1348
+ const values = nodes.map(literals).find(candidates => candidates !== null);
1349
+ if (values !== undefined) return values.some(value => nodes.every(node => membership(value, node) !== 'miss') && addresses(value, at));
1350
+ const union = nodes.find(node => Array.isArray(node.oneOf) && !expanded.has(node));
1351
+ if (union) return union.oneOf.some((variant, index) => {
1352
+ const selected = [...nodes, variant];
1353
+ return !union.oneOf.some((other, otherIndex) => index !== otherIndex && guaranteed(selected, other, at))
1354
+ && visit(selected, at, new Set([...expanded, union]));
1355
+ });
1356
+ // Reaching the end of a pointer still requires a value. Intersect known
1357
+ // bounds before accepting a terminal scalar or using it as a sibling/item.
1358
+ if (nodes.some(node => node.type === 'string')) {
1359
+ let minimum = 0, maximum = Infinity;
1360
+ for (const node of nodes) {
1361
+ const lower = schemaValue(node, 'minLength'), upper = schemaValue(node, 'maxLength');
1362
+ if (numeric(lower) && lower > minimum) minimum = lower;
1363
+ if (numeric(upper) && upper < maximum) maximum = upper;
1364
+ }
1365
+ if (minimum > maximum) return false;
1366
+ }
1367
+ if (nodes.some(node => node.type === 'integer' || node.type === 'number')) {
1368
+ let minimum = -Infinity, maximum = Infinity, lowerOpen = false, upperOpen = false;
1369
+ for (const node of nodes) for (const [key, lower, open] of [
1370
+ ['minimum', true, false], ['exclusiveMinimum', true, true],
1371
+ ['maximum', false, false], ['exclusiveMaximum', false, true]
1372
+ ]) {
1373
+ const bound = schemaValue(node, key);
1374
+ if (!numeric(bound)) continue;
1375
+ if (lower) {
1376
+ if (bound > minimum) { minimum = bound; lowerOpen = open; }
1377
+ else if (sameJsonValue(bound, minimum)) lowerOpen ||= open;
1378
+ } else {
1379
+ if (bound < maximum) { maximum = bound; upperOpen = open; }
1380
+ else if (sameJsonValue(bound, maximum)) upperOpen ||= open;
1381
+ }
1382
+ }
1383
+ if (minimum > maximum || sameJsonValue(minimum, maximum) && (lowerOpen || upperOpen)) return false;
1384
+ const multiples = nodes.map(node => schemaValue(node, 'multipleOf')).filter(step => numeric(step) && step > 0);
1385
+ // Safe JSON integers arrive as Numbers. Larger whole values can also
1386
+ // arrive as exact integer tokens; retain every representable spelling.
1387
+ const candidatePossible = value => {
1388
+ let candidates = [value];
1389
+ if (typeof value === 'bigint') {
1390
+ const number = Number(value);
1391
+ if (Number.isSafeInteger(number)) candidates = [number];
1392
+ else if (Number.isFinite(number) && BigInt(number) === value) candidates.push(number);
1393
+ } else if (Number.isInteger(value) && !Number.isSafeInteger(value)) candidates.push(BigInt(value));
1394
+ return candidates.some(candidate => nodes.every(node => membership(candidate, node) !== 'miss'));
1395
+ };
1396
+ if (nodes.some(node => node.type === 'integer')) {
1397
+ const endpoint = (bound, lower, open) => {
1398
+ if (typeof bound === 'number' && !Number.isFinite(bound)) return bound;
1399
+ const whole = typeof bound === 'bigint' ? bound : BigInt(lower ? Math.ceil(bound) : Math.floor(bound));
1400
+ return open && (typeof bound === 'bigint' || Number.isInteger(bound)) ? whole + (lower ? 1n : -1n) : whole;
1401
+ };
1402
+ const first = endpoint(minimum, true, lowerOpen), last = endpoint(maximum, false, upperOpen);
1403
+ if (first > last) return false;
1404
+ // Bound the proof cost. Wider/unbounded domains remain unproven.
1405
+ if (multiples.length && typeof first === 'bigint' && typeof last === 'bigint' && last - first < 1024n) {
1406
+ let possible = false;
1407
+ for (let value = first; value <= last; value += 1n) if (candidatePossible(value)) { possible = true; break; }
1408
+ if (!possible) return false;
1409
+ }
1410
+ } else if (multiples.length) {
1411
+ if (sameJsonValue(minimum, maximum)) {
1412
+ if ((typeof minimum === 'bigint' || Number.isFinite(minimum)) && !candidatePossible(minimum)) return false;
1413
+ } else if (typeof minimum === 'number' && typeof maximum === 'number'
1414
+ && minimum >= Number.MIN_SAFE_INTEGER && maximum <= Number.MAX_SAFE_INTEGER) {
1415
+ // For ordinary Numbers, division is monotone. Widen its quotient
1416
+ // interval by the existing membership tolerance and rounding slack.
1417
+ // Include open endpoints: an overapproximation can prove absence.
1418
+ for (const step of multiples) if (typeof step === 'number' && Number.isFinite(step)) {
1419
+ const first = minimum / step, last = maximum / step;
1420
+ if (!Number.isFinite(first) || !Number.isFinite(last)) continue;
1421
+ const slack = 1e-9 + 8 * Number.EPSILON * Math.max(1, Math.abs(first), Math.abs(last));
1422
+ if (Math.ceil(first - slack) > Math.floor(last + slack)) return false;
1423
+ }
1424
+ }
1425
+ }
1426
+ }
1427
+ const token = tokens[at], children = [];
1428
+ if (nodes.some(node => node.type === 'object')) {
1429
+ // The addressed property consumes one slot alongside every required
1430
+ // sibling. All selected oneOf and sibling constraints apply together.
1431
+ const required = new Set([...(at < tokens.length ? [token] : []), ...nodes.flatMap(node => node.required ?? [])]);
1432
+ let minimum = required.size, maximum = Infinity, allowed = null;
1433
+ for (const node of nodes) {
1434
+ const lower = schemaValue(node, 'minProperties'), upper = schemaValue(node, 'maxProperties');
1435
+ if (numeric(lower) && lower > minimum) minimum = lower;
1436
+ if (numeric(upper) && upper < maximum) maximum = upper;
1437
+ if (node.additionalProperties === false) {
1438
+ const keys = new Set(Object.keys(node.properties ?? {}));
1439
+ allowed = allowed === null ? keys : new Set([...allowed].filter(key => keys.has(key)));
1440
+ }
1441
+ }
1442
+ if (allowed !== null && ([...required].some(key => !allowed.has(key)) || minimum > allowed.size)) return false;
1443
+ if (minimum > maximum) return false;
1444
+ const objects = nodes.filter(node => node.type === 'object');
1445
+ const propertyPossible = key => {
1446
+ const schemas = [];
1447
+ for (const node of objects) {
1448
+ if (Object.hasOwn(node.properties ?? {}, key)) schemas.push(node.properties[key]);
1449
+ else if (node.additionalProperties === false) return false;
1450
+ else schemas.push(node.additionalProperties);
1451
+ }
1452
+ return visit(schemas, tokens.length);
1453
+ };
1454
+ // Required siblings need values even when the pointer follows another
1455
+ // field. Optional fields supply capacity only when their values can exist.
1456
+ if ([...required].some(key => !propertyPossible(key))) return false;
1457
+ if (allowed === null && !visit(objects.map(node => node.additionalProperties), tokens.length)) {
1458
+ allowed = new Set(objects.flatMap(node => Object.keys(node.properties ?? {})));
1459
+ }
1460
+ if (allowed !== null && minimum > required.size) {
1461
+ let capacity = required.size;
1462
+ for (const key of allowed) if (!required.has(key) && propertyPossible(key)) {
1463
+ capacity += 1;
1464
+ if (capacity >= minimum) break;
1465
+ }
1466
+ if (capacity < minimum) return false;
1467
+ }
1468
+ }
1469
+ if (nodes.some(node => node.type === 'array')) {
1470
+ let minimum = 0, maximum = Infinity;
1471
+ for (const node of nodes) {
1472
+ const lower = schemaValue(node, 'minItems'), upper = schemaValue(node, 'maxItems');
1473
+ if (numeric(lower) && lower > minimum) minimum = lower;
1474
+ if (numeric(upper) && upper < maximum) maximum = upper;
1475
+ }
1476
+ if (at < tokens.length) {
1477
+ if (!/^(0|[1-9][0-9]*)$/.test(token)) return false;
1478
+ const addressed = BigInt(token) + 1n;
1479
+ if (addressed > minimum) minimum = addressed;
1480
+ }
1481
+ if (minimum > maximum) return false;
1482
+ const items = nodes.map(node => node.items).filter(isObject);
1483
+ if (minimum > 0 && !visit(items, tokens.length)) return false;
1484
+ if (nodes.some(node => node.uniqueItems === true) && !items.some(node => unknownKeyword(node))) {
1485
+ const candidates = items.map(literals).find(values => values !== null);
1486
+ if (candidates !== undefined) {
1487
+ // This is an upper capacity: unknown membership keeps a candidate.
1488
+ // Numeric equality includes signed zero and exact integer tokens.
1489
+ const possible = candidates.filter(value => items.every(node => membership(value, node) !== 'miss'));
1490
+ const distinct = possible.filter((value, index) => possible.findIndex(other => sameJsonValue(value, other)) === index);
1491
+ if (minimum > distinct.length) return false;
1492
+ }
1493
+ }
1494
+ }
1495
+ if (at === tokens.length) return true;
1496
+ for (const node of nodes) {
1497
+ if (node.type === 'object') {
1498
+ if (isObject(node.properties) && Object.hasOwn(node.properties, token)) children.push(node.properties[token]);
1499
+ else if (node.additionalProperties === false) return false;
1500
+ else children.push(node.additionalProperties);
1501
+ } else if (node.type === 'array') {
1502
+ if (!/^(0|[1-9][0-9]*)$/.test(token)) return false;
1503
+ if (numeric(schemaValue(node, 'maxItems')) && BigInt(token) >= schemaValue(node, 'maxItems')) return false;
1504
+ children.push(node.items);
1505
+ } else if (['null', 'boolean', 'string', 'integer', 'number'].includes(node.type)) return false;
1506
+ }
1507
+ return visit(children, at + 1);
1508
+ };
1509
+ return visit([schema], 0);
1510
+ }
1511
+
1512
+ function computeBindingRefusal(doc, step, index, prompts, storySource) {
1513
+ const plan = buildBindingPlan({test:{path:'',storyPath:doc.story_path,doc:{...doc,steps:[step]}}, storyText:storySource,
1514
+ // Source capture has not validated the Story boundary yet. Mandatory
1515
+ // compute admission follows actual entry/call reachability independently.
1516
+ boundaryState:{boundary:null,notes:[]},
1517
+ prompts:new Map([...prompts].map(([path, prompt]) => [path, prompt.interface]))});
1518
+ // Binding advice is conservative for called modules. Admission follows the
1519
+ // operations actually invoked, including multiple operations of one module.
1520
+ const required = new Map(), seen = new Set(), pending = [[step.entry_path, step.operation]];
1521
+ for (let at = 0; at < pending.length; at++) {
1522
+ const [path, operation] = pending[at], identity = JSON.stringify([path, operation]);
1523
+ if (seen.has(identity)) continue;
1524
+ seen.add(identity);
1525
+ const iface = prompts.get(path)?.interface;
1526
+ if (!iface) continue;
1527
+ const entries = Array.isArray(iface.entries) ? iface.entries : [];
1528
+ const declared = new Set((iface.resources ?? []).flatMap(resource => (resource.operations ?? [])
1529
+ .map(member => `${resource.name}.${member.name}`)));
1530
+ const selected = entries.filter(entry => entry.operation === operation);
1531
+ const complete = selected.length === 1 && entries.every(entry => typeof entry.operation === 'string' && entry.operation
1532
+ && Array.isArray(entry.resource_operations) && entry.resource_operations.every(key => declared.has(key))
1533
+ && new Set(entry.resource_operations).size === entry.resource_operations.length)
1534
+ && new Set(entries.map(entry => entry.operation)).size === entries.length
1535
+ && new Set(entries.flatMap(entry => entry.resource_operations)).size === declared.size;
1536
+ const active = complete ? selected[0].resource_operations : null;
1537
+ if (active === null) required.set(path, null);
1538
+ else if (!required.has(path)) required.set(path, new Set(active));
1539
+ else if (required.get(path) !== null) for (const key of active) required.get(path).add(key);
1540
+ for (const call of iface.calls ?? []) if (typeof call.target === 'string') pending.push([call.target, call.target_operation]);
1541
+ }
1542
+ const simulation = {...(isObject(doc.simulation) ? doc.simulation : {})};
1543
+ if (Array.isArray(step.simulation_overrides)) {
1544
+ for (const row of step.simulation_overrides) if (typeof row?.operation === 'string') simulation[row.operation] = row.binding;
1545
+ } else if (isObject(step.simulation_overrides)) Object.assign(simulation, step.simulation_overrides);
1546
+ for (const edge of plan.edges) {
1547
+ if (!required.has(edge.prompt_path) || required.get(edge.prompt_path) !== null && !required.get(edge.prompt_path).has(edge.key)) continue;
1548
+ const resource = prompts.get(edge.prompt_path)?.interface?.resources?.find(item => item?.name === edge.resource);
1549
+ if (resource?.kind !== 'compute') continue;
1550
+ const binding = Object.hasOwn(simulation, edge.key) ? simulation[edge.key] : null;
1551
+ if (isObject(binding) && binding.action === 'compute') continue;
1552
+ return refusal(binding == null ? 'simulation-binding-missing' : 'invalid-simulation-binding', `steps[${index}].simulation`,
1553
+ `${edge.prompt_path} requires a simulation binding for ${edge.key} with action "compute".`,
1554
+ {step:index + 1,path:edge.prompt_path,hint:`Add or repair simulation["${edge.key}"] with action "compute", or its effective step override.`});
1555
+ }
1556
+ return null;
1557
+ }
1090
1558
  function appMapsRefusal(doc) {
1091
1559
  if (!Object.hasOwn(doc,'app_maps')) return null;
1092
1560
  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 +1581,16 @@ function documentRefusal(doc, path, { allowOmittedCriteria = false } = {}) {
1113
1581
  return appMapsRefusal(doc);
1114
1582
  }
1115
1583
 
1584
+ export function scenarioDerivationRefusal(doc) {
1585
+ for (const [index, step] of (Array.isArray(doc?.steps) ? doc.steps : []).entries()) {
1586
+ for (const [at, check] of (Array.isArray(step?.checks) ? step.checks : []).entries()) {
1587
+ const problem = checkDerivation(check);
1588
+ if (problem) return refusal(problem.code, `steps[${index}].checks[${at}].derivation`, problem.message, { step: index + 1 });
1589
+ }
1590
+ }
1591
+ return null;
1592
+ }
1593
+
1116
1594
  export function scenarioShapeRefusal(doc,path) {
1117
1595
  const broken=documentRefusal(doc,path);if(broken)return broken;
1118
1596
  if (!Array.isArray(doc.criteria)||!doc.criteria.length) return refusal('invalid-criterion','criteria','The test has no criteria.');
@@ -1134,10 +1612,187 @@ export function scenarioShapeRefusal(doc,path) {
1134
1612
  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
1613
  }
1136
1614
  }
1615
+ return scenarioDerivationRefusal(doc);
1616
+ }
1617
+
1618
+ // A diagnostic projection changes effective inputs only; authored files keep their identity.
1619
+ function selectDiagnosticSteps(doc, stepIds) {
1620
+ if (!Array.isArray(doc.steps) || !doc.steps.length) return {refusal:refusal('missing-steps', 'steps', 'The test has no steps.')};
1621
+ const available = (Array.isArray(doc.steps) ? doc.steps : []).map(step => step?.step_id).filter(id => typeof id === 'string');
1622
+ const requested = new Set(stepIds), unknown = [...requested].filter(id => !available.includes(id));
1623
+ if (unknown.length) return { refusal: refusal('step-unknown', 'steps', `Unknown step_id: ${unknown.join(', ')}. Available step_id values: ${available.join(', ')}.`) };
1624
+ if (new Set(available).size !== available.length) return { refusal: refusal('invalid-step', 'steps', 'Diagnostic selection requires unique step_id values.') };
1625
+ const steps = doc.steps.filter(step => requested.has(step?.step_id));
1626
+ const selected = new Set(steps.map(step => step.step_id));
1627
+ const stateful = [doc.initial_world, doc.simulation, doc.$simulation].some(value => value && typeof value === 'object' && Object.keys(value).length > 0);
1628
+ const last = Math.max(...steps.map(step => doc.steps.indexOf(step)));
1629
+ if (stateful && doc.steps.slice(0, last).some(step => !selected.has(step?.step_id))) {
1630
+ return { refusal: refusal('step-prerequisite-omitted', 'steps', 'Selected steps use world or simulation data; include every earlier step explicitly.') };
1631
+ }
1632
+ let omitted = null;
1633
+ const visit = value => {
1634
+ if (!value || typeof value !== 'object') return;
1635
+ const reference = value.$step_result;
1636
+ if (isObject(value) && Object.keys(value).length === 1 && isObject(reference)
1637
+ && Object.keys(reference).length === 2 && typeof reference.step_id === 'string' && typeof reference.path === 'string') {
1638
+ if (!selected.has(reference.step_id)) omitted ??= reference.step_id;
1639
+ return;
1640
+ }
1641
+ for (const item of Object.values(value)) visit(item);
1642
+ };
1643
+ for (const step of steps) visit(step.input);
1644
+ if (omitted !== null) return { refusal: refusal('step-prerequisite-omitted', 'steps', `Selected steps reference omitted step_id ${omitted}. Include that prerequisite explicitly.`) };
1645
+ const criterionIds = new Set(steps.flatMap(step => Array.isArray(step.checks) ? step.checks.map(check => check?.criterion_id) : []));
1646
+ return { doc: { ...doc, steps, criteria: doc.criteria.filter(item => criterionIds.has(item.id)) } };
1647
+ }
1648
+
1649
+ function diagnosticStoryText(source, criteria) {
1650
+ const retained = new Map(), heading = AC_HEADING.exec(source);
1651
+ for (const item of criteria) retained.set(item.text, (retained.get(item.text) ?? 0) + 1);
1652
+ const offset = heading ? heading.index + heading[0].length : 0, body = source.slice(offset);
1653
+ if (!numberedStoryCriteria(source).length) {
1654
+ if (!heading) return source;
1655
+ const nextHeading = NEXT_HEADING.exec(body), end = nextHeading?.index ?? body.length;
1656
+ const section = body.slice(0, end);
1657
+ const items = [...section.matchAll(BULLET_ITEM)];
1658
+ const trailingBoundary = /^```pdd-boundary\r?\n[\s\S]*?^```(?=\r?$)/m.exec(section);
1659
+ // Bullet admission can include trailing authority in the final criterion.
1660
+ // Keep that exact text when selected, or move its complete authored tail
1661
+ // beyond the acceptance terminator when omitted. Never duplicate a marker.
1662
+ if (trailingBoundary && trailingBoundary.index >= items.at(-1)?.index && runtimeBoundary('', source)) {
1663
+ const prefix = source.slice(0, offset) + section.slice(0, items[0].index);
1664
+ let fence = null;
1665
+ for (const line of prefix.split(/\r?\n/)) {
1666
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1667
+ if (!fence && match) fence = match[1];
1668
+ else if (fence && match && match[1][0] === fence[0] && match[1].length >= fence.length && !match[2].trim()) fence = null;
1669
+ }
1670
+ let projected = '', removedFences = '', omittedTail = '', cursor = items[0].index;
1671
+ let retainedTail = false;
1672
+ for (const item of items) {
1673
+ projected += section.slice(cursor, item.index);
1674
+ cursor = item.index + item[0].length;
1675
+ const tailAt = trailingBoundary.index - item.index;
1676
+ const hasTail = tailAt >= 0 && tailAt < item[0].length;
1677
+ const head = hasTail ? item[0].slice(0, tailAt) : item[0];
1678
+ const tail = hasTail ? item[0].slice(tailAt) : '';
1679
+ const text = pyWords(item[1]);
1680
+ if (retained.get(text) > 0) {
1681
+ retained.set(text, retained.get(text) - 1);
1682
+ // Continuation indentation does not change bullet criterion text.
1683
+ // Prevent its example delimiters from enclosing the real declaration.
1684
+ projected += head + tail;
1685
+ retainedTail ||= hasTail;
1686
+ } else {
1687
+ projected += item[0].match(/\s*$/)[0];
1688
+ removedFences += [...head.matchAll(/^ {0,3}(?:`{3,}|~{3,})[^\r\n]*/gm)].map(match => match[0] + '\n').join('');
1689
+ omittedTail += tail;
1690
+ }
1691
+ }
1692
+ const guard = '~'.repeat([...removedFences.matchAll(/~+/g)].reduce((length, match) => Math.max(length, match[0].length + 1), 3));
1693
+ const tailAt = retainedTail ? projected.indexOf(trailingBoundary[0]) : projected.length;
1694
+ const head = projected.slice(0, tailAt), tail = projected.slice(tailAt);
1695
+ const html = [...head.matchAll(/<(?:[!?]|\/?[A-Za-z])/g)].at(-1);
1696
+ // Protect literal HTML as authored code. When the final criterion also
1697
+ // contains the boundary, its existing closer must end the protection:
1698
+ // inserting another closer there would change the exact criterion text.
1699
+ const closer = html && retainedTail
1700
+ ? [...head.matchAll(/^ {0,3}(`{3,}|~{3,})[ \t]*(?=\r?$)/gm)].findLast(match => match.index > html.index)
1701
+ : null;
1702
+ const enclosure = html ? closer?.[1] ?? '~'.repeat([...head.matchAll(/~+/g)].reduce((length, match) => Math.max(length, match[0].length + 1), 3)) : '';
1703
+ projected = head.replace(/^ {0,3}(?:`{3,}|~{3,})[^\r\n]*/gm, (line, at) => at === closer?.index ? line : ' ' + line) + tail;
1704
+ return prefix + (fence ? '\n' + fence + '\n\n' : '') + (enclosure ? enclosure + '\n' : '') + projected
1705
+ + '\n\n## Diagnostic acceptance boundary\n\n' + (enclosure && !retainedTail ? enclosure + '\n\n' : '')
1706
+ + (removedFences ? guard + '\n' + removedFences + guard + '\n\n' : '') + omittedTail + body.slice(end);
1707
+ }
1708
+ let projected = '', cursor = 0, removedFences = '';
1709
+ for (const match of section.matchAll(BULLET_ITEM)) {
1710
+ projected += section.slice(cursor, match.index);
1711
+ const text = pyWords(match[1]);
1712
+ if (retained.get(text) > 0) {
1713
+ retained.set(text, retained.get(text) - 1);
1714
+ projected += match[0];
1715
+ } else {
1716
+ projected += match[0].match(/\s*$/)[0];
1717
+ for (const line of match[0].matchAll(/^ {0,3}(?:`{3,}|~{3,})[^\r\n]*/gm)) {
1718
+ const start = match.index + line.index, finish = start + line[0].length;
1719
+ const before = section.slice(start - 2, start) === '\r\n' ? '\r\n' : '\n';
1720
+ const after = section.slice(finish, finish + 2) === '\r\n' ? '\r\n' : section[finish] === '\n' ? '\n' : '';
1721
+ removedFences += before + line[0] + after;
1722
+ }
1723
+ }
1724
+ cursor = match.index + match[0].length;
1725
+ }
1726
+ // A numbered terminator would suppress the engine's bullet fallback.
1727
+ const acceptance = projected + section.slice(cursor) + '\n\n## Diagnostic acceptance boundary\n\n';
1728
+ if (!removedFences) return source.slice(0, offset) + acceptance + body.slice(end);
1729
+ // A retained declaration inside the parsed criterion must keep its own
1730
+ // top-level context; do not put that declaration inside a new fence.
1731
+ if (/[`~]{3,}[ \t]*pdd-boundary\b/.test(section)) {
1732
+ return source.slice(0, offset) + acceptance + removedFences + '\n' + body.slice(end);
1733
+ }
1734
+ // Bullet parsing consumes delimiter lines as criterion text. Retain removed
1735
+ // delimiters after its terminator and isolate the projected section, then
1736
+ // restore the authored fence state before the untouched supporting context.
1737
+ const fenceAfter = text => {
1738
+ let fence = null;
1739
+ for (const line of text.split(/\r?\n/)) {
1740
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1741
+ if (!fence && match) fence = match[1];
1742
+ else if (fence && match && match[1][0] === fence[0] && match[1].length >= fence.length && !match[2].trim()) fence = null;
1743
+ }
1744
+ return fence;
1745
+ };
1746
+ const prefix = source.slice(0, offset), before = fenceAfter(prefix), after = fenceAfter(prefix + section);
1747
+ const guard = '~'.repeat([...section.matchAll(/~+/g)].reduce((length, match) => Math.max(length, match[0].length + 1), 3));
1748
+ return prefix + '\n\n' + (before ? before + '\n\n' : '') + guard + '\n'
1749
+ + acceptance + removedFences + '\n' + guard + '\n\n' + (after ? after + '\n\n' : '') + body.slice(end);
1750
+ }
1751
+ // Numbered criteria use Python splitlines even when the LF-only heading
1752
+ // pattern falls back to scanning the whole Story. Keep each authored ending.
1753
+ 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);
1754
+ const lineText = line => line.replace(/(?:\r\n|[\n\r\v\f\x1c-\x1e\x85\u2028\u2029])$/, '');
1755
+ let next = 1, seen = 1, boundary = 0;
1756
+ for (let index = 0; index < lines.length; index++) {
1757
+ const match = NUMBERED_ITEM.exec(lineText(lines[index]));
1758
+ if (!match || Number(match[1]) !== seen) {
1759
+ if (match && seen > 1) break;
1760
+ continue;
1761
+ }
1762
+ seen += 1;
1763
+ let end = index + 1;
1764
+ while (end < lines.length && pyStrip(lineText(lines[end])) && !lineText(lines[end]).startsWith('#') && !NUMBERED_ITEM.test(lineText(lines[end]))) end += 1;
1765
+ // Later criteria can follow prose; the trailing authored suffix starts here.
1766
+ boundary = end;
1767
+ const text = [match[2], ...lines.slice(index + 1, end).map(lineText)].map(pyStrip).join(' ');
1768
+ if (retained.get(text) > 0) {
1769
+ retained.set(text, retained.get(text) - 1);
1770
+ lines[index] = lines[index].replace(/^[1-9][0-9]*/, String(next++));
1771
+ }
1772
+ else for (let at = index; at < end; at++) {
1773
+ const authored = lineText(lines[at]);
1774
+ // A criterion can end inside a fence whose remaining lines are authored
1775
+ // context. Keep its delimiters and line separation so that context and
1776
+ // a later boundary retain their original fence state.
1777
+ if (!/^ {0,3}(?:`{3,}|~{3,})/.test(authored)) lines[at] = lines[at].slice(authored.length);
1778
+ }
1779
+ index = end - 1;
1780
+ }
1781
+ // The engine's sequential-number parser needs an explicit mismatch to stop
1782
+ // before numbered examples without changing authored fence or HTML state.
1783
+ const terminator = '\n\n1. End of diagnostic acceptance criteria.\n\n';
1784
+ return source.slice(0, offset) + lines.slice(0, boundary).join('') + terminator + lines.slice(boundary).join('');
1785
+ }
1786
+
1787
+ function diagnosticStoryProjectionRefusal(path, source, projected) {
1788
+ const boundary = runtimeBoundary(path, source);
1789
+ if (boundary !== null && !isDeepStrictEqual(runtimeBoundary(path, projected), boundary)) {
1790
+ 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.`);
1791
+ }
1137
1792
  return null;
1138
1793
  }
1139
1794
 
1140
- function checkTest(root, found, test, prompts, { allowMissingInterfaces = false } = {}) {
1795
+ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false, executablePaths = new Set(prompts.keys()), localLint = false, stepIds = [] } = {}) {
1141
1796
  let doc = test.doc;
1142
1797
  if (!test.error && isObject(doc)) {
1143
1798
  const prepared = preparedText(root,found.visible,test.path,readText(root,test.path),'scenario');
@@ -1147,6 +1802,8 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1147
1802
  if (test.error) return done(discoveryRefusal(test));
1148
1803
  const shape = documentRefusal(doc, test.path, { allowOmittedCriteria: true });
1149
1804
  if (shape) return done(shape);
1805
+ const derivation = scenarioDerivationRefusal(doc);
1806
+ if (derivation) return done(derivation);
1150
1807
  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
1808
  if (!found.visible.has(doc.story_path)) return done(refusal('story-missing', 'story_path', `${doc.story_path} is not a Git-visible file.`));
1152
1809
  if (test.storyPath && doc.story_path !== test.storyPath) return done(discoveryRefusal({ ...test, doc }));
@@ -1155,12 +1812,20 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1155
1812
  const resolved = resolveScenarioCriteria(doc, storySource);
1156
1813
  if (resolved.refusal) return done(resolved.refusal);
1157
1814
  doc = resolved.doc;
1158
- const ids = new Set(doc.criteria.map(item => item.id));
1159
- const story = storyCriteria(storySource);
1815
+ let story = storyCriteria(storySource);
1160
1816
  if (!story.length) return done(refusal('story-criteria-missing', 'story_path', `${doc.story_path} has no numbered "## Acceptance criteria" list.`), story);
1161
1817
  const testTexts = doc.criteria.map(item => item.text).sort(), storyTexts = [...story].sort();
1162
1818
  if (!isDeepStrictEqual(testTexts, storyTexts) && !criterionPlan(doc, story)) return done(refusal('story-criterion-mismatch', 'criteria', firstDifference(testTexts, storyTexts)), story);
1163
1819
  if (!Array.isArray(doc.steps) || !doc.steps.length) return done(refusal('missing-steps', 'steps', 'The test has no steps.'), story);
1820
+ if (stepIds.length) {
1821
+ const selection = selectDiagnosticSteps(doc, stepIds);
1822
+ if (selection.refusal) return done(selection.refusal, story);
1823
+ const projectionIssue = diagnosticStoryProjectionRefusal(doc.story_path, storySource, diagnosticStoryText(storySource, selection.doc.criteria));
1824
+ if (projectionIssue) return done(projectionIssue, story);
1825
+ doc = selection.doc;
1826
+ story = doc.criteria.map(item => item.text);
1827
+ }
1828
+ const ids = new Set(doc.criteria.map(item => item.id));
1164
1829
  const exact = new Set(), inputIssues = [];
1165
1830
  for (const [index, step] of doc.steps.entries()) {
1166
1831
  const section = `steps[${index}]`, at = { step: index + 1 };
@@ -1176,21 +1841,28 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1176
1841
  const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
1177
1842
  const broken = lazyMissing ? null : promptRefusal(prompt, section);
1178
1843
  if (broken) return done({ ...broken, ...at }, story);
1179
- const schemaIssues = promptSchemaRefusals(root, found, prompt, prompts, new Set(), { allowMissingInterfaces });
1844
+ const schemaIssues = promptSchemaRefusals(root, found, prompt, prompts, new Set(), { allowMissingInterfaces })
1845
+ .filter(problem => !localLint || !problem.code?.startsWith('graph-schema-'));
1180
1846
  if (schemaIssues.length) return done(schemaIssues, story);
1181
1847
  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');
1848
+ const native = [...executablePaths].some(path => prompts.get(path)?.interface?.kind === 'native-only');
1183
1849
  if (!lazyMissing && !entry && !native) return done(refusal('entry-operation-missing', section, `${step.entry_path} has no operation "${step.operation}".`, at), story);
1184
1850
  const errorStep = Object.hasOwn(step, 'expected_error');
1185
1851
  if (!lazyMissing && !native && errorStep && !(Array.isArray(entry.errors) && entry.errors.includes(step.expected_error))) {
1186
1852
  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
1853
  }
1188
1854
  if (!Array.isArray(step.checks)) return done(refusal('invalid-check', `${section}.checks`, 'checks must be a list.', at), story);
1189
- let errorChecks = 0;
1855
+ let errorChecks = 0, resultWithErrorRefusal = null;
1190
1856
  for (const [checkIndex, check] of step.checks.entries()) {
1191
1857
  if (!checkShape(check)) {
1192
1858
  return done(refusal('invalid-check', `${section}.checks[${checkIndex}]`, 'A check has criterion_id, target, path and op.', at), story);
1193
1859
  }
1860
+ const checkSection = `${section}.checks[${checkIndex}]`;
1861
+ if (!checkTargets.has(check.target)) return done(refusal('invalid-check', checkSection, 'A check target must be "result", "world", "calls" or "error".', at), story);
1862
+ 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);
1863
+ if (check.target === 'result' && entry?.result_schema && !resultPathPossible(entry.result_schema, check.path)) {
1864
+ 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);
1865
+ }
1194
1866
  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);
1195
1867
  if (EXACT_OPS.has(check.op) || (Object.hasOwn(check, 'html') && check.op === 'exists')) exact.add(check.criterion_id);
1196
1868
  if (check.target === 'error' && check.path === '/code' && check.op === 'equals' && check.value === step.expected_error) errorChecks += 1;
@@ -1198,6 +1870,11 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1198
1870
  if (errorStep && errorChecks === 0) {
1199
1871
  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
1872
  }
1873
+ if (resultWithErrorRefusal) return done(resultWithErrorRefusal, story);
1874
+ if (!native) {
1875
+ const bindingIssue = computeBindingRefusal(doc, step, index, prompts, storySource);
1876
+ if (bindingIssue) return done(bindingIssue, story);
1877
+ }
1201
1878
  if (!lazyMissing && !native) inputIssues.push(...checkInput(step.input, entry.input_schema, index).refusals);
1202
1879
  }
1203
1880
  if (inputIssues.length) return done(inputIssues, story);
@@ -1211,28 +1888,31 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false
1211
1888
  }
1212
1889
 
1213
1890
  // 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 }) {
1891
+ export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false, localLint = false, stepIds = [] }) {
1215
1892
  found={...found,workspace};for(const test of selected)requireRuntimePath(workspace,{path:test.path,from:'Selected test'});
1216
1893
  const warnings = [];
1217
1894
  const reviews = numericReviews(root, found, warnings);
1218
1895
  const rows = selected.map(test => {
1219
- const prompts = new Map();
1896
+ const prompts = new Map(), executablePaths = new Set(), visited = new Set();
1220
1897
  // Discover identity independently of validation: an early criterion error or
1221
1898
  // 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
- }
1899
+ const visit = (path, executable = true) => {
1900
+ if (typeof path !== 'string') return;
1901
+ const identity = `${executable ? 'call' : 'context'}:${path}`;
1902
+ if (visited.has(identity)) return;
1903
+ visited.add(identity);
1904
+ if (executable) executablePaths.add(path);
1905
+ if (!prompts.has(path)) prompts.set(path, readPrompt(root, found.visible, path, workspace));
1906
+ const prompt = prompts.get(path);
1907
+ for (const call of Array.isArray(prompt.interface?.calls) ? prompt.interface.calls : []) visit(call?.target, executable);
1908
+ for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) visit(target, false);
1230
1909
  };
1231
1910
  let refused, plan, testSha = null, effectiveDoc = test.doc;
1232
1911
  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 });
1912
+ for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) if (!stepIds.length || stepIds.includes(step?.step_id)) visit(step?.entry_path);
1913
+ const checked = checkTest(root, found, test, prompts, { allowMissingInterfaces, executablePaths, localLint, stepIds });
1235
1914
  refused = checked.refusal;
1915
+ if (stepIds.length && selected.length !== 1) refused = refusal('step-scenario-ambiguous', 'steps', 'Diagnostic --step selection requires one unambiguous scenario file. Select its path.');
1236
1916
  effectiveDoc = checked.doc;
1237
1917
  const nativeProblems = [...prompts.values()].filter(prompt => prompt.interface?.kind === 'native-only')
1238
1918
  .map(prompt => promptRefusal(prompt,'interface')).filter(Boolean);
@@ -1247,10 +1927,11 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
1247
1927
  {hint:'Restore the named dependency, make it readable, or correct its declared path.'});
1248
1928
  }
1249
1929
  const row = { test: test.path, story: test.story, title: test.title, refusals: refused ? [refused].flat() : [], warnings: numberWarnings(effectiveDoc, { testPath: test.path, testSha, reviews }),
1930
+ ...(stepIds.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:(effectiveDoc?.steps ?? []).filter(step=>stepIds.includes(step?.step_id)).map(step=>step.step_id)} : {}),
1250
1931
  max_calls: defaultMaxCalls(effectiveDoc), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
1251
1932
  criteria_total: plan?.criteria.length ?? (Array.isArray(effectiveDoc?.criteria) ? effectiveDoc.criteria.length : 0),
1252
1933
  ...(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}));
1934
+ 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
1935
  row.draft = row.steps.some(step => prompts.get(step?.entry_path)?.interface?.status === 'draft');
1255
1936
  for (const [index, step] of row.steps.entries()) {
1256
1937
  const prompt = prompts.get(step?.entry_path), entries = Array.isArray(prompt?.interface?.entries) ? prompt.interface.entries : [];
@@ -1307,7 +1988,7 @@ export function missingCliImplementationWarnings({ root, found, selected, worksp
1307
1988
  return warnings;
1308
1989
  }
1309
1990
 
1310
- // Keep PDD's declaration classification and CLI implementation binding local.
1991
+ // Keep PDD's declaration classification and local implementation bindings local.
1311
1992
  // Token offsets preserve all other JSON spellings; parsing and stringifying would round numbers.
1312
1993
  export function executableInterfaceText(text) {
1313
1994
  const blocks = interfaceBlocks(text);
@@ -1318,8 +1999,8 @@ export function executableInterfaceText(text) {
1318
1999
  if (!isObject(value) || (Object.hasOwn(value, 'kind') && !['full', 'partial'].includes(value.kind))) return text;
1319
2000
  const hasLocalKind = Object.hasOwn(value, 'kind');
1320
2001
  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));
2002
+ if (entries.some(entry => isObject(entry) && Object.hasOwn(entry, 'implementation') && !validLocalImplementation(entry.implementation))) return text;
2003
+ const hasImplementation = entries.some(entry => isObject(entry) && validLocalImplementation(entry.implementation));
1323
2004
  if (!hasLocalKind && !hasImplementation) return text;
1324
2005
  const tokens = [...body.matchAll(/"(?:[^"\\]|\\[\s\S])*"|[{}\[\],:]|[^\s{}\[\],:"]+/g)];
1325
2006
  const skipValue = pos => {
@@ -1678,7 +2359,7 @@ function contextPath(raw, from, visible) {
1678
2359
  if (target.startsWith('/') || target.includes('\\')) throw sourceProblem(from, raw, 'must stay inside this repository.');
1679
2360
  const relative = posix.normalize(posix.join(posix.dirname(from), target));
1680
2361
  const path = visible.has(relative) ? relative : visible.has(target.replace(/^\.\//, '')) ? target.replace(/^\.\//, '') : relative;
1681
- return sourcePath(path, from);
2362
+ return sourcePath(path === '.' ? './' : path, from);
1682
2363
  }
1683
2364
 
1684
2365
  // Read only a section name, never rewritten HTML. Ambiguous markup retains context.
@@ -1745,6 +2426,7 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1745
2426
  let unstable = false;
1746
2427
  root = realpathSync(root);
1747
2428
  const observations = new Map();
2429
+ const dependencyRepair = ' List required files explicitly, or move navigation-only links outside ## Dependencies.';
1748
2430
  const changed = () => { unstable = true; throw unstableSource; };
1749
2431
  function observe(path) {
1750
2432
  const stat = statOf(join(root, path));
@@ -1773,6 +2455,7 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1773
2455
  observe('');
1774
2456
  function inspectRaw(path, from, allowMissing = false, noLinks = false, control = false, presenceOnly = false) {
1775
2457
  path = sourcePath(path, from);
2458
+ const repair = from === 'Source' ? '' : dependencyRepair;
1776
2459
  if(!control)requireRuntimePath(workspace,{path,from});
1777
2460
  if (isSecretPath(path)) {
1778
2461
  // Refusal is already decided. Enrich it only along non-following metadata
@@ -1795,11 +2478,17 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1795
2478
  if (noLinks && file.target) throw sourceProblem(from, path, ': symbolic links are not allowed for prepared output.');
1796
2479
  return file;
1797
2480
  }
1798
- let pending = path.split('/').map(part => ({part, context:null})), resolved = [], lastLink = null, firstLink = null, linkedVisible = false, authored = true;
2481
+ let pending = path.split('/').filter(Boolean).map(part => ({part, context:null})), resolved = [], lastLink = null, firstLink = null, linkedVisible = false, authored = true;
1799
2482
  const seen = new Set(), observed = new Set(['']);
1800
2483
  const refuse = (reason, context = lastLink, plain = false) => {
1801
2484
  throw sourceProblem(from, path, context ? `: link ${context.path} -> ${context.link}: ${reason}` : `${plain ? '' : ': '}${reason}`);
1802
2485
  };
2486
+ const refuseDirectory = (current, context = lastLink) => {
2487
+ const prefix = current ? `${current}/` : '';
2488
+ const directory = [...diskVisible].some(file => file.startsWith(prefix))
2489
+ ? 'is a Git-visible directory, not a regular file.' : 'is a directory that is not Git-visible, not a regular file.';
2490
+ refuse(directory + dependencyRepair, context, !lastLink);
2491
+ };
1803
2492
  // Resolve components individually: an ancestor link must be checked before any
1804
2493
  // descendant is inspected. No host lookup follows an unchecked link.
1805
2494
  while (pending.length) {
@@ -1839,19 +2528,22 @@ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false
1839
2528
  if (isSecretPath(current) || (!pending.length && isSecretPath(path))) refuse('the name looks like a secret. pdd never sends it.', context ?? lastLink);
1840
2529
  if (!stat) {
1841
2530
  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);
2531
+ if (!allowMissing) refuse('is not a Git-visible file on disk. Restore it or correct the declared dependency.' + repair, null, true);
1843
2532
  const file = { path, stat: null, size: 0, observed }; snapshots.set(path, file); return file;
1844
2533
  }
1845
2534
  if (pending.length && !stat.isDirectory()) refuse(`${lastLink ? 'non-directory ancestor' : 'has a non-directory ancestor'} (${current}).`, context ?? lastLink, !lastLink);
1846
2535
  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);
2536
+ if (stat.isDirectory()) {
2537
+ refuseDirectory(current, context ?? lastLink);
2538
+ }
2539
+ if (!stat.isFile()) refuse('a submodule or other non-regular file. pdd sends only regular files.', context ?? lastLink);
2540
+ 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);
2541
+ 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
2542
  const file = { path, stat, size: Number(stat.size), observed, ...(presenceOnly && !diskVisible.has(current) ? {presenceOnly:true} : {}), ...(lastLink ? { target: current } : {}) };
1851
2543
  snapshots.set(path, file); return file;
1852
2544
  }
1853
2545
  }
1854
- refuse('a folder or other non-regular file.');
2546
+ refuseDirectory(resolved.join('/'));
1855
2547
  }
1856
2548
  function bytes(file) {
1857
2549
  if (file.bytes) return file.bytes;
@@ -1905,13 +2597,13 @@ function preparedText(root, visible, path, text, format,workspace) {
1905
2597
  }
1906
2598
  }
1907
2599
 
1908
- function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=tests === undefined,validateCriteria=true,allowMissingInterfaces=true }, strict = false, ports = {}) {
2600
+ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=true,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=tests === undefined,validateCriteria=true,allowMissingInterfaces=true,stepIds=[] }, strict = false, ports = {}) {
1909
2601
  const { isStoryPath, matchTests } = requireSelectionPorts(ports);
1910
2602
  const headBefore = gitHead(root);
1911
2603
  const policyBefore=JSON.stringify(loadRuntimeWorkspace({root}));workspace=boundedWorkspace(root,workspace);
1912
2604
  const names = gitFiles(root), visible = new Set(names), overlay = new Map(), payload = new Map(), queue = [], visited = new Set();
1913
2605
  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();
2606
+ const effective = new Map(), provenance = new Map(), edges = new Map(), shared = new Set(), footprintPayload = new Map(), storyContexts = new Map();
1915
2607
  let selecting = true;
1916
2608
  const unavailable = new Map();
1917
2609
  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 +2658,38 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
1966
2658
  {message:`${file.path}: ${authority.message}`,hint:'Restore the Story path selected by the test name, then run the selection again.'});
1967
2659
  if (typeof doc?.story_path === 'string' && !documentRefusal(doc, file.path, { allowOmittedCriteria: true })) {
1968
2660
  add(doc.story_path, file.path, 'story');
1969
- if (validateCriteria) {
2661
+ if (validateCriteria || stepIds.length) {
1970
2662
  const storySource = bytes(inspect(doc.story_path, file.path)).toString('utf8');
1971
2663
  const partial = partialTestRefusal(doc);
1972
- const resolved = partial ? { doc, changed: false, refusal: null } : resolveScenarioCriteria(doc, storySource);
2664
+ let resolved = partial ? { doc, changed: false, refusal: null } : resolveScenarioCriteria(doc, storySource);
2665
+ let checkedStory = storySource;
2666
+ if (stepIds.length && (!tests || tests.includes(file.path)) && !resolved.refusal) {
2667
+ if (partial) throw Object.assign(new PreflightError(4, `${file.path}: ${partial.message}`), partial);
2668
+ const projection = selectDiagnosticSteps(resolved.doc, stepIds);
2669
+ if (projection.refusal) throw Object.assign(new PreflightError(4, `${file.path}: ${projection.refusal.message}`), projection.refusal);
2670
+ storyContexts.set(doc.story_path, storySource);
2671
+ checkedStory = diagnosticStoryText(storySource, projection.doc.criteria);
2672
+ const projectionIssue = diagnosticStoryProjectionRefusal(doc.story_path, storySource, checkedStory);
2673
+ if (projectionIssue) throw Object.assign(new PreflightError(4, `${file.path}: ${projectionIssue.message}`), projectionIssue);
2674
+ // Omitted criterion prose cannot grant scope authority. Keep the
2675
+ // uploaded Story conservative too, even when deleting that prose
2676
+ // removes the reason its authored boundary was rejected.
2677
+ if (runtimeBoundary(doc.story_path, storySource) === null && runtimeBoundary(doc.story_path, checkedStory) !== null) {
2678
+ checkedStory += '\n\n<!-- Diagnostic subset retains authored full dependency closure. -->\n';
2679
+ }
2680
+ const storyFile = inspect(doc.story_path, file.path), storyBytes = Buffer.from(checkedStory, 'utf8');
2681
+ const projected = {...storyFile,bytes:storyBytes,size:storyBytes.length};
2682
+ effective.set(doc.story_path, projected); footprintPayload.set(doc.story_path, projected);
2683
+ if (selecting) payload.set(doc.story_path, projected);
2684
+ resolved = {...resolved,doc:projection.doc,changed:true};
2685
+ }
1973
2686
  if (resolved.refusal && needsCriteriaResolution(doc)) {
1974
2687
  throw Object.assign(new PreflightError(4, `${file.path}: ${resolved.refusal.message}`), resolved.refusal,
1975
2688
  { message: `${file.path}: ${resolved.refusal.message}`, hint: 'Fix the scenario criteria or Story acceptance list, then run the selection again.' });
1976
2689
  }
1977
2690
  if (resolved.changed && !resolved.refusal) content = Buffer.from(stringifyScenarioJson(resolved.doc), 'utf8');
1978
2691
  if (!resolved.refusal && !scenarioShapeRefusal(resolved.doc, file.path)) {
1979
- const plan = capturedCriterionPlan(resolved.doc, storyCriteria(storySource), file.path);
2692
+ const plan = capturedCriterionPlan(resolved.doc, storyCriteria(checkedStory), file.path);
1980
2693
  if (resolved.changed || (plan?.not_checked.length && plan.checked)) {
1981
2694
  content = Buffer.from(stringifyScenarioJson({ ...resolved.doc, criteria: plan.criteria,
1982
2695
  ...(plan?.not_checked.length ? { check_exemptions: plan.not_checked.map(item => ({ criterion_id: item.criterion_id, reason: 'out-of-scope', detail: item.reason })) } : {}) }), 'utf8');
@@ -2034,7 +2747,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2034
2747
  }
2035
2748
  for (const path of overlay.keys()) add(path, 'prepareSource');
2036
2749
  }
2037
- if (visible.has(SOURCE_CONFIG)) {
2750
+ if (sourceIncludes && visible.has(SOURCE_CONFIG)) {
2038
2751
  try {
2039
2752
  const config = overlay.get(SOURCE_CONFIG)??inspectRaw(SOURCE_CONFIG, SOURCE_CONFIG, false, false, true);
2040
2753
  let doc;
@@ -2053,6 +2766,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2053
2766
  const named = matchTests(onDisk.storyFiles, outsideFixtureProjects([...onDisk.visible, ...overlay.keys()], excluded)).tests.filter(test=>!test.problem);
2054
2767
  const allNamed=matchTests(onDisk.storyFiles,discoveryNames).tests.flatMap(test=>(test.files??[test.path]).map(path=>({...test,path})));
2055
2768
  const selected = tests ?? named.map(test=>test.path);
2769
+ 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
2770
  for (const path of selected) add(path, 'Selected test',path.endsWith('.prompt.md')?'context':isStoryPath(path)?'story':'test');
2057
2771
  if (appMap) { add(appMap, 'App map', 'app-map'); shared.add(sourcePath(appMap,'App map')); }
2058
2772
  const storyTests = new Map(), boundaries = new Map();
@@ -2112,7 +2826,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2112
2826
  } else {
2113
2827
  if (role === 'story') {
2114
2828
  const notes=[];
2115
- let boundary=runtimeBoundary(path,text,{notes});
2829
+ let boundary=runtimeBoundary(path,storyContexts.get(path) ?? text,{notes});
2116
2830
  if (boundary) {
2117
2831
  try {
2118
2832
  // Validate all members before admitting any boundary-only source.
@@ -2130,7 +2844,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,workspace=loadR
2130
2844
  boundaries.set(path,{boundary,notes});
2131
2845
  for (const member of boundary ?? []) add(member,path);
2132
2846
  }
2133
- for (const raw of markdownContext(text)) { const context = contextPath(raw, path, visible); if (context) add(context, path); }
2847
+ for (const raw of markdownContext(storyContexts.get(path) ?? text)) { const context = contextPath(raw, path, visible); if (context) add(context, path); }
2134
2848
  if (path.endsWith('.prompt.md')) {
2135
2849
  for (const block of interfaceBlocks(text)) {
2136
2850
  let doc;