@promptdriven/runtime-client 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +152 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +974 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/live-local-bridge.mjs +178 -0
  18. package/src/runtime/live-local.mjs +181 -0
  19. package/src/runtime/product-composition.mjs +384 -0
  20. package/src/runtime/run-program.mjs +797 -0
  21. package/src/runtime/runtime-binding-plan.mjs +145 -0
  22. package/src/runtime/runtime-bindings.mjs +81 -0
  23. package/src/runtime/runtime-check-plan.mjs +411 -0
  24. package/src/runtime/runtime-client.mjs +8114 -0
  25. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  26. package/src/runtime/runtime-markdown.mjs +215 -0
  27. package/src/runtime/runtime-outcome.mjs +468 -0
  28. package/src/runtime/runtime-output.mjs +752 -0
  29. package/src/runtime/runtime-preflight.mjs +3832 -0
  30. package/src/runtime/runtime-slots.mjs +462 -0
  31. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  32. package/src/runtime/runtime-workspace.mjs +52 -0
  33. package/src/runtime/scenario-json.mjs +257 -0
  34. package/src/runtime/secret-redaction.mjs +54 -0
  35. package/src/runtime/try-doors.mjs +597 -0
  36. package/src/runtime/try-http.mjs +285 -0
  37. package/src/runtime/try-mcp.mjs +223 -0
  38. package/src/runtime/try-session.mjs +95 -0
  39. package/src/runtime/try-update-policy.mjs +43 -0
@@ -0,0 +1,3832 @@
1
+ // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: 82c0d4c07385035d6555f688ddda347268bd17777f02d8394079955bc0d7d0c9).
2
+ import { markdownLinks, markdownDefinitions, markdownSectionText } from './runtime-markdown.mjs';
3
+ import { buildBindingPlan, runtimeBoundary } from './runtime-binding-plan.mjs';
4
+ import { createHash } from 'node:crypto';
5
+ import { spawnSync } from 'node:child_process';
6
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, readlinkSync, realpathSync, writeFileSync } from 'node:fs';
7
+ import { basename, join, posix, isAbsolute, relative, resolve, sep } from 'node:path';
8
+ import { isDeepStrictEqual } from 'node:util';
9
+ import { expandSource } from './contract-refs.mjs';
10
+ import { checkDerivation, exactValue, parseScenarioJson, roundedNumberTokens, stringifyScenarioJson } from './scenario-json.mjs';
11
+ import {loadRuntimeWorkspace as loadWorkspacePolicy,allowsRuntimePath,requireRuntimePath as requireWorkspacePath} from './runtime-workspace.mjs';
12
+
13
+ function workspaceError(error){if(error?.code?.startsWith('workspace-'))throw Object.assign(new PreflightError(4,error.message),{code:error.code});throw error;}
14
+ function loadRuntimeWorkspace(input){try{return loadWorkspacePolicy(input);}catch(error){workspaceError(error);}}
15
+ function requireRuntimePath(policy,input){try{return requireWorkspacePath(policy,input);}catch(error){workspaceError(error);}}
16
+ function boundedWorkspace(root,supplied){const native=loadRuntimeWorkspace({root});if(!supplied||!supplied.configured)return native;if(!native.configured)return supplied;const allowed=[];for(const a of native.allowed_paths)for(const b of supplied.allowed_paths){if(a===b)allowed.push(a);else if(a.endsWith('/')&&b.startsWith(a))allowed.push(b);else if(b.endsWith('/')&&a.startsWith(b))allowed.push(a);}return Object.freeze({configured:true,allowed_paths:Object.freeze([...new Set(allowed)])});}
17
+ export const TEST_SCHEMA = 'prompt-runtime.program-scenario.v1';
18
+ // The interpreter's upload limit (server/uploads.py: MAX_UPLOAD 10 MiB, at most 10,000 files).
19
+ // The only size limit on what pdd sends; over it, pdd names the largest files with their sizes.
20
+ export const LIMITS = Object.freeze({ bytes: 10_485_760, files: 10_000 });
21
+ const TOP_KEYS = new Set(['schema_version', 'story_path', 'criteria', 'initial_world', 'steps', 'entry_paths', 'simulation', '$simulation',
22
+ 'check_exemptions', 'context', 'context_byte_budget', 'criteria_scope', 'prompt_mappings', 'app_maps']);
23
+ const REQUIRED_KEYS = ['schema_version', 'criteria', 'initial_world', 'steps'];
24
+ const REQUIRED_STEP_KEYS = ['step_id', 'entry_path', 'operation', 'input', 'checks'];
25
+ const OPTIONAL_STEP_KEYS = ['expected_error', 'simulation_overrides', 'model'];
26
+ const STEP_KEYS = new Set([...REQUIRED_STEP_KEYS, ...OPTIONAL_STEP_KEYS]);
27
+ const RULE_OPS = new Set(['at_most', 'at_least', 'lt', 'lte', 'gt', 'gte', 'not_contains', 'all_in', 'equals_ignore_case']);
28
+ const EXACT_OPS = new Set(['equals', 'not_equals', 'one_of', 'count', 'integer_relation', ...RULE_OPS]);
29
+ const SCHEMA_RULES = new Set(['type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'oneOf',
30
+ 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'pattern',
31
+ 'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties']);
32
+ const SCHEMA_NOTES = new Set(['title', 'description', 'default', 'examples', 'format', '$comment', '$schema', '$id']);
33
+
34
+ // The engine's _INTERFACE regex (prompt_program_discovery.py, eae2202a).
35
+ const INTERFACE = /<details\b[^>]*>\s*<summary\b[^>]*>\s*(?:<strong\b[^>]*>\s*)?Runtime\s+interface(?:\s*:\s*[^<]+?)?\s*(?:<\/strong\s*>\s*)?(?:\s*:\s*[^<]+?)?\s*<\/summary\s*>\s*```json\b\s*([\s\S]*?)\s*```\s*<\/details\s*>/gid;
36
+
37
+ export class PreflightError extends Error {
38
+ constructor(exitCode, message) { super(message); this.name = 'PreflightError'; this.exitCode = exitCode; }
39
+ }
40
+
41
+ export const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
42
+ export const interfaceBlocks = text => [...text.matchAll(INTERFACE)];
43
+ export const proseSha256 = text => sha256(Buffer.from(text.replace(INTERFACE, ''), 'utf8'));
44
+
45
+ // Python str.isspace, str.splitlines and str.split, so story criteria equal the engine's.
46
+ const PY_SPACE = '[\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
47
+ const pyStrip = text => text.replace(new RegExp(`^${PY_SPACE}+|${PY_SPACE}+$`, 'g'), '');
48
+ const pyWords = text => text.split(new RegExp(`${PY_SPACE}+`)).filter(Boolean).join(' ');
49
+ function pySplitLines(text) {
50
+ const lines = text.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/);
51
+ if (lines.at(-1) === '') lines.pop();
52
+ return lines;
53
+ }
54
+ const AC_HEADING = /(?<![^\n])##[ \t]+Acceptance(?:[ \t]+Criteria)?[ \t]*(?![^\n])/i;
55
+ const NEXT_HEADING = /(?<![^\n])##[ \t]+/;
56
+ const NUMBERED_ITEM = /^([1-9][0-9]*)[.)][ \t]+(.+)$/;
57
+ const BULLET_ITEM = /(?<![^\n])[ \t]*[-*][ \t]+([\s\S]+?)(?=\n[ \t]*[-*][ \t]+|(?![\s\S]))/g;
58
+ const AC_ID = /^ac-?([1-9][0-9]*)$/i;
59
+
60
+ function numberedStoryCriteria(source, { requireHeading = false } = {}) {
61
+ const heading = AC_HEADING.exec(source);
62
+ if (requireHeading && !heading) return [];
63
+ const body = heading ? source.slice(heading.index + heading[0].length) : source;
64
+ const result = [];
65
+ let current = null, expected = 1;
66
+ for (const line of pySplitLines(body)) {
67
+ const match = NUMBERED_ITEM.exec(line);
68
+ if (match) {
69
+ if (Number(match[1]) !== expected) {
70
+ if (result.length || current !== null) break;
71
+ continue;
72
+ }
73
+ if (current !== null) result.push(current.join(' '));
74
+ current = [pyStrip(match[2])];
75
+ expected += 1;
76
+ } else if (current !== null) {
77
+ if (!pyStrip(line) || line.startsWith('#')) { result.push(current.join(' ')); current = null; }
78
+ else current.push(pyStrip(line));
79
+ }
80
+ }
81
+ if (current !== null) result.push(current.join(' '));
82
+ return result;
83
+ }
84
+
85
+ // A port of the engine's explicit_story_criteria (program_scenario.py, eae2202a).
86
+ export function storyCriteria(source) {
87
+ const result = numberedStoryCriteria(source);
88
+ if (result.length) return result;
89
+ const heading = AC_HEADING.exec(source);
90
+ if (!heading) return result;
91
+ const body = source.slice(heading.index + heading[0].length);
92
+ const next = NEXT_HEADING.exec(body);
93
+ const section = next ? body.slice(0, next.index) : body;
94
+ return [...section.matchAll(BULLET_ITEM)].map(match => pyWords(match[1]));
95
+ }
96
+
97
+ export function gitFiles(root) {
98
+ const listed = spawnSync('git', ['ls-files', '-z', '-co', '--exclude-standard'], { cwd: root, maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
99
+ if (listed.status !== 0) throw new PreflightError(5, 'pdd could not list the Git files of this repository.');
100
+ return [...new Set(listed.stdout.toString('utf8').split('\0').filter(Boolean))].sort();
101
+ }
102
+
103
+ const COMMIT_HEX = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
104
+ function gitHead(root) {
105
+ const rev = spawnSync('git', ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
106
+ if (rev.status !== 0) return null;
107
+ const sha = rev.stdout.trim().toLowerCase();
108
+ return COMMIT_HEX.test(sha) ? sha : null;
109
+ }
110
+ function gitTreeBlobs(root, commit) {
111
+ const tree = spawnSync('git', ['ls-tree', '-r', '-z', commit], { cwd: root, maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
112
+ if (tree.status !== 0) return null;
113
+ const entries = new Map();
114
+ for (const record of tree.stdout.toString('utf8').split('\0')) {
115
+ if (!record) continue;
116
+ const tab = record.indexOf('\t');
117
+ if (tab < 0) continue;
118
+ const [mode, type, oid] = record.slice(0, tab).trim().split(/\s+/);
119
+ const path = record.slice(tab + 1);
120
+ if (path && oid && type === 'blob') entries.set(path, { mode, oid: oid.toLowerCase() });
121
+ }
122
+ return entries;
123
+ }
124
+ function gitBlobOid(buf, algorithm = 'sha1') {
125
+ return createHash(algorithm).update(`blob ${buf.length}\0`).update(buf).digest('hex');
126
+ }
127
+
128
+ const statOf = path => { try { return lstatSync(path, { bigint: true }); } catch (error) { if (['ENOENT', 'ENAMETOOLONG'].includes(error.code)) return null; throw error; } };
129
+ const readText = (root, path) => {
130
+ requireRuntimePath(loadRuntimeWorkspace({root}),{path,from:'Source read'});
131
+ const stat=statOf(join(root,path));
132
+ sourceLimit([{path,size:Number(stat?.size ?? 0)}]);
133
+ return readFileSync(join(root,path),'utf8');
134
+ };
135
+ const storyName = path => basename(path).replace(/\.md$/, '');
136
+ const titleOf = text => text.split('\n').find(line => line.startsWith('# '))?.slice(2).trim() || null;
137
+ export const hasPromptInterface = (root, path) => interfaceBlocks(readText(root, path)).length > 0;
138
+
139
+ function requireSelectionPorts(ports) {
140
+ if (
141
+ typeof ports?.isStoryPath !== 'function' ||
142
+ typeof ports?.hasAcceptance !== 'function' ||
143
+ typeof ports?.matchTests !== 'function' ||
144
+ typeof ports?.orphanSummary !== 'function'
145
+ ) {
146
+ throw Object.assign(new Error('Test selection ports (isStoryPath, hasAcceptance, matchTests, orphanSummary) are not bound.'), { unboundPort: true });
147
+ }
148
+ return ports;
149
+ }
150
+
151
+ // Tests, stories and Git-visible regular files of one repo.
152
+ export function findTests({ root, files = gitFiles(root), workspace, excludeFixtureProjects = false }, ports = {}) {
153
+ return discoverTests(root, files, false, workspace, excludeFixtureProjects, ports);
154
+ }
155
+
156
+ // Identify projects by Git-visible names before inspecting any Story or test content.
157
+ function fixtureProjectRoots(root, files) {
158
+ const directories = new Map();
159
+ for (const path of files) {
160
+ const parts = path.split('/');
161
+ if (parts[0] !== 'test' || parts[1] !== 'fixtures') continue;
162
+ // Do not follow an unchecked link while classifying a name.
163
+ let safe = true;
164
+ for (let i = 1; i < parts.length; i++) {
165
+ const ancestor = statOf(join(root, ...parts.slice(0, i)));
166
+ if (!ancestor?.isDirectory()) { safe = false; break; }
167
+ }
168
+ if (!safe) continue;
169
+ const stat = statOf(join(root, path));
170
+ if (!stat || (!stat.isFile() && !stat.isSymbolicLink())) continue;
171
+ for (let i = 3; i < parts.length - 1; i++) {
172
+ if (parts[i] !== 'user_stories' && parts[i] !== 'tests') continue;
173
+ const project = parts.slice(0, i).join('/');
174
+ if (!directories.has(project)) directories.set(project, new Set());
175
+ directories.get(project).add(parts[i]);
176
+ }
177
+ }
178
+ return [...directories].filter(([, dirs]) => dirs.has('user_stories') && dirs.has('tests')).map(([path]) => path).sort();
179
+ }
180
+
181
+ const outsideFixtureProjects = (files, roots) => files.filter(path => !roots.some(root => path.startsWith(`${root}/`)));
182
+
183
+ export function discoveryVisibleFiles({ root, files = gitFiles(root), workspace = loadRuntimeWorkspace({ root }), excludeFixtureProjects = false }) {
184
+ const excluded = excludeFixtureProjects ? fixtureProjectRoots(root, files) : [];
185
+ const discoveryFiles = new Set(outsideFixtureProjects(files, excluded));
186
+ const policy = boundedWorkspace(root, workspace);
187
+ const visible = new Set();
188
+ let linkedFiles = policy.configured ? filePort(root, new Set(files), false, policy) : undefined;
189
+ for (const path of files) {
190
+ if (!allowsRuntimePath(policy, path)) continue;
191
+ let stat = statOf(join(root, path));
192
+ if (policy.configured || stat?.isSymbolicLink()) {
193
+ linkedFiles ??= sourceFilePort(root, new Set(files));
194
+ try {
195
+ const info = linkedFiles.stat({ path });
196
+ stat = { isFile: () => info.exists, size: BigInt(info.size) };
197
+ } catch { continue; }
198
+ }
199
+ if (!stat?.isFile()) continue;
200
+ if (discoveryFiles.has(path)) visible.add(path);
201
+ }
202
+ return visible;
203
+ }
204
+
205
+ // Git-visible regular files and Stories: discovery reads Story files, never JSON files.
206
+ function discoverStories(root, files, strict = false, workspace=loadRuntimeWorkspace({root}), discoveryFiles = null, ports = {}) {
207
+ const { isStoryPath, hasAcceptance } = requireSelectionPorts(ports);
208
+ workspace=boundedWorkspace(root,workspace);
209
+ const visible = new Set(), stories = [], storyFiles = [], titles = new Map(), storyTexts = new Map(), warnings = [], linkedPaths = new Set(), sizes = new Map();
210
+ let linkedFiles = strict||workspace.configured ? filePort(root, new Set(files), strict,workspace) : undefined;
211
+ for (const path of files) {
212
+ if(!allowsRuntimePath(workspace,path))continue;
213
+ let stat = strict ? null : statOf(join(root, path)), linked = false;
214
+ if (strict || workspace.configured || stat?.isSymbolicLink()) {
215
+ linkedFiles ??= sourceFilePort(root, new Set(files));
216
+ try {
217
+ const info = linkedFiles.stat({path});
218
+ stat = { isFile: () => info.exists, size: BigInt(info.size) }; linked = true;
219
+ } catch { continue; } // Unrelated unsafe links do not select or refuse source.
220
+ }
221
+ if (!stat?.isFile()) continue;
222
+ visible.add(path); sizes.set(path, Number(stat.size));
223
+ if (linked) linkedPaths.add(path);
224
+ if ((!discoveryFiles || discoveryFiles.has(path)) && isStoryPath(path)) {
225
+ // Every Story file can own a test by its name. An index (PLAN.md, README.md) or a file with no acceptance
226
+ // criteria section is not listed as a Story (2048 session, 0.1.6), so it never gets a "has no test" line.
227
+ storyFiles.push(path);
228
+ if (stat.size > LIMITS.bytes) { warnings.push(`Warning: ${path}: discovery unavailable (too big; limit 10 MB).`); continue; }
229
+ let text;
230
+ try { text = linked ? linkedFiles.read({path}).content : readText(root, path); }
231
+ catch (error) {
232
+ if (!(error instanceof PreflightError && error.exitCode === 4) && !['EACCES','EPERM','EISDIR','ENOENT'].includes(error.code)) throw error;
233
+ warnings.push(`Warning: ${path}: discovery unavailable (${error.code ?? error.message}).`); continue;
234
+ }
235
+ titles.set(path, titleOf(text));
236
+ storyTexts.set(path, text);
237
+ if (hasAcceptance(text)) stories.push({ path, name: storyName(path), title: titleOf(text) });
238
+ }
239
+ }
240
+ const read = path => strict || linkedPaths.has(path) ? linkedFiles.read({path}).content : readText(root, path);
241
+ return { visible, stories, storyFiles, titles, storyTexts, warnings, sizes, read };
242
+ }
243
+
244
+ function discoverTests(root, files, strict = false,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=false,ports={}) {
245
+ const { matchTests, orphanSummary } = requireSelectionPorts(ports);
246
+ const excluded = excludeFixtureProjects ? fixtureProjectRoots(root, files) : [];
247
+ const discoveryFiles = new Set(outsideFixtureProjects(files, excluded));
248
+ const { visible, stories, storyFiles, titles, storyTexts, warnings: storyWarnings, sizes, read } = discoverStories(root, files, strict,workspace,discoveryFiles,ports);
249
+ const named = new Set(stories.map(story => story.path)), rule = matchTests(storyFiles, [...visible].filter(path => discoveryFiles.has(path)));
250
+ rule.untested = rule.untested.filter(item => named.has(item.storyPath));
251
+ const tests = rule.tests.map(entry => {
252
+ const size = sizes.get(entry.path);
253
+ const test = { path: entry.path, files: entry.files, story: entry.story, storyPath: entry.storyPath, storyPaths: entry.storyPaths, title: titles.get(entry.storyPath) ?? entry.story };
254
+ if (entry.problem) return { ...test, error: entry.problem };
255
+ if (size > LIMITS.bytes) return { ...test, error: `${entry.path} is ${formatSize(size)}. The upload limit is 10 MB, so pdd cannot send it.` };
256
+ // A matched test is read in full, at any size below the upload limit.
257
+ try {
258
+ const rawDoc = JSON.parse(read(entry.path));
259
+ let doc = rawDoc, criteriaRefusal = null, resolvedStorySource;
260
+ const hasRefCriteria = isObject(doc?.criteria) && (Object.hasOwn(doc.criteria, '$contract') || Object.hasOwn(doc.criteria, '$seed'))
261
+ || Array.isArray(doc?.criteria) && doc.criteria.some(item => isObject(item) && (Object.hasOwn(item, '$contract') || Object.hasOwn(item, '$seed')));
262
+ if (isObject(doc) && !hasRefCriteria && needsCriteriaResolution(doc) && !documentRefusal(doc, entry.path, { allowOmittedCriteria: true })
263
+ && typeof doc.story_path === 'string' && doc.story_path && visible.has(doc.story_path)
264
+ && (!entry.storyPath || doc.story_path === entry.storyPath) && !partialTestRefusal(doc)) {
265
+ const storySource = storyTexts.get(doc.story_path);
266
+ if (typeof storySource === 'string') {
267
+ resolvedStorySource = storySource;
268
+ const resolved = resolveScenarioCriteria(doc, storySource);
269
+ if (resolved.changed && !resolved.refusal) doc = resolved.doc;
270
+ else if (resolved.refusal) criteriaRefusal = resolved.refusal;
271
+ }
272
+ }
273
+ const item = { ...test, doc };
274
+ Object.defineProperty(item, 'rawDoc', { value: rawDoc });
275
+ if (resolvedStorySource !== undefined) Object.defineProperty(item, 'storySource', { value: resolvedStorySource });
276
+ if (criteriaRefusal) Object.defineProperty(item, 'criteriaRefusal', { value: criteriaRefusal });
277
+ return item;
278
+ }
279
+ catch (error) {
280
+ if (error instanceof SyntaxError) return { ...test, error: `${entry.path} is not valid JSON: ${error.message}` };
281
+ if (error.code === 'EACCES' || error.code === 'EISDIR' || error.code === 'ENOENT' || error instanceof PreflightError) return { ...test, error: `${entry.path} cannot be read: ${error.code ?? error.message}.` };
282
+ throw error;
283
+ }
284
+ });
285
+ const warnings = [...excluded.map(path => `Warning: skipped nested fixture project ${path}.`), ...storyWarnings, ...rule.tests.filter(entry => entry.problem).map(entry => `Warning: ${entry.problem}`),
286
+ ...rule.untested.map(item => `Warning: ${item.line}`), ...(rule.orphans.length ? [orphanSummary(rule.orphans)] : [])];
287
+ // Discover declarations from already bounded Story reads. Owner files are
288
+ // opened only after explicit lint selection.
289
+ const nativeSelections = stories.flatMap(story => {
290
+ const section = /^## Native validation\s*\n([\s\S]*?)(?=^## |$(?![\s\S]))/m.exec(read(story.path));
291
+ return section ? [{ storyPath: story.path, story: story.name, section: section[1] }] : [];
292
+ });
293
+ const found={ root, visible, tests, stories, nativeSelections, warnings, untested: rule.untested, orphans: rule.orphans, excludedFixtureProjects: excluded, discoveryVisible: new Set([...visible].filter(path => discoveryFiles.has(path))) };
294
+ Object.defineProperty(found,'workspace',{value:workspace});return found;
295
+ }
296
+
297
+ const refusal = (code, section, message, extra = {}) => ({ code, section, message, ...extra });
298
+ // The PDD interpreter's whole-number range today: prompt_runtime/program_scenario.py (_validate_scenario_integers)
299
+ // for test values and prompt_runtime/graph_runtime_protocol.py for schema bounds. Change it only with the interpreter.
300
+ const INTERPRETER_INTEGERS = { min: -(2n ** 53n - 1n), max: 2n ** 53n - 1n, text: '-9007199254740991 through 9007199254740991' };
301
+ const outsideInterpreter = value => typeof value === 'bigint' && (value < INTERPRETER_INTEGERS.min || value > INTERPRETER_INTEGERS.max);
302
+ // The interpreter's section of a test value: keys joined by ".", indexes as [N] (steps[10].input.seconds).
303
+ const interpreterSection = path => path.reduce((text, part) => typeof part === 'number' ? `${text}[${part}]` : text ? `${text}.${part}` : String(part), '');
304
+ // The exact Number spelling that the interpreter admits: a token with an exponent, so it is no integer literal, that
305
+ // reads back as exactly this Number. String(n) has an exponent only from 1e21; below that (2^53 <= n < 1e21) it is plain
306
+ // digits, which the interpreter refuses and which, as an integer literal, may even name another whole number.
307
+ export function exactNumberSpelling(n) {
308
+ const text = /e/i.test(String(n)) ? String(n) : n.toExponential();
309
+ return Number(text) === n ? text : null;
310
+ }
311
+ // Advice only: the interpreter is the one place that refuses; the test is still sent.
312
+ function interpreterIntegerWarning(doc, path) {
313
+ let found = null;
314
+ const visit = (value, at) => {
315
+ if (found) return;
316
+ if (outsideInterpreter(value)) found = { value, path: at };
317
+ else if (Array.isArray(value)) value.forEach((item, index) => visit(item, [...at, index]));
318
+ else if (isObject(value)) for (const [key, item] of Object.entries(value)) visit(item, [...at, key]);
319
+ };
320
+ visit(doc, []);
321
+ if (!found) return null;
322
+ const section = interpreterSection(found.path), nearest = Number(found.value), exact = Number.isFinite(nearest) && BigInt(nearest) === found.value ? exactNumberSpelling(nearest) : null;
323
+ const spelling = exact ? `If the parameter takes a Number, write its exact Number spelling ${exact}; the interpreter accepts it. ` : 'No JavaScript Number holds this value. ';
324
+ return `Warning: ${path} scenario-integer-out-of-range: ${section} is ${found.value}, outside the PDD interpreter's integer range ${INTERPRETER_INTEGERS.text}, `
325
+ + 'so the interpreter refuses this test before execution (0 AI calls). ' + spelling
326
+ + "Check the exact value in the repository's own vector test (RUNBOOK §17); do not change the input type or the expected value to fit the interpreter.";
327
+ }
328
+ // Advice only: integer schema bound tokens that the interpreter refuses (graph-schema-invalid).
329
+ function schemaBoundWarnings(prompt) {
330
+ const found = [], iface = prompt?.interface;
331
+ const visit = (schema, pointer) => {
332
+ if (!isObject(schema)) return;
333
+ if (schema.type === 'integer' || schema.type === 'number') for (const key of [...BOUND_FIELDS, 'multipleOf']) {
334
+ const bound = schemaValue(schema, key);
335
+ if (outsideInterpreter(bound)) found.push(`Warning: ${prompt.path} ${pointer}/${key} is ${bound}, outside the PDD interpreter's integer range ${INTERPRETER_INTEGERS.text}, so the interpreter refuses this bound (graph-schema-invalid, bound_text ${bound}).`);
336
+ }
337
+ if (isObject(schema.properties)) for (const [name, child] of Object.entries(schema.properties)) visit(child, `${pointer}/properties/${pointerOf([name]).slice(1)}`);
338
+ if (isObject(schema.items)) visit(schema.items, `${pointer}/items`);
339
+ if (isObject(schema.additionalProperties)) visit(schema.additionalProperties, `${pointer}/additionalProperties`);
340
+ if (Array.isArray(schema.oneOf)) schema.oneOf.forEach((variant, index) => visit(variant, `${pointer}/oneOf/${index}`));
341
+ };
342
+ for (const [index, entry] of (Array.isArray(iface?.entries) ? iface.entries : []).entries())
343
+ for (const key of ['input_schema', 'result_schema']) visit(entry?.[key], `/entries/${index}/${key}`);
344
+ for (const [index, resource] of (Array.isArray(iface?.resources) ? iface.resources : []).entries())
345
+ for (const [opIndex, operation] of (Array.isArray(resource?.operations) ? resource.operations : []).entries())
346
+ for (const key of ['arguments_schema', 'result_schema']) visit(operation?.[key], `/resources/${index}/operations/${opIndex}/${key}`);
347
+ return found;
348
+ }
349
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
350
+ const show = value => { const text = stringifyScenarioJson(value) ?? String(value); return text.length > 60 ? `${text.slice(0, 57)}...` : text; };
351
+ const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
352
+ function range(min, max, unit = '') {
353
+ const tail = unit ? ` ${unit}${(max ?? min) === 1 ? '' : 's'}` : '';
354
+ if (min !== undefined && max !== undefined) return `${min} to ${max}${tail}`;
355
+ return min !== undefined ? `at least ${min}${tail}` : `at most ${max}${tail}`;
356
+ }
357
+ // An exact whole number above 2^53 is a BigInt (scenario-json): it is an integer and a number.
358
+ const typeName = value => value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value === 'bigint' ? 'integer'
359
+ : typeof value === 'number' ? (Number.isInteger(value) ? 'integer' : 'number') : typeof value;
360
+ const numeric = value => typeof value === 'number' || typeof value === 'bigint';
361
+ const typeMatches = (value, type) => type === 'number' ? numeric(value) : type === 'integer' ? typeof value === 'bigint' || Number.isInteger(value) : typeName(value) === type;
362
+ // A schema number read with its own JSON token: an exact integer literal above 2^53 keeps its digits.
363
+ const schemaValue = (holder, key) => {
364
+ const value = holder?.[key], source = numberSources.get(holder)?.get(String(key));
365
+ return typeof value === 'number' && !Number.isSafeInteger(value) && typeof source === 'string' && /^-?(?:0|[1-9][0-9]*)$/.test(source) ? BigInt(source) : value;
366
+ };
367
+ // const and enum values read with their own tokens at every depth.
368
+ const exactSchemaValue = (holder, key) => {
369
+ const value = schemaValue(holder, key);
370
+ return Array.isArray(value) ? value.map((_, index) => exactSchemaValue(value, index))
371
+ : isObject(value) ? Object.fromEntries(Object.keys(value).map(name => [name, exactSchemaValue(value, name)])) : value;
372
+ };
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
+ }
389
+ const article = type => /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
390
+
391
+ function unknownKeyword(schema) {
392
+ if (!isObject(schema)) return null;
393
+ for (const [key, value] of Object.entries(schema)) {
394
+ if (!SCHEMA_RULES.has(key) && !SCHEMA_NOTES.has(key)) return key;
395
+ if (key === 'properties' && isObject(value)) for (const child of Object.values(value)) { const found = unknownKeyword(child); if (found) return found; }
396
+ if (key === 'items' || key === 'additionalProperties') { const found = unknownKeyword(value); if (found) return found; }
397
+ if (key === 'oneOf' && Array.isArray(value)) for (const child of value) { const found = unknownKeyword(child); if (found) return found; }
398
+ }
399
+ return null;
400
+ }
401
+
402
+ const either = items => items.length > 1 ? `${items.slice(0, -1).join(', ')} or ${items.at(-1)}` : items[0];
403
+ const variantNames = variants => [...new Set(variants.map(variant => typeof variant?.type === 'string' ? (variant.type === 'null' ? 'null' : article(variant.type)) : 'another shape'))];
404
+
405
+ // The JSON Schema check of rule P9: every problem, not only the first. Pattern misses are warnings (JS and Python regexes differ).
406
+ // Only a common regex subset is evidence of cross-runtime membership. Other
407
+ // syntax may still be checked by the runtime, but cannot establish overlap.
408
+ function portablePattern(source, value) {
409
+ // Character classes and end anchors differ outside this concrete domain.
410
+ // Empty JS classes are also invalid in Python, even with ASCII input.
411
+ if (/[^\x20-\x7e]/u.test(source) || /[^\x20-\x7e]/u.test(value) || /\[\^?\]/u.test(source)) return null;
412
+ if (/\\(?:[1-9bBAZzGkpPuU]|x|c)|\(\?|[\s\S]*[\u0080-\uffff]/u.test(source)) return null;
413
+ try { return new RegExp(source, 'u'); } catch { return null; }
414
+ }
415
+ function schemaRun(value, schema, tokens, equality = null) {
416
+ const problems = [], warnings = [], evidence = { miss: false, unknown: false };
417
+ schemaProblems(value, schema, tokens, problems, warnings, evidence, equality);
418
+ return { problems, warnings, state: problems.length || evidence.miss ? 'miss' : evidence.unknown ? 'unknown' : 'match' };
419
+ }
420
+ function schemaProblems(value, schema, tokens, out, warnings, evidence = { miss: false, unknown: false }, equality = null) {
421
+ const at = rule => out.push({ tokens, rule });
422
+ if (!isObject(schema)) return;
423
+ if (Array.isArray(schema.oneOf)) {
424
+ const runs = schema.oneOf.map(variant => schemaRun(value, variant, tokens, equality));
425
+ const fits = runs.filter(run => run.state === 'match').length;
426
+ if (fits > 1) return at(`fits more than one of the allowed shapes (oneOf). Make the shapes exclusive.`);
427
+ if (fits === 1) {
428
+ if (runs.some(run => run.state === 'unknown')) evidence.unknown = true;
429
+ return;
430
+ }
431
+ if (runs.some(run => run.state === 'unknown')) { evidence.unknown = true; return; }
432
+ evidence.miss = true;
433
+ const advisory = runs.find(run => !run.problems.length);
434
+ if (advisory) { warnings.push(...advisory.warnings); return; }
435
+ const same = schema.oneOf.findIndex(variant => typeof variant?.type === 'string' && typeMatches(value, variant.type));
436
+ if (same >= 0) { out.push(...runs[same].problems); return; }
437
+ return at(`is ${show(value)}. The prompt allows ${either(variantNames(schema.oneOf))}.`);
438
+ }
439
+ if (schema.type !== undefined) {
440
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
441
+ if (!types.some(type => typeMatches(value, type))) return at(`is ${show(value)}. The prompt wants ${types.map(article).join(' or ')}.`);
442
+ }
443
+ const wanted = exactSchemaValue(schema, 'const'), choices = Array.isArray(schema.enum) ? schema.enum.map((_, index) => exactSchemaValue(schema.enum, index)) : null;
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))}.`);
447
+ if (numeric(value)) {
448
+ const [minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf] = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'].map(key => schemaValue(schema, key));
449
+ if ((minimum !== undefined && value < minimum) || (maximum !== undefined && value > maximum)) at(`is ${show(value)}. The prompt allows ${range(minimum, maximum)}.`);
450
+ if (numeric(exclusiveMinimum) && value <= exclusiveMinimum) at(`is ${show(value)}. The prompt wants more than ${exclusiveMinimum}.`);
451
+ if (numeric(exclusiveMaximum) && value >= exclusiveMaximum) at(`is ${show(value)}. The prompt wants less than ${exclusiveMaximum}.`);
452
+ const whole = item => typeof item === 'bigint' || Number.isInteger(item);
453
+ if (numeric(multipleOf) && multipleOf > 0) {
454
+ // Exact remainder for whole numbers; a BigInt with a fractional step cannot be judged for sure here.
455
+ if (whole(value) && whole(multipleOf) && (typeof value === 'bigint' || typeof multipleOf === 'bigint')) {
456
+ if (BigInt(value) % BigInt(multipleOf) !== 0n) at(`is ${show(value)}. The prompt wants a multiple of ${multipleOf}.`);
457
+ } else if (typeof value === 'number' && typeof multipleOf === 'number') {
458
+ const ratio = value / multipleOf;
459
+ if (Math.abs(ratio - Math.round(ratio)) > 1e-9) at(`is ${show(value)}. The prompt wants a multiple of ${multipleOf}.`);
460
+ }
461
+ }
462
+ }
463
+ if (typeof value === 'string') {
464
+ const length = [...value].length;
465
+ if ((schema.minLength !== undefined && length < schema.minLength) || (schema.maxLength !== undefined && length > schema.maxLength)) {
466
+ at(`has ${plural(length, 'character')}. The prompt allows ${range(schema.minLength, schema.maxLength, 'character')}.`);
467
+ }
468
+ if (typeof schema.pattern === 'string') {
469
+ const pattern = portablePattern(schema.pattern, value);
470
+ if (!pattern) evidence.unknown = true;
471
+ const pointer = pointerOf(tokens);
472
+ if (pattern && !pattern.test(value)) {
473
+ evidence.miss = true;
474
+ warnings.push(`input${pointer ? ` ${pointer}` : ''} is ${show(value)}. It does not match the pattern ${schema.pattern}, so the interpreter will likely refuse it.`);
475
+ }
476
+ }
477
+ }
478
+ if (Array.isArray(value)) {
479
+ if ((schema.minItems !== undefined && value.length < schema.minItems) || (schema.maxItems !== undefined && value.length > schema.maxItems)) {
480
+ at(`has ${plural(value.length, 'item')}. The prompt allows ${range(schema.minItems, schema.maxItems, 'item')}.`);
481
+ }
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);
484
+ }
485
+ if (isObject(value)) {
486
+ const count = Object.keys(value).length;
487
+ if ((schema.minProperties !== undefined && count < schema.minProperties) || (schema.maxProperties !== undefined && count > schema.maxProperties)) {
488
+ at(`has ${plural(count, 'field')}. The prompt allows ${range(schema.minProperties, schema.maxProperties, 'field')}.`);
489
+ }
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.`);
491
+ const properties = isObject(schema.properties) ? schema.properties : {};
492
+ for (const [key, child] of Object.entries(value)) {
493
+ if (Object.hasOwn(properties, key)) schemaProblems(child, properties[key], [...tokens, key], out, warnings, evidence, equality);
494
+ else if (schema.additionalProperties === false) at(`has ${show(key)}. The prompt does not allow it.`);
495
+ else if (isObject(schema.additionalProperties)) schemaProblems(child, schema.additionalProperties, [...tokens, key], out, warnings, evidence, equality);
496
+ }
497
+ }
498
+ }
499
+
500
+ const hasReference = value => Array.isArray(value) ? value.some(hasReference)
501
+ : isObject(value) && (Object.hasOwn(value, '$step_result') || Object.values(value).some(hasReference));
502
+ const pointerOf = tokens => tokens.map(token => `/${String(token).replace(/~/g, '~0').replace(/\//g, '~1')}`).join('');
503
+ const sectionOf = (base, tokens) => tokens.reduce((text, token) => /^\d+$/.test(token) ? `${text}[${token}]` : `${text}.${token}`, base);
504
+
505
+ // P9 on one step input: {refusals, warnings}. An unknown schema keyword skips that input with a warning.
506
+ export function checkInput(input, schema, index) {
507
+ if (hasReference(input)) return { refusals: [], warnings: [] };
508
+ const keyword = unknownKeyword(schema);
509
+ if (keyword) return { refusals: [], warnings: [`steps[${index}] input was not checked here: the prompt schema uses "${keyword}". The interpreter still checks it.`] };
510
+ const problems = [], warnings = [];
511
+ schemaProblems(input, schema, [], problems, warnings);
512
+ const seen = new Set();
513
+ return {
514
+ refusals: problems.filter(problem => { const key = `${pointerOf(problem.tokens)} ${problem.rule}`; if (seen.has(key)) return false; seen.add(key); return true; })
515
+ .map(problem => refusal('invalid-input', sectionOf(`steps[${index}].input`, problem.tokens),
516
+ `steps[${index}] input${problem.tokens.length ? ` ${pointerOf(problem.tokens)}` : ''} ${problem.rule}`, { step: index + 1 })),
517
+ warnings: warnings.map(text => `steps[${index}] ${text}`),
518
+ };
519
+ }
520
+
521
+ // The engine's executable schema subset (graph_runtime_protocol.py, _validate_schema_node, eae2202a).
522
+ const SCHEMA_ANNOTATIONS = new Set(['default', 'description', 'title', 'examples', 'format']);
523
+ const SCHEMA_FORBIDDEN = new Set(['$ref', '$dynamicRef', 'anyOf', 'allOf', 'not', 'if', 'then', 'else', 'contains',
524
+ 'unevaluatedProperties', 'patternProperties', 'propertyNames', 'contentEncoding']);
525
+ const NUMBER_FIELDS = ['type', 'enum', 'const', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'];
526
+ const SCHEMA_FIELDS = { null: ['type', 'enum', 'const'], boolean: ['type', 'enum', 'const'], string: ['type', 'enum', 'const', 'minLength', 'maxLength', 'pattern'],
527
+ integer: NUMBER_FIELDS, number: NUMBER_FIELDS, array: ['type', 'items', 'enum', 'const', 'minItems', 'maxItems', 'uniqueItems'],
528
+ object: ['type', 'properties', 'required', 'additionalProperties', 'enum', 'const', 'minProperties', 'maxProperties'] };
529
+ const COUNT_FIELDS = ['minLength', 'maxLength', 'minItems', 'maxItems', 'minProperties', 'maxProperties'];
530
+ const BOUND_FIELDS = ['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum'];
531
+
532
+ function schemaRules(schema, pointer, out) {
533
+ const add = (code, rule) => out.push({ code, pointer, rule });
534
+ if (!isObject(schema) || !Object.keys(schema).length) return add('graph-schema-type-invalid', 'is not a schema. Use an object such as {"type": "string"}.');
535
+ if (Array.isArray(schema.type)) {
536
+ return add('graph-schema-type-list', `has a list of types (${schema.type.map(String).join(', ')}). Use "oneOf" with one schema for each type, for example {"oneOf": [{"type": "string"}, {"type": "null"}]}.`);
537
+ }
538
+ for (const key of Object.keys(schema)) if (SCHEMA_FORBIDDEN.has(key)) add('graph-schema-unsupported-keyword', `uses "${key}", which the interpreter does not support.${key === 'anyOf' ? ' Use "oneOf" with a complete schema for each alternative.' : ''}`);
539
+ if (Object.hasOwn(schema, 'oneOf')) {
540
+ for (const key of Object.keys(schema)) if (key !== 'oneOf' && !SCHEMA_ANNOTATIONS.has(key) && !SCHEMA_FORBIDDEN.has(key)) add('graph-schema-unsupported-keyword', `has "${key}" next to "oneOf". Put it inside each oneOf schema.`);
541
+ if (!Array.isArray(schema.oneOf) || !schema.oneOf.length) add('graph-schema-invalid', '"oneOf" must be a list of at least one schema.');
542
+ else {
543
+ schema.oneOf.forEach((variant, index) => schemaRules(variant, `${pointer}/oneOf/${index}`, out));
544
+ if (schema.oneOf.some((variant, index) => schema.oneOf.findIndex(other => isDeepStrictEqual(other, variant)) !== index)) add('graph-schema-invalid', '"oneOf" has the same schema twice.');
545
+ }
546
+ return annotationRules(schema, add);
547
+ }
548
+ const type = schema.type;
549
+ if (typeof type !== 'string' || !Object.hasOwn(SCHEMA_FIELDS, type)) {
550
+ return add('graph-schema-type-invalid', `${type === undefined ? 'has no "type"' : `has the type ${show(type)}`}. Use null, boolean, string, integer, number, array or object, or "oneOf".`);
551
+ }
552
+ const allowed = new Set(SCHEMA_FIELDS[type]);
553
+ for (const key of Object.keys(schema)) {
554
+ if (!allowed.has(key) && !SCHEMA_ANNOTATIONS.has(key) && !SCHEMA_FORBIDDEN.has(key)) add('graph-schema-unsupported-keyword', `uses "${key}", which a ${type} schema cannot have. It can have ${[...allowed].join(', ')}.`);
555
+ }
556
+ if (type === 'array') {
557
+ if (!Object.hasOwn(schema, 'items')) add('graph-schema-invalid', 'is an array with no "items". Add "items" with the schema of one item.');
558
+ else schemaRules(schema.items, `${pointer}/items`, out);
559
+ }
560
+ if (type === 'object') {
561
+ if (schema.additionalProperties !== false) add('graph-schema-open-object', 'needs "additionalProperties": false.');
562
+ const properties = isObject(schema.properties) ? schema.properties : null, required = schema.required;
563
+ if (!properties) add('graph-schema-invalid', 'needs "properties": an object with one schema for each field (it may be empty).');
564
+ if (!Array.isArray(required)) add('graph-schema-invalid', 'needs "required": a list of the property names that must be present. It may be empty; a property that is not in the list is optional.');
565
+ else {
566
+ const wrong = required.find(name => typeof name !== 'string' || !properties || !Object.hasOwn(properties, name));
567
+ if (wrong !== undefined) add('graph-schema-invalid', `has ${show(wrong)} in "required", but not in "properties".`);
568
+ else if (new Set(required).size !== required.length) add('graph-schema-invalid', 'names a property twice in "required".');
569
+ }
570
+ for (const [name, child] of Object.entries(properties ?? {})) schemaRules(child, `${pointer}/properties/${pointerOf([name]).slice(1)}`, out);
571
+ }
572
+ for (const key of COUNT_FIELDS) if (Object.hasOwn(schema, key) && !(Number.isInteger(schema[key]) && schema[key] >= 0)) add('graph-schema-invalid', `"${key}" must be a whole number of 0 or more.`);
573
+ for (const key of BOUND_FIELDS) if (Object.hasOwn(schema, key) && typeof schema[key] !== 'number') add('graph-schema-invalid', `"${key}" must be a number.`);
574
+ if (Object.hasOwn(schema, 'multipleOf') && !(typeof schema.multipleOf === 'number' && schema.multipleOf > 0)) add('graph-schema-invalid', '"multipleOf" must be a number above 0.');
575
+ if (Object.hasOwn(schema, 'pattern') && typeof schema.pattern !== 'string') add('graph-schema-invalid', '"pattern" must be a string.');
576
+ if (Object.hasOwn(schema, 'uniqueItems') && typeof schema.uniqueItems !== 'boolean') add('graph-schema-invalid', '"uniqueItems" must be true or false.');
577
+ if (Object.hasOwn(schema, 'enum')) {
578
+ if (!Array.isArray(schema.enum) || !schema.enum.length) add('graph-schema-invalid', '"enum" must be a list of at least one value.');
579
+ else if (schema.enum.some((item, index) => schema.enum.findIndex(other => isDeepStrictEqual(other, item)) !== index)) add('graph-schema-invalid', '"enum" has the same value twice.');
580
+ else if (schema.enum.some(item => !typeMatches(item, type))) add('graph-schema-invalid', `"enum" has a value that is not ${article(type)}.`);
581
+ }
582
+ if (Object.hasOwn(schema, 'const') && !typeMatches(schema.const, type)) add('graph-schema-invalid', `"const" is not ${article(type)}.`);
583
+ if (Object.hasOwn(schema, 'default') && !typeMatches(schema.default, type)) add('graph-schema-invalid', `"default" is not ${article(type)}.`);
584
+ annotationRules(schema, add);
585
+ }
586
+
587
+ function annotationRules(schema, add) {
588
+ for (const key of ['description', 'title', 'format']) if (Object.hasOwn(schema, key) && typeof schema[key] !== 'string') add('graph-schema-invalid', `"${key}" must be a string.`);
589
+ if (Object.hasOwn(schema, 'examples') && !Array.isArray(schema.examples)) add('graph-schema-invalid', '"examples" must be a list.');
590
+ }
591
+
592
+ // Preserve numeric JSON spelling only for parsed prompt interfaces; ordinary callers supply JSON values.
593
+ const numberSources = new WeakMap();
594
+ function limitProblems(iface) {
595
+ const out = [], keys = ['max_steps', 'max_model_calls'];
596
+ const add = (code, pointer, rule, hint) => out.push({code,pointer,rule,hint});
597
+ const shapeHint = 'Fix limits: use exactly "max_steps" and "max_model_calls", each an integer of at least 1.';
598
+ if (!isObject(iface) || !Object.hasOwn(iface, 'limits')) {
599
+ add('invalid-interface', '/limits', 'has no limits object.', 'Add "limits": {"max_steps": 1, "max_model_calls": 1}.');
600
+ return out;
601
+ }
602
+ const limits = iface.limits;
603
+ if (!isObject(limits)) {
604
+ add('invalid-limits', '/limits', 'must be an object with exactly max_steps and max_model_calls.', shapeHint);
605
+ return out;
606
+ }
607
+ for (const key of Object.keys(limits)) if (!keys.includes(key)) {
608
+ add('invalid-limits', `/limits/${pointerOf([key]).slice(1)}`, 'is not an allowed limit field.', `Remove the extra limits key ${JSON.stringify(key)}; use exactly "max_steps" and "max_model_calls", each an integer of at least 1.`);
609
+ }
610
+ for (const key of keys) {
611
+ const token = numberSources.get(limits)?.get(key);
612
+ const integer = typeof limits[key] === 'number' && (token === undefined ? Number.isInteger(limits[key]) && limits[key] >= 1
613
+ : /^-?(?:0|[1-9]\d*)$/.test(token) && BigInt(token) >= 1n);
614
+ if (!Object.hasOwn(limits, key) || !integer) {
615
+ add('invalid-limits', `/limits/${key}`, Object.hasOwn(limits, key) ? 'must be an integer JSON literal of at least 1.' : 'is missing; must be an integer JSON literal of at least 1.', `Fix limits.${key}: set an integer of at least 1 (for example 1), without a decimal point or exponent.`);
616
+ }
617
+ }
618
+ return out;
619
+ }
620
+
621
+ // Every schema problem of one interface: entry input and result schemas (any root) and resource operation schemas (object root).
622
+ export function interfaceKindProblems(iface) {
623
+ if (!isObject(iface)) return [{code:'invalid-interface',pointer:'',rule:'must be an object.'}];
624
+ const kind = Object.hasOwn(iface, 'kind') ? iface.kind : 'full';
625
+ if (!['full', 'partial', 'native-only'].includes(kind)) return [{code:'interface-kind-invalid',pointer:'/kind',rule:'must be full, partial or native-only.'}];
626
+ if (kind === 'native-only' && (typeof iface.reason !== 'string' || !iface.reason.trim())) return [{code:'native-reason-missing',pointer:'/reason',rule:'must name the native effect that bound ports cannot fake (RUNBOOK §21).'}];
627
+ return [];
628
+ }
629
+ // Local format advice (#3206): a draft that spells "kind": "full" still works, because
630
+ // upload copies omit kind (#3210). So it is a warning, never a refusal; the engine decides.
631
+ export function interfaceFormatWarnings(iface) {
632
+ return isObject(iface) && Object.hasOwn(iface, 'kind') && iface.kind === 'full' && iface.status === 'draft'
633
+ ? [{code:'interface-kind-explicit-full',pointer:'/kind',rule:'must omit /kind for a full interface.'}] : [];
634
+ }
635
+ export const formatWarningLines = prompt => interfaceFormatWarnings(prompt?.interface).map(item => `Warning: ${prompt.path} ${item.pointer} ${item.code}: ${item.rule}`);
636
+ // Lint and the files preview give unsupported schema keywords as advice too (#3206); a check keeps its schema rules.
637
+ export const schemaKeywordWarningLines = prompt => (isObject(prompt?.interface) ? interfaceSchemaProblems(prompt.interface) : [])
638
+ .filter(item => item.code === 'graph-schema-unsupported-keyword').map(item => `Warning: ${prompt.path} ${item.pointer} ${item.code}: ${item.rule}`);
639
+ const validCliImplementation = impl => isObject(impl) && Object.keys(impl).length === 2 && impl.kind === 'cli'
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);
647
+ const isCliEntry = (iface, index) => index >= 0 && Array.isArray(iface?.conventions)
648
+ && ['input_schema', 'result_schema'].every(key => iface.conventions.some(item => isObject(item) && item.path === `/entries/${index}/${key}` && item.convention === 'cli'));
649
+ export function interfaceSchemaProblems(iface) {
650
+ const kindProblems = interfaceKindProblems(iface);
651
+ if (kindProblems.length || iface?.kind === 'native-only') return kindProblems;
652
+ const out = limitProblems(iface);
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('; ')});
654
+ for (const [index, entry] of (Array.isArray(iface?.entries) ? iface.entries : []).entries()) {
655
+ for (const key of ['input_schema', 'result_schema']) if (isObject(entry) && Object.hasOwn(entry, key)) schemaRules(entry[key], `/entries/${index}/${key}`, out);
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.' });
658
+ }
659
+ }
660
+ for (const [index, resource] of (Array.isArray(iface?.resources) ? iface.resources : []).entries()) {
661
+ for (const [opIndex, operation] of (Array.isArray(resource?.operations) ? resource.operations : []).entries()) {
662
+ for (const key of ['arguments_schema', 'result_schema']) {
663
+ if (!isObject(operation) || !Object.hasOwn(operation, key)) continue;
664
+ const pointer = `/resources/${index}/operations/${opIndex}/${key}`;
665
+ schemaRules(operation[key], pointer, out);
666
+ if (isObject(operation[key]) && !Array.isArray(operation[key].type) && operation[key].type !== 'object' && !Object.hasOwn(operation[key], 'oneOf')) {
667
+ out.push({ code: 'graph-schema-invalid', pointer, rule: 'must be an object schema ("type": "object").' });
668
+ }
669
+ }
670
+ }
671
+ }
672
+ return out;
673
+ }
674
+
675
+ function unquoteFrontmatterScalar(raw) {
676
+ const value = raw.trim();
677
+ if (!value) return '';
678
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
679
+ if (value.startsWith('"')) {
680
+ try { return JSON.parse(value); } catch { return value.slice(1, -1); }
681
+ }
682
+ return value.slice(1, -1).replaceAll("''", "'");
683
+ }
684
+ return value;
685
+ }
686
+
687
+ export function parsePromptFrontmatter(text) {
688
+ const str = String(text ?? '');
689
+ if (!/^(?:\uFEFF)?---[ \t]*\r?\n/.test(str)) {
690
+ return { hasFrontmatter: false, kind: null, reason: null, error: null };
691
+ }
692
+ const match = /^(?:\uFEFF)?---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(str);
693
+ if (!match) {
694
+ return { hasFrontmatter: true, kind: null, reason: null, error: 'interface-kind-invalid' };
695
+ }
696
+ const fields = {};
697
+ for (const rawLine of match[1].split(/\r?\n/)) {
698
+ const trimmed = rawLine.trim();
699
+ if (!trimmed || trimmed.startsWith('#')) continue;
700
+ const kv = /^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(rawLine);
701
+ if (!kv || !['kind', 'reason'].includes(kv[1]) || Object.hasOwn(fields, kv[1])) {
702
+ return { hasFrontmatter: true, kind: fields.kind ?? null, reason: fields.reason ?? null, error: 'interface-kind-invalid' };
703
+ }
704
+ fields[kv[1]] = unquoteFrontmatterScalar(kv[2]);
705
+ }
706
+ const kind = fields.kind ?? null;
707
+ const reason = Object.hasOwn(fields, 'reason') ? fields.reason : null;
708
+ if (kind !== 'native-only') {
709
+ return { hasFrontmatter: true, kind, reason, error: 'interface-kind-invalid' };
710
+ }
711
+ if (typeof reason !== 'string' || !reason.trim()) {
712
+ return { hasFrontmatter: true, kind, reason, error: 'native-reason-missing' };
713
+ }
714
+ return { hasFrontmatter: true, kind, reason: reason.trim(), error: null };
715
+ }
716
+
717
+ // The prompt file of an entry: {path, text, blocks, interface, error}.
718
+ export function readPrompt(root, visible, path,workspace=loadRuntimeWorkspace({root})) {
719
+ workspace=boundedWorkspace(root,workspace);
720
+ if(typeof path==='string')requireRuntimePath(workspace,{path,from:'Prompt'});
721
+ if (typeof path !== 'string' || !path.endsWith('.prompt.md') || !visible.has(path)) return { path, error: 'entry-missing' };
722
+ const rawText = sourceFilePort(root,visible,workspace).read({path}).content, prepared = preparedText(root,visible,path,rawText,'prompt',workspace), text = prepared.text, blocks = interfaceBlocks(text);
723
+ const frontmatter = parsePromptFrontmatter(text);
724
+ const source = { path, rawText, text, blocks, references: prepared.references };
725
+ if (frontmatter.hasFrontmatter) {
726
+ if (blocks.length > 0) return { ...source, error: 'pdd-two-interfaces' };
727
+ if (frontmatter.error) {
728
+ return { ...source, frontmatter: true, frontmatterError: frontmatter.error, interface: { ...(frontmatter.kind !== null ? { kind: frontmatter.kind } : {}), ...(frontmatter.reason !== null ? { reason: frontmatter.reason } : {}) }, prose: proseSha256(text) };
729
+ }
730
+ return { ...source, frontmatter: true, hasInterface: false, nativeOnly: { path, reason: frontmatter.reason }, interface: { kind: 'native-only', reason: frontmatter.reason }, prose: proseSha256(text) };
731
+ }
732
+ if (!blocks.length) return { ...source, error: 'interface-missing' };
733
+ if (blocks.length > 1) return { ...source, error: 'pdd-two-interfaces' };
734
+ let value;
735
+ try {
736
+ value = JSON.parse(blocks[0][1], function(key, value, context) {
737
+ if (typeof value === 'number' && context?.source !== undefined) {
738
+ if (!numberSources.has(this)) numberSources.set(this, new Map());
739
+ numberSources.get(this).set(key, context.source);
740
+ }
741
+ return value;
742
+ });
743
+ } catch (error) { return { ...source, error: 'invalid-json', detail: error.message }; }
744
+ if (!isObject(value)) return { ...source, error: 'invalid-json', detail: 'The interface is not a JSON object.' };
745
+ return { ...source, interface: value, prose: proseSha256(text) };
746
+ }
747
+
748
+ // Drafts may run; until the server takes them, its refusal gets this plain text.
749
+ export const DRAFT_SERVER_TEXT = 'The server does not run draft prompts yet. Approve the prompt first, or wait for the server update.';
750
+ const draftStaleHint = path => `pdd: ${path} is a draft whose prose_sha256 is not current.`;
751
+ export const STALE_HINT = 'the text changed after approval: update the prompt and ask the person to approve it again';
752
+ export const staleHint = `pdd: ${STALE_HINT}.`;
753
+ const PROMPT_MESSAGES = {
754
+ 'entry-missing': path => `${path} is not a Git-visible *.prompt.md file.`,
755
+ 'interface-missing': path => `${path} has no Runtime interface block, and the PDD interpreter does not advertise lazy-interfaces.`,
756
+ 'pdd-two-interfaces': path => `${path} has more than one Runtime interface declaration. Keep one.`,
757
+ 'invalid-json': path => `The Runtime interface of ${path} is not valid JSON.`,
758
+ };
759
+
760
+ // Rule P7 for one prompt. Returns null or a refusal (without the step).
761
+ export function promptRefusal(prompt, section) {
762
+ if (prompt.error) return refusal(prompt.error, section, PROMPT_MESSAGES[prompt.error](prompt.path));
763
+ if (prompt.frontmatter) {
764
+ if (prompt.frontmatterError === 'native-reason-missing') {
765
+ return refusal('native-reason-missing', section, `${prompt.path} /reason must state in plain words why the effect cannot be faked.`);
766
+ }
767
+ if (prompt.frontmatterError) {
768
+ return refusal(prompt.frontmatterError, section, `${prompt.path} frontmatter must declare only kind: native-only and reason.`);
769
+ }
770
+ const kindProblems = interfaceKindProblems(prompt.interface);
771
+ return kindProblems.length ? refusal(kindProblems[0].code, section, `${prompt.path} ${kindProblems[0].rule}`) : null;
772
+ }
773
+ const kindProblems = interfaceKindProblems(prompt.interface);
774
+ if (kindProblems.length) return refusal(kindProblems[0].code, section, `${prompt.path} ${kindProblems[0].rule}`);
775
+ const status = prompt.interface.status;
776
+ if (status !== 'approved' && status !== 'draft') {
777
+ return refusal('interface-unapproved', section, `${prompt.path} has status ${show(status)}. Use "draft" or "approved".`);
778
+ }
779
+ if (prompt.interface.prose_sha256 !== prompt.prose) {
780
+ return status === 'draft' ? refusal('interface-stale', section, `${prompt.path} has a prose_sha256 that is not current.`, { hint: draftStaleHint(prompt.path) })
781
+ : refusal('interface-stale', section, `${prompt.path} changed after its interface was approved.`, { hint: staleHint });
782
+ }
783
+ return null;
784
+ }
785
+
786
+ function discoveryPromptPaths(root) {
787
+ return [...discoveryVisibleFiles({ root, excludeFixtureProjects: true })].filter(path => path.endsWith('.prompt.md')).sort();
788
+ }
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
+
906
+ export function interfaceFindings({ root, paths = discoveryPromptPaths(root) }) {
907
+ const visible = new Set(gitFiles(root));
908
+ const appMapScreens = readAppMapScreens(root, visible);
909
+ return paths.flatMap(path => {
910
+ try {
911
+ const prompt = readPrompt(root, visible, path), problem = promptRefusal(prompt, 'interface');
912
+ if (!prompt.interface) return [{ ...problem, path }];
913
+ const schema = interfaceSchemaProblems(prompt.interface).map(item => ({ code: item.code, path, section: item.pointer, message: `${path} ${item.pointer} ${item.rule}` }));
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;
922
+ } catch (error) {
923
+ return [{ code: error.code ?? 'interface-unreadable', path, message: error.message }];
924
+ }
925
+ });
926
+ }
927
+
928
+ export function runtimeCoverage({ root, paths = discoveryPromptPaths(root), allowMissingInterfaces = true }) {
929
+ const visible = new Set(gitFiles(root));
930
+ let checkable = 0, native_only = 0;
931
+ for (const path of paths) {
932
+ try {
933
+ const prompt = readPrompt(root, visible, path);
934
+ if (prompt.error === 'interface-missing') continue;
935
+ if (promptRefusal(prompt, 'interface') || interfaceSchemaProblems(prompt.interface).length) continue;
936
+ if (prompt.interface.kind === 'native-only') native_only++;
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++;
938
+ } catch { /* Missing and invalid source remains in the denominator. */ }
939
+ }
940
+ return { checkable, total: paths.length, native_only };
941
+ }
942
+
943
+ function numbersIn(text) {
944
+ const numbers = [];
945
+ for (const match of text.matchAll(/\d+(?:,\d{3})*(?:\.\d+)?/g)) {
946
+ const before = text.slice(0, match.index);
947
+ const negative = before.endsWith('-') && !/[\w.]-$/.test(before);
948
+ numbers.push({ index: match.index, end: match.index + match[0].length, text: `${negative ? '-' : ''}${match[0]}`, value: Number(match[0].replace(/,/g, '')) * (negative ? -1 : 1) });
949
+ }
950
+ return numbers;
951
+ }
952
+
953
+ const REVIEW_FILE = 'pdd-numeric-reviews.json';
954
+ const REVIEW_KEYS = ['test_path','test_sha256','step_id','criterion_id','target','path','value','reason'];
955
+ function validNumericReview(row) {
956
+ return isObject(row) && Object.keys(row).length === REVIEW_KEYS.length && REVIEW_KEYS.every(key => Object.hasOwn(row,key))
957
+ && ['test_path','step_id','criterion_id','target','path','test_sha256','reason'].every(key => typeof row[key] === 'string')
958
+ && row.test_path.endsWith('.json') && !row.test_path.startsWith('/') && posix.normalize(row.test_path) === row.test_path
959
+ && !row.test_path.split('/').includes('..') && /^[a-f0-9]{64}$/i.test(row.test_sha256)
960
+ && !!row.step_id.trim() && !!row.criterion_id.trim() && ['result','error'].includes(row.target)
961
+ && (row.path === '' || row.path.startsWith('/')) && Number.isFinite(row.value)
962
+ && !!row.reason.trim() && row.reason.length <= 1000 && !/[\r\n]/.test(row.reason);
963
+ }
964
+ function numericReviews(root, found, warnings) {
965
+ const path = join(root, REVIEW_FILE), stat = statOf(path);
966
+ if (!stat) return [];
967
+ const ignore = () => { warnings.push(`Warning: ${REVIEW_FILE} is invalid, unreadable or not a Git-visible regular file; its numeric reviews are ignored.`); return []; };
968
+ if (!found.visible.has(REVIEW_FILE) || !stat.isFile() || stat.isSymbolicLink() || stat.size > 16n * 1024n) return ignore();
969
+ let fd;
970
+ try {
971
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
972
+ const actual = fstatSync(fd);
973
+ if (!actual.isFile() || actual.size > 16 * 1024) return ignore();
974
+ const source = readFileSync(fd,'utf8');
975
+ if (Buffer.byteLength(source) > 16 * 1024) return ignore();
976
+ const data = JSON.parse(source);
977
+ if (!isObject(data) || Object.keys(data).length !== 2 || data.schema_version !== 'pdd.numeric-reviews.v1'
978
+ || !Array.isArray(data.reviews) || data.reviews.length > 100 || !data.reviews.every(validNumericReview)) return ignore();
979
+ return data.reviews;
980
+ } catch { return ignore(); } finally { if (fd !== undefined) closeSync(fd); }
981
+ }
982
+ const quantityWords = text => String(text ?? '').replace(/([a-z])([A-Z])/g,'$1 $2').toLowerCase().split(/[^a-z]+/).filter(Boolean);
983
+ const aggregateWords = new Set(['total','combined','cumulative','aggregate','sum','cap','limit','budget']);
984
+
985
+ const namedQuantity = text => {
986
+ const words = quantityWords(text);
987
+ const names = new Set(words.map(word => /^(scores?|points?)$/.test(word) ? 'score'
988
+ : /^(moves?|turns?)$/.test(word) ? 'moves' : /^seeds?$/.test(word) ? 'seed' : null).filter(Boolean));
989
+ return names.size === 1 ? [...names][0] : null;
990
+ };
991
+ function numberQuantity(text, number) {
992
+ // Prefer an immediately following unit ("30 moves"), then a preceding
993
+ // subject ("score is 30"). Do not cross clauses or another number.
994
+ const after = /^\s*([a-z]+)/i.exec(text.slice(number.end));
995
+ const following = after && namedQuantity(after[1]);
996
+ if (following) return following;
997
+ const before = /([a-z]+)(?:\s+(?:is|of|equals|at|the|fixed))*\s*$/i.exec(text.slice(0, number.index));
998
+ return before ? namedQuantity(before[1]) : null;
999
+ }
1000
+
1001
+ // A number can be a component of the criterion's quantity, rather than a typo.
1002
+ export function numberWarnings(doc, { testPath, testSha, reviews = [] } = {}) {
1003
+ const texts = new Map((Array.isArray(doc?.criteria) ? doc.criteria : []).filter(isObject).map(item => [item.id, item.text]));
1004
+ const steps = Array.isArray(doc?.steps) ? doc.steps : [], allChecks = steps.flatMap(step => Array.isArray(step?.checks) ? step.checks : []);
1005
+ const warnings = new Set();
1006
+ for (const [stepIndex,step] of steps.entries()) for (const [checkIndex,check] of (Array.isArray(step?.checks) ? step.checks : []).entries()) {
1007
+ const text = texts.get(check?.criterion_id);
1008
+ if (!isObject(check) || typeof text !== 'string' || !['result','error'].includes(check.target)) continue;
1009
+ const values = check.op === 'one_of' && Array.isArray(check.value) ? check.value : check.op === 'equals' ? [check.value] : [];
1010
+ const allNumbers = numbersIn(text), quantity = namedQuantity(check.path);
1011
+ const associated = allNumbers.map(item => ({ ...item, quantity: numberQuantity(text, item) }));
1012
+ const matching = associated.filter(item => quantity && item.quantity === quantity);
1013
+ const found = quantity && matching.length ? matching
1014
+ : quantity && associated.length && associated.every(item => item.quantity) ? [] : associated;
1015
+ const leaf = quantityWords(String(check.path ?? '').split('/').at(-1));
1016
+ const sameQuantity = leaf.some(word => aggregateWords.has(word)) && quantityWords(text).some(word => aggregateWords.has(word));
1017
+ const members = /\bacross\b([\s\S]*)/i.exec(text)?.[1] ?? '';
1018
+ const namedComponent = !sameQuantity && /\b(?:combined|cumulative|total|aggregate|sum|across)\b/i.test(text)
1019
+ && quantityWords(check.path).some(word => word.length > 2 && quantityWords(members).includes(word));
1020
+ for (const value of values) {
1021
+ if (typeof value !== 'number' || !found.length || found.some(item => item.value === value)) continue;
1022
+ const closest = found.reduce((best,item) => Math.abs(item.value-value) < Math.abs(best.value-value) ? item : best);
1023
+ if (Math.abs(closest.value-value) > 0.1 * Math.max(Math.abs(closest.value),Math.abs(value))) continue;
1024
+ const companion = allChecks.some(peer => isObject(peer) && peer !== check && peer.criterion_id === check.criterion_id
1025
+ && peer.target === check.target && peer.path !== check.path && peer.op === 'equals' && peer.value === closest.value);
1026
+ if (namedComponent || (!sameQuantity && !matching.length && companion)) continue;
1027
+ if (reviews.some(row => validNumericReview(row) && row.test_path === testPath && row.test_sha256.toLowerCase() === testSha
1028
+ && row.step_id === step.step_id && row.criterion_id === check.criterion_id && row.target === check.target && row.path === check.path && row.value === value)) continue;
1029
+ const location = `${testPath ?? 'test'} steps[${stepIndex}].checks[${checkIndex}] (${check.target} ${check.path})`;
1030
+ warnings.add(`Warning: possible numeric mismatch at ${location}: expected ${value}; ${doc.story_path ?? 'criterion text'} ${check.criterion_id} contains ${closest.text}. These may be different quantities. Confirm against the Story and prompt; retain a correct expected value. Record a scoped rationale in ${REVIEW_FILE} if needed (RUNBOOK §4).`);
1031
+ }
1032
+ }
1033
+ return [...warnings];
1034
+ }
1035
+
1036
+ const stepCount = doc => Array.isArray(doc?.steps) ? doc.steps.length : 0;
1037
+ // Leave room for the whole call graph; the budget is a ceiling, not a charge.
1038
+ export const defaultMaxCalls = doc => Math.min(1000, Math.max(18, stepCount(doc) * 12));
1039
+
1040
+ function firstDifference(testTexts, storyTexts) {
1041
+ const left = [...storyTexts];
1042
+ for (const text of testTexts) {
1043
+ const index = left.indexOf(text);
1044
+ if (index < 0) return `The test has this criterion, but the story does not: "${text}"`;
1045
+ left.splice(index, 1);
1046
+ }
1047
+ return `The story has this criterion, but the test does not: "${left[0]}"`;
1048
+ }
1049
+
1050
+ // Coverage is structural. A negative assertion with an exact calls/world check is checkable.
1051
+ const exactCheck = check => EXACT_OPS.has(check?.op) || (isObject(check) && Object.hasOwn(check, 'html') && check.op === 'exists');
1052
+ const ordinaryInexactCheck = check => isObject(check) && ['exists','contains'].includes(check.op)
1053
+ && ['result','world','calls','error'].includes(check.target) && typeof check.path === 'string'
1054
+ && (check.path === '' || check.path.startsWith('/')) && !/~(?![01])/.test(check.path)
1055
+ && (check.op !== 'contains' || Object.hasOwn(check,'value'));
1056
+ function criterionPlan(doc, story) {
1057
+ if (!Array.isArray(doc?.criteria) || !doc.criteria.length || !Array.isArray(doc.steps)
1058
+ || Object.hasOwn(doc, 'criteria_scope')
1059
+ || (Object.hasOwn(doc,'check_exemptions') && !(Array.isArray(doc.check_exemptions) && !doc.check_exemptions.length))
1060
+ || doc.criteria.some(item => !isObject(item) || !isDeepStrictEqual(Object.keys(item).sort(),['id','text']) || typeof item.id !== 'string' || !item.id || typeof item.text !== 'string')
1061
+ || new Set(doc.criteria.map(item => item.id)).size !== doc.criteria.length) return null;
1062
+ const remaining = [...story], criteria = doc.criteria.map(item => ({...item}));
1063
+ for (const item of criteria) {
1064
+ const index = remaining.indexOf(item.text);
1065
+ if (index < 0) return null;
1066
+ remaining.splice(index, 1);
1067
+ }
1068
+ const assigned = new Set(), exact = new Set();
1069
+ const declared = new Set(doc.criteria.map(item=>item.id));
1070
+ for (const step of doc.steps) for (const check of Array.isArray(step?.checks) ? step.checks : []) {
1071
+ if (!isObject(check) || !declared.has(check.criterion_id)) return null;
1072
+ assigned.add(check?.criterion_id);
1073
+ if (exactCheck(check)) exact.add(check.criterion_id);
1074
+ }
1075
+ for (const step of doc.steps) for (const check of Array.isArray(step?.checks) ? step.checks : []) {
1076
+ if (!exact.has(check.criterion_id) && !ordinaryInexactCheck(check)) return null;
1077
+ }
1078
+ const not_checked = criteria.filter(item => !exact.has(item.id)).map(item => ({criterion_id:item.id,text:item.text,
1079
+ reason:assigned.has(item.id) ? 'no exact check is assigned' : 'no check is assigned'}));
1080
+ const unmatched = [...doc.criteria.map(item => item.text)], used = new Set(criteria.map(item => item.id));
1081
+ for (const [index, text] of story.entries()) {
1082
+ const at = unmatched.indexOf(text);
1083
+ if (at >= 0) { unmatched.splice(at, 1); continue; }
1084
+ const base = `ac-${index + 1}`; let id = base;
1085
+ for (let n = 2; used.has(id); n++) id = `${base}-${n}`;
1086
+ used.add(id); criteria.push({id,text});
1087
+ not_checked.push({criterion_id:id,text,reason:'the test has no criterion for this Story item'});
1088
+ }
1089
+ return {criteria,not_checked,checked:criteria.length-not_checked.length};
1090
+ }
1091
+
1092
+ // This applies to authored/effective input before capture adds automatic exemptions.
1093
+ function partialTestRefusal(doc) {
1094
+ if (Object.hasOwn(doc, 'criteria_scope') || (Object.hasOwn(doc, 'check_exemptions') && !(Array.isArray(doc.check_exemptions) && !doc.check_exemptions.length))) {
1095
+ return refusal('pdd-partial-test', Object.hasOwn(doc, 'criteria_scope') ? 'criteria_scope' : 'check_exemptions', 'In the beta a test checks the whole story. Remove criteria_scope and check_exemptions.');
1096
+ }
1097
+ return null;
1098
+ }
1099
+
1100
+ function capturedCriterionPlan(doc, story, path) {
1101
+ let broken = partialTestRefusal(doc);
1102
+ const plan = broken ? null : criterionPlan(doc, story);
1103
+ if (!broken && !story.length) broken = refusal('story-criteria-missing', 'story_path', `${doc.story_path} has no numbered "## Acceptance criteria" list.`);
1104
+ if (!broken && !plan) {
1105
+ const testTexts = doc.criteria.map(item => item.text).sort(), storyTexts = [...story].sort();
1106
+ broken = !isDeepStrictEqual(testTexts, storyTexts)
1107
+ ? refusal('story-criterion-mismatch', 'criteria', firstDifference(testTexts, storyTexts))
1108
+ : refusal('criterion-needs-exact-check', 'criteria', 'The checks do not establish valid criterion coverage.');
1109
+ }
1110
+ if (!broken && !plan.checked) broken = refusal('unchecked-criteria', 'criteria', 'No criterion has an exact check.',
1111
+ {hint:'Add an exact result, world or call-count check for an observable criterion.'});
1112
+ if (broken) throw Object.assign(new PreflightError(4, `${path}: ${broken.message}`), broken,
1113
+ {message:`${path}: ${broken.message}`,hint:broken.hint ?? 'Fix the test criterion text or partial-test metadata, then run the selection again.'},
1114
+ plan ? {not_checked:plan.not_checked,criteria_total:plan.criteria.length} : {});
1115
+ return plan;
1116
+ }
1117
+
1118
+ export function promptMarkdownTargets(text, fromPath, visible) {
1119
+ if (typeof text !== 'string') return [];
1120
+ return markdownContext(text).flatMap(raw => {
1121
+ try { const target = contextPath(raw, fromPath, visible); return target?.endsWith('.prompt.md') ? [target] : []; }
1122
+ catch { return []; }
1123
+ });
1124
+ }
1125
+
1126
+ // The schema rules of a prompt and of the prompts it calls, all at once (cached per prompt).
1127
+ export function promptSchemaRefusals(root, found, prompt, prompts, seen = new Set(), { allowMissingInterfaces = false } = {}) {
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);
1153
+ }
1154
+
1155
+ // A refusal that discovery alone proves: a conflict, an unreadable or invalid file, a file over the upload limit,
1156
+ // or a story_path that names another Story than the test name rule matched.
1157
+ export function discoveryRefusal(test) {
1158
+ if (test.error) return refusal('invalid-document', 'scenario', test.error,
1159
+ {hint:'Fix the named test file, make it readable, or keep one file for the Story.'});
1160
+ if (test.storyPath && isObject(test.doc) && typeof test.doc.story_path === 'string' && test.doc.story_path !== test.storyPath) {
1161
+ return refusal('pdd-story-mismatch', 'story_path', `${test.path} is the test of ${test.storyPath} by its name, but its story_path names ${test.doc.story_path}. Make them agree.`);
1162
+ }
1163
+ return null;
1164
+ }
1165
+
1166
+ const criterionShape = item => isObject(item) && isDeepStrictEqual(Object.keys(item).sort(), ['id','text'])
1167
+ && typeof item.id === 'string' && !!item.id && typeof item.text === 'string' && !!item.text;
1168
+ function idOnlyCriterion(item) {
1169
+ if (typeof item === 'string' && item && item.trim() === item) return item;
1170
+ if (isObject(item) && Object.keys(item).length === 1 && typeof item.id === 'string' && item.id && item.id.trim() === item.id) return item.id;
1171
+ return null;
1172
+ }
1173
+ const needsCriteriaResolution = doc => !Object.hasOwn(doc, 'criteria')
1174
+ || (Array.isArray(doc.criteria) && doc.criteria.some(item => !criterionShape(item)));
1175
+ function resolveScenarioCriteria(doc, storySource) {
1176
+ if (!isObject(doc) || typeof doc.story_path !== 'string' || !doc.story_path) return { doc, changed: false, refusal: null };
1177
+ if (!Object.hasOwn(doc, 'criteria')) {
1178
+ const numbered = numberedStoryCriteria(storySource, { requireHeading: true });
1179
+ if (!numbered.length) return { doc, changed: false, refusal: refusal('story-criteria-missing', 'story_path', `${doc.story_path} has no numbered "## Acceptance criteria" list.`) };
1180
+ return { doc: { ...doc, criteria: numbered.map((text, index) => ({ id: `AC${index + 1}`, text })) }, changed: true, refusal: null };
1181
+ }
1182
+ if (!Array.isArray(doc.criteria) || !doc.criteria.length) {
1183
+ return { doc, changed: false, refusal: refusal('invalid-criterion', 'criteria', 'The test has no criteria.') };
1184
+ }
1185
+ const hasIdOnly = doc.criteria.some(item => idOnlyCriterion(item) !== null);
1186
+ const ids = new Set(), positions = new Set(), criteria = [];
1187
+ let numbered = null, changed = false;
1188
+ for (const [index, item] of doc.criteria.entries()) {
1189
+ if (criterionShape(item)) {
1190
+ const match = hasIdOnly ? AC_ID.exec(item.id) : null, position = match ? Number(match[1]) : 0;
1191
+ if (ids.has(item.id) || (position && positions.has(position))) {
1192
+ return { doc, changed: false, refusal: refusal('duplicate-criterion', `criteria[${index}]`, `The criterion ID ${item.id} is used twice.`) };
1193
+ }
1194
+ ids.add(item.id);
1195
+ if (position) positions.add(position);
1196
+ criteria.push(item);
1197
+ continue;
1198
+ }
1199
+ const id = idOnlyCriterion(item);
1200
+ if (!id) return { doc, changed: false, refusal: refusal('invalid-criterion', `criteria[${index}]`, 'Each criterion has only a nonempty "id" and "text", or a numbered ID ("AC1" or {"id": "AC1"}).') };
1201
+ if (ids.has(id)) return { doc, changed: false, refusal: refusal('duplicate-criterion', `criteria[${index}]`, `The criterion ID ${id} is used twice.`) };
1202
+ ids.add(id);
1203
+ numbered ??= numberedStoryCriteria(storySource, { requireHeading: true });
1204
+ if (!numbered.length) return { doc, changed: false, refusal: refusal('story-criteria-missing', 'story_path', `${doc.story_path} has no numbered "## Acceptance criteria" list.`) };
1205
+ const match = AC_ID.exec(id), position = match ? Number(match[1]) : 0;
1206
+ if (!position || position > numbered.length) {
1207
+ return { doc, changed: false, refusal: refusal('invalid-criterion', `criteria[${index}]`,
1208
+ `Criterion ID ${show(id)} does not match numbered item 1..${numbered.length} in ${doc.story_path}.`) };
1209
+ }
1210
+ if (positions.has(position)) {
1211
+ return { doc, changed: false, refusal: refusal('duplicate-criterion', `criteria[${index}]`, `The criterion ID ${id} is used twice.`) };
1212
+ }
1213
+ positions.add(position);
1214
+ criteria.push({ id, text: numbered[position - 1] });
1215
+ changed = true;
1216
+ }
1217
+ return { doc: changed ? { ...doc, criteria } : doc, changed, refusal: null };
1218
+ }
1219
+ const STEP_SHAPE_NOTE = `Required step keys: ${REQUIRED_STEP_KEYS.join(', ')}; optional step keys: ${OPTIONAL_STEP_KEYS.join(', ')}.`;
1220
+ function stepProblem(step) {
1221
+ if (!isObject(step)) return `A step must be a JSON object. ${STEP_SHAPE_NOTE}`;
1222
+ const missing = REQUIRED_STEP_KEYS.filter(key => !Object.hasOwn(step, key));
1223
+ const extra = Object.keys(step).filter(key => !STEP_KEYS.has(key));
1224
+ if (missing.length || extra.length) {
1225
+ const parts = [];
1226
+ if (missing.length) parts.push(`missing required key${missing.length > 1 ? 's' : ''} ${missing.map(key => `"${key}"`).join(', ')}`);
1227
+ if (extra.length) parts.push(`unknown key${extra.length > 1 ? 's' : ''} ${extra.map(key => `"${key}"`).join(', ')}`);
1228
+ return `Invalid step (${parts.join('; ')}). ${STEP_SHAPE_NOTE}`;
1229
+ }
1230
+ const badStrings = ['step_id', 'entry_path', 'operation'].filter(key => typeof step[key] !== 'string' || !step[key]);
1231
+ if (badStrings.length) return `Step ${badStrings.map(key => `"${key}"`).join(', ')} must be ${badStrings.length > 1 ? 'nonblank strings' : 'a nonblank string'}.`;
1232
+ return null;
1233
+ }
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
+ }
1558
+ function appMapsRefusal(doc) {
1559
+ if (!Object.hasOwn(doc,'app_maps')) return null;
1560
+ if (!Array.isArray(doc.app_maps)) return refusal('invalid-app-maps','app_maps','app_maps must be a list of repository-relative paths.');
1561
+ const seen=new Set();
1562
+ for (const [index,path] of doc.app_maps.entries()) {
1563
+ const section='app_maps['+index+']';
1564
+ if (typeof path!=='string' || !path || /[\\\p{Cc}]/u.test(path) || /^[A-Za-z]:/.test(path)
1565
+ || path.split('/').some(part=>!part || part==='.' || part==='..')) {
1566
+ return refusal('invalid-app-maps',section,'Each app map must be a safe repository-relative path.');
1567
+ }
1568
+ if (seen.has(path)) return refusal('invalid-app-maps',section,path+' is listed twice.');
1569
+ seen.add(path);
1570
+ }
1571
+ return null;
1572
+ }
1573
+ function documentRefusal(doc, path, { allowOmittedCriteria = false } = {}) {
1574
+ if (!isObject(doc)) return refusal('invalid-document', 'scenario', `${path} is not a JSON object.`);
1575
+ const required = allowOmittedCriteria && typeof doc.story_path === 'string' && doc.story_path
1576
+ ? REQUIRED_KEYS.filter(key => key !== 'criteria') : REQUIRED_KEYS;
1577
+ const missing = required.filter(key => !Object.hasOwn(doc, key)), extra = Object.keys(doc).filter(key => !TOP_KEYS.has(key));
1578
+ if (missing.length) return refusal('invalid-document', 'scenario', `The test has no ${missing.map(key => `"${key}"`).join(', ')}.`);
1579
+ if (extra.length) return refusal('invalid-document', 'scenario', `The test has keys the interpreter does not know: ${extra.map(key => `"${key}"`).join(', ')}.`);
1580
+ if (doc.schema_version !== TEST_SCHEMA) return refusal('invalid-document', 'schema_version', `schema_version must be "${TEST_SCHEMA}".`);
1581
+ return appMapsRefusal(doc);
1582
+ }
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
+
1594
+ export function scenarioShapeRefusal(doc,path) {
1595
+ const broken=documentRefusal(doc,path);if(broken)return broken;
1596
+ if (!Array.isArray(doc.criteria)||!doc.criteria.length) return refusal('invalid-criterion','criteria','The test has no criteria.');
1597
+ const ids=new Set();
1598
+ for (const [index,item] of doc.criteria.entries()) {
1599
+ if(!criterionShape(item))return refusal('invalid-criterion',`criteria[${index}]`,'Each criterion has only a nonempty "id" and "text".');
1600
+ if(ids.has(item.id))return refusal('duplicate-criterion',`criteria[${index}]`,`The criterion ID ${item.id} is used twice.`);
1601
+ ids.add(item.id);
1602
+ }
1603
+ if(!Array.isArray(doc.steps)||!doc.steps.length)return refusal('missing-steps','steps','The test has no steps.');
1604
+ for(const [index,step] of doc.steps.entries()) {
1605
+ const section=`steps[${index}]`;
1606
+ const brokenStep=stepProblem(step);
1607
+ if(brokenStep)return refusal('invalid-step',section,brokenStep);
1608
+ if(Object.hasOwn(step,'model')&&(typeof step.model!=='string'||!step.model.trim()))return refusal('invalid-step-model',`${section}.model`,'A step model must be a model name (a string).');
1609
+ if(!Array.isArray(step.checks))return refusal('invalid-check',`${section}.checks`,'checks must be a list.');
1610
+ for(const [at,check] of step.checks.entries()) {
1611
+ if(!checkShape(check))return refusal('invalid-check',`${section}.checks[${at}]`,'A check has criterion_id, target, path and op.');
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.`);
1613
+ }
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
+ }
1792
+ return null;
1793
+ }
1794
+
1795
+ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false, executablePaths = new Set(prompts.keys()), localLint = false, stepIds = [] } = {}) {
1796
+ let doc = test.doc;
1797
+ if (!test.error && isObject(doc)) {
1798
+ const prepared = preparedText(root,found.visible,test.path,readText(root,test.path),'scenario');
1799
+ try { doc = parseScenarioJson(prepared.text); } catch { /* Preserve ordinary malformed scenario handling. */ }
1800
+ }
1801
+ const done = (issue, story = null) => ({ refusal: issue, doc, story });
1802
+ if (test.error) return done(discoveryRefusal(test));
1803
+ const shape = documentRefusal(doc, test.path, { allowOmittedCriteria: true });
1804
+ if (shape) return done(shape);
1805
+ const derivation = scenarioDerivationRefusal(doc);
1806
+ if (derivation) return done(derivation);
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".'));
1808
+ if (!found.visible.has(doc.story_path)) return done(refusal('story-missing', 'story_path', `${doc.story_path} is not a Git-visible file.`));
1809
+ if (test.storyPath && doc.story_path !== test.storyPath) return done(discoveryRefusal({ ...test, doc }));
1810
+ const partial = partialTestRefusal(doc); if (partial) return done(partial);
1811
+ const storySource = sourceFilePort(root, found.visible, found.workspace).read({ path: doc.story_path }).content;
1812
+ const resolved = resolveScenarioCriteria(doc, storySource);
1813
+ if (resolved.refusal) return done(resolved.refusal);
1814
+ doc = resolved.doc;
1815
+ let story = storyCriteria(storySource);
1816
+ if (!story.length) return done(refusal('story-criteria-missing', 'story_path', `${doc.story_path} has no numbered "## Acceptance criteria" list.`), story);
1817
+ const testTexts = doc.criteria.map(item => item.text).sort(), storyTexts = [...story].sort();
1818
+ if (!isDeepStrictEqual(testTexts, storyTexts) && !criterionPlan(doc, story)) return done(refusal('story-criterion-mismatch', 'criteria', firstDifference(testTexts, storyTexts)), story);
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));
1829
+ const exact = new Set(), inputIssues = [];
1830
+ for (const [index, step] of doc.steps.entries()) {
1831
+ const section = `steps[${index}]`, at = { step: index + 1 };
1832
+ const brokenStep = stepProblem(step);
1833
+ if (brokenStep) {
1834
+ return done(refusal('invalid-step', section, brokenStep, at), story);
1835
+ }
1836
+ if (Object.hasOwn(step, 'model') && (typeof step.model !== 'string' || !step.model.trim())) {
1837
+ return done(refusal('invalid-step-model', `${section}.model`, 'A step model must be a model name (a string).', at), story);
1838
+ }
1839
+ if (!prompts.has(step.entry_path)) prompts.set(step.entry_path, readPrompt(root, found.visible, step.entry_path,found.workspace));
1840
+ const prompt = prompts.get(step.entry_path);
1841
+ const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
1842
+ const broken = lazyMissing ? null : promptRefusal(prompt, section);
1843
+ if (broken) return done({ ...broken, ...at }, story);
1844
+ const schemaIssues = promptSchemaRefusals(root, found, prompt, prompts, new Set(), { allowMissingInterfaces })
1845
+ .filter(problem => !localLint || !problem.code?.startsWith('graph-schema-'));
1846
+ if (schemaIssues.length) return done(schemaIssues, story);
1847
+ const entry = lazyMissing ? null : (Array.isArray(prompt.interface.entries) ? prompt.interface.entries : []).find(item => item?.operation === step.operation);
1848
+ const native = [...executablePaths].some(path => prompts.get(path)?.interface?.kind === 'native-only');
1849
+ if (!lazyMissing && !entry && !native) return done(refusal('entry-operation-missing', section, `${step.entry_path} has no operation "${step.operation}".`, at), story);
1850
+ const errorStep = Object.hasOwn(step, 'expected_error');
1851
+ if (!lazyMissing && !native && errorStep && !(Array.isArray(entry.errors) && entry.errors.includes(step.expected_error))) {
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);
1853
+ }
1854
+ if (!Array.isArray(step.checks)) return done(refusal('invalid-check', `${section}.checks`, 'checks must be a list.', at), story);
1855
+ let errorChecks = 0, resultWithErrorRefusal = null;
1856
+ for (const [checkIndex, check] of step.checks.entries()) {
1857
+ if (!checkShape(check)) {
1858
+ return done(refusal('invalid-check', `${section}.checks[${checkIndex}]`, 'A check has criterion_id, target, path and op.', at), story);
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
+ }
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);
1867
+ if (EXACT_OPS.has(check.op) || (Object.hasOwn(check, 'html') && check.op === 'exists')) exact.add(check.criterion_id);
1868
+ if (check.target === 'error' && check.path === '/code' && check.op === 'equals' && check.value === step.expected_error) errorChecks += 1;
1869
+ }
1870
+ if (errorStep && errorChecks === 0) {
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);
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
+ }
1878
+ if (!lazyMissing && !native) inputIssues.push(...checkInput(step.input, entry.input_schema, index).refusals);
1879
+ }
1880
+ if (inputIssues.length) return done(inputIssues, story);
1881
+ for (const step of doc.steps) for (const check of step.checks) {
1882
+ if (!exact.has(check.criterion_id) && !ordinaryInexactCheck(check)) return done(refusal('criterion-needs-exact-check', 'criteria',
1883
+ `The checks for ${check.criterion_id} do not establish valid criterion coverage.`, {hint:'Fix the check operation, target and JSON pointer before checking this test.'}), story);
1884
+ }
1885
+ if (!exact.size) return done(refusal('unchecked-criteria', 'criteria', 'No criterion has an exact check.',
1886
+ {hint:'Add an exact result, world or call-count check for an observable criterion.'}), story);
1887
+ return done(null, story);
1888
+ }
1889
+
1890
+ // Rules P1-P10 for the selected tests. Returns rows and warnings; never throws for a test problem.
1891
+ export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false, localLint = false, stepIds = [] }) {
1892
+ found={...found,workspace};for(const test of selected)requireRuntimePath(workspace,{path:test.path,from:'Selected test'});
1893
+ const warnings = [];
1894
+ const reviews = numericReviews(root, found, warnings);
1895
+ const rows = selected.map(test => {
1896
+ const prompts = new Map(), executablePaths = new Set(), visited = new Set();
1897
+ // Discover identity independently of validation: an early criterion error or
1898
+ // stale caller must not make a reachable native-only declaration executable.
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);
1909
+ };
1910
+ let refused, plan, testSha = null, effectiveDoc = test.doc;
1911
+ try {
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 });
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.');
1916
+ effectiveDoc = checked.doc;
1917
+ const nativeProblems = [...prompts.values()].filter(prompt => prompt.interface?.kind === 'native-only')
1918
+ .map(prompt => promptRefusal(prompt,'interface')).filter(Boolean);
1919
+ if (nativeProblems.length) refused = [...(refused ? [refused].flat() : []),...nativeProblems];
1920
+ if (!refused || refused.code === 'unchecked-criteria') {
1921
+ plan = criterionPlan(effectiveDoc, checked.story ?? storyCriteria(sourceFilePort(root, found.visible, workspace).read({ path: effectiveDoc.story_path }).content));
1922
+ }
1923
+ if (!refused && reviews.length) testSha = sha256(readFileSync(join(root,test.path)));
1924
+ } catch (error) {
1925
+ if (!(error instanceof PreflightError && error.exitCode === 4) && !['ENOENT','EACCES','EPERM','EISDIR'].includes(error.code)) throw error;
1926
+ refused = refusal(error.code ?? 'source-unavailable', 'source', error.message,
1927
+ {hint:'Restore the named dependency, make it readable, or correct its declared path.'});
1928
+ }
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)} : {}),
1931
+ max_calls: defaultMaxCalls(effectiveDoc), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
1932
+ criteria_total: plan?.criteria.length ?? (Array.isArray(effectiveDoc?.criteria) ? effectiveDoc.criteria.length : 0),
1933
+ ...(plan?.not_checked.length ? {not_checked:plan.not_checked} : {}), draft: false };
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}));
1935
+ row.draft = row.steps.some(step => prompts.get(step?.entry_path)?.interface?.status === 'draft');
1936
+ for (const [index, step] of row.steps.entries()) {
1937
+ const prompt = prompts.get(step?.entry_path), entries = Array.isArray(prompt?.interface?.entries) ? prompt.interface.entries : [];
1938
+ const entryIndex = entries.findIndex(item => item?.operation === step?.operation), entry = entryIndex >= 0 ? entries[entryIndex] : undefined;
1939
+ for (const text of entry ? checkInput(step.input, entry.input_schema, index).warnings : []) warnings.push(`Warning: ${test.path} ${text}`);
1940
+ if (entry && isCliEntry(prompt?.interface, entryIndex) && !entry.implementation) {
1941
+ const message = `Warning: ${step.entry_path} entry ${step.operation} has no implementation declaration.`;
1942
+ if (!warnings.includes(message)) warnings.push(message);
1943
+ }
1944
+ }
1945
+ // Number advice from the exact test values. It never blocks; the interpreter decides.
1946
+ // A native-only test is never sent to the interpreter, so it gets no number advice.
1947
+ let tokens = [], range = null, rawTestText = null;
1948
+ if (!test.error && !row.refusals.some(item => item.section === 'source')) {
1949
+ try { rawTestText = readText(root, test.path); } catch { rawTestText = null; }
1950
+ }
1951
+ if (!row.native_only.length && rawTestText !== null) {
1952
+ try { tokens = roundedNumberTokens(rawTestText); range = interpreterIntegerWarning(parseScenarioJson(rawTestText), test.path); } catch { tokens = []; }
1953
+ }
1954
+ if (range) warnings.push(range);
1955
+ if (!row.native_only.length) for (const prompt of prompts.values()) for (const line of schemaBoundWarnings(prompt)) if (!warnings.includes(line)) warnings.push(line);
1956
+ for (const prompt of prompts.values()) {
1957
+ for (const line of formatWarningLines(prompt)) if (!warnings.includes(line)) warnings.push(line);
1958
+ const proseWarning = promptProseWarningLine(prompt.path, prompt.rawText ?? prompt.text);
1959
+ if (proseWarning && !warnings.includes(proseWarning)) warnings.push(proseWarning);
1960
+ }
1961
+ const storyWarning = storyComplexityWarningLine({ path: test.path, storyPath: test.storyPath, doc: test.doc }, rawTestText);
1962
+ if (storyWarning && !warnings.includes(storyWarning)) warnings.push(storyWarning);
1963
+ for (const item of tokens) warnings.push(`Warning: ${test.path} ${interpreterSection(item.path)} is ${item.source}, which reads as the Number ${String(item.value)}. Write the value you mean: plain digits for an exact whole number, or the exact Number spelling.`);
1964
+ return row;
1965
+ });
1966
+ return { rows, warnings };
1967
+ }
1968
+
1969
+ export function missingCliImplementationWarnings({ root, found, selected, workspace = found.workspace ?? loadRuntimeWorkspace({ root }) }) {
1970
+ workspace = boundedWorkspace(root, workspace);
1971
+ const warnings = [], prompts = new Map();
1972
+ for (const test of Array.isArray(selected) ? selected : []) {
1973
+ if (test?.error) continue;
1974
+ for (const step of Array.isArray(test?.doc?.steps) ? test.doc.steps : []) {
1975
+ const path = step?.entry_path;
1976
+ if (typeof path !== 'string') continue;
1977
+ if (!prompts.has(path)) {
1978
+ try { prompts.set(path, readPrompt(root, found.visible, path, workspace)); } catch { prompts.set(path, null); }
1979
+ }
1980
+ const iface = prompts.get(path)?.interface, entries = Array.isArray(iface?.entries) ? iface.entries : [];
1981
+ const entryIndex = entries.findIndex(item => item?.operation === step?.operation), entry = entryIndex >= 0 ? entries[entryIndex] : undefined;
1982
+ if (entry && isCliEntry(iface, entryIndex) && !entry.implementation) {
1983
+ const message = `Warning: ${path} entry ${step.operation} has no implementation declaration.`;
1984
+ if (!warnings.includes(message)) warnings.push(message);
1985
+ }
1986
+ }
1987
+ }
1988
+ return warnings;
1989
+ }
1990
+
1991
+ // Keep PDD's declaration classification and local implementation bindings local.
1992
+ // Token offsets preserve all other JSON spellings; parsing and stringifying would round numbers.
1993
+ export function executableInterfaceText(text) {
1994
+ const blocks = interfaceBlocks(text);
1995
+ if (blocks.length !== 1) return text;
1996
+ const block = blocks[0], body = block[1];
1997
+ let value;
1998
+ try { value = parseScenarioJson(body); } catch { return text; }
1999
+ if (!isObject(value) || (Object.hasOwn(value, 'kind') && !['full', 'partial'].includes(value.kind))) return text;
2000
+ const hasLocalKind = Object.hasOwn(value, 'kind');
2001
+ const entries = Array.isArray(value.entries) ? value.entries : [];
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));
2004
+ if (!hasLocalKind && !hasImplementation) return text;
2005
+ const tokens = [...body.matchAll(/"(?:[^"\\]|\\[\s\S])*"|[{}\[\],:]|[^\s{}\[\],:"]+/g)];
2006
+ const skipValue = pos => {
2007
+ const first = tokens[pos];
2008
+ if (!first) return null;
2009
+ if (first[0] !== '{' && first[0] !== '[') return { end: first.index + first[0].length, next: pos + 1 };
2010
+ let depth = 0;
2011
+ for (let index = pos; index < tokens.length; index++) {
2012
+ const spelling = tokens[index][0];
2013
+ if (spelling === '{' || spelling === '[') depth++;
2014
+ else if (spelling === '}' || spelling === ']') {
2015
+ depth--;
2016
+ if (depth === 0) return { end: tokens[index].index + 1, next: index + 1 };
2017
+ }
2018
+ }
2019
+ return null;
2020
+ };
2021
+ const objectMembers = pos => {
2022
+ const members = [];
2023
+ let cur = pos + 1, commaBefore = null;
2024
+ while (cur < tokens.length && tokens[cur][0] !== '}') {
2025
+ const keyTok = tokens[cur], valPos = cur + 2;
2026
+ if (!keyTok?.[0].startsWith('"') || tokens[cur + 1]?.[0] !== ':') return null;
2027
+ const skipped = skipValue(valPos), after = skipped ? tokens[skipped.next] : null;
2028
+ if (!skipped || !after) return null;
2029
+ members.push({ key: JSON.parse(keyTok[0]), keyStart: keyTok.index, valPos, end: skipped.end, commaBefore, commaAfter: after[0] === ',' ? after.index : null });
2030
+ if (after[0] !== ',') break;
2031
+ commaBefore = after.index;
2032
+ cur = skipped.next + 1;
2033
+ }
2034
+ return members;
2035
+ };
2036
+ const arrayItems = pos => {
2037
+ const items = [];
2038
+ let cur = pos + 1;
2039
+ while (cur < tokens.length && tokens[cur][0] !== ']') {
2040
+ const skipped = skipValue(cur), after = skipped ? tokens[skipped.next] : null;
2041
+ if (!skipped || !after) return null;
2042
+ items.push(cur);
2043
+ if (after[0] !== ',') break;
2044
+ cur = skipped.next + 1;
2045
+ }
2046
+ return items;
2047
+ };
2048
+ const memberSpan = member => member.commaBefore !== null ? [member.commaBefore, member.end]
2049
+ : member.commaAfter !== null ? [member.keyStart, member.commaAfter + 1] : [member.keyStart, member.end];
2050
+ const rootMembers = tokens[0]?.[0] === '{' ? objectMembers(0) : null;
2051
+ if (!rootMembers) return text;
2052
+ const spans = [];
2053
+ if (hasLocalKind) {
2054
+ const kindMembers = rootMembers.filter(member => member.key === 'kind');
2055
+ if (kindMembers.length !== 1 || !tokens[kindMembers[0].valPos]?.[0].startsWith('"')) return text;
2056
+ spans.push(memberSpan(kindMembers[0]));
2057
+ }
2058
+ if (hasImplementation) {
2059
+ const entriesMembers = rootMembers.filter(member => member.key === 'entries');
2060
+ if (entriesMembers.length !== 1 || tokens[entriesMembers[0].valPos]?.[0] !== '[') return text;
2061
+ const itemPositions = arrayItems(entriesMembers[0].valPos);
2062
+ if (!itemPositions) return text;
2063
+ for (const itemPos of itemPositions) {
2064
+ if (tokens[itemPos]?.[0] !== '{') continue;
2065
+ const entryMembers = objectMembers(itemPos);
2066
+ if (!entryMembers) return text;
2067
+ const implMembers = entryMembers.filter(member => member.key === 'implementation');
2068
+ if (implMembers.length > 1) return text;
2069
+ if (implMembers.length === 1) spans.push(memberSpan(implMembers[0]));
2070
+ }
2071
+ }
2072
+ if (!spans.length) return text;
2073
+ spans.sort((a, b) => b[0] - a[0]);
2074
+ const projected = spans.reduce((current, [start, end]) => current.slice(0, start) + current.slice(end), body);
2075
+ const offset = block.indices[1][0];
2076
+ return text.slice(0, offset) + projected + text.slice(block.indices[1][1]);
2077
+ }
2078
+
2079
+ // The caller has parsed a root object. Keep surrounding whitespace and all
2080
+ // string/token bytes; remove only JSON whitespace between tokens.
2081
+ function compactInterface(body) {
2082
+ const start = body.indexOf('{'), end = body.lastIndexOf('}') + 1;
2083
+ let compacted = '', inString = false, escaped = false;
2084
+ for (const char of body.slice(start, end)) {
2085
+ if (inString) {
2086
+ compacted += char;
2087
+ if (escaped) escaped = false;
2088
+ else if (char === '\\') escaped = true;
2089
+ else if (char === '"') inString = false;
2090
+ } else if (char === '"') { inString = true; compacted += char; }
2091
+ else if (![' ', '\t', '\r', '\n'].includes(char)) compacted += char;
2092
+ }
2093
+ return body.slice(0, start) + compacted + body.slice(end);
2094
+ }
2095
+
2096
+ // Split only root object members, retaining authored token bytes. JSON has
2097
+ // already been parsed; quoted commas/braces and nested members stay opaque.
2098
+ function omitFullKind(body) {
2099
+ const members = [];
2100
+ let depth = 0, start, end;
2101
+ for (const token of body.matchAll(/"(?:[^"\\]|\\.)*"|[{}[\],:]/g)) {
2102
+ const char = token[0];
2103
+ if (char === '{' || char === '[') {
2104
+ if (depth === 0) start = token.index + 1;
2105
+ depth++;
2106
+ } else if (char === '}' || char === ']') {
2107
+ depth--;
2108
+ if (depth === 0) { members.push(body.slice(start, token.index)); end = token.index; break; }
2109
+ } else if (char === ',' && depth === 1) {
2110
+ members.push(body.slice(start, token.index)); start = token.index + 1;
2111
+ }
2112
+ }
2113
+ const kept = members.filter(member => JSON.parse(member.match(/^\s*("(?:[^"\\]|\\.)*")\s*:/)[1]) !== 'kind');
2114
+ // Keep the root's closing whitespace even if its final member was removed.
2115
+ const trailing = kept.at(-1) === members.at(-1) ? '' : members.at(-1).match(/\s*$/)[0];
2116
+ return body.slice(0, body.indexOf('{') + 1) + kept.join(',') + trailing + body.slice(end);
2117
+ }
2118
+
2119
+ function syncedCriteriaTexts(criteria, numbered) {
2120
+ if (!numbered.length || !Array.isArray(criteria) || criteria.length !== numbered.length) return null;
2121
+ if (criteria.some(item => !criterionShape(item))) return null;
2122
+ const parsed = criteria.map(item => AC_ID.exec(item.id));
2123
+ if (!parsed.every(Boolean)) return null;
2124
+ const indices = parsed.map(match => Number(match[1]));
2125
+ if (indices.some(index => index < 1 || index > numbered.length) || new Set(indices).size !== indices.length) return null;
2126
+ return indices.map(index => numbered[index - 1]);
2127
+ }
2128
+
2129
+ // Replace only top-level criteria[].text string tokens in an already parsed scenario JSON object.
2130
+ function replaceCriteriaTexts(body, nextTexts) {
2131
+ const tokens = [...body.matchAll(/"(?:[^"\\]|\\.)*"|[{}[\],:]|[^\s{}[\],:"]+/g)];
2132
+ let at = 0;
2133
+ const node = () => {
2134
+ const head = tokens[at++];
2135
+ if (!head) return null;
2136
+ if (head[0] === '{') {
2137
+ const members = [];
2138
+ if (tokens[at]?.[0] !== '}') while (at < tokens.length) {
2139
+ const key = tokens[at++];
2140
+ if (!key?.[0].startsWith('"') || tokens[at]?.[0] !== ':') return null;
2141
+ at++;
2142
+ const value = node();
2143
+ if (!value) return null;
2144
+ members.push({ key: JSON.parse(key[0]), value });
2145
+ if (tokens[at]?.[0] === ',') at++; else break;
2146
+ }
2147
+ if (tokens[at]?.[0] !== '}') return null;
2148
+ at++;
2149
+ return { kind: 'object', members };
2150
+ }
2151
+ if (head[0] === '[') {
2152
+ const items = [];
2153
+ if (tokens[at]?.[0] !== ']') while (at < tokens.length) {
2154
+ const item = node();
2155
+ if (!item) return null;
2156
+ items.push(item);
2157
+ if (tokens[at]?.[0] === ',') at++; else break;
2158
+ }
2159
+ if (tokens[at]?.[0] !== ']') return null;
2160
+ at++;
2161
+ return { kind: 'array', items };
2162
+ }
2163
+ return { kind: head[0].startsWith('"') ? 'string' : 'scalar', start: head.index, end: head.index + head[0].length };
2164
+ };
2165
+ const root = node();
2166
+ const criteria = root?.kind === 'object' ? root.members.filter(member => member.key === 'criteria') : [];
2167
+ if (criteria.length !== 1 || criteria[0].value.kind !== 'array' || criteria[0].value.items.length !== nextTexts.length) return null;
2168
+ const edits = [];
2169
+ for (const [index, item] of criteria[0].value.items.entries()) {
2170
+ const texts = item.kind === 'object' ? item.members.filter(member => member.key === 'text') : [];
2171
+ if (texts.length !== 1 || texts[0].value.kind !== 'string') return null;
2172
+ edits.push({ start: texts[0].value.start, end: texts[0].value.end, text: JSON.stringify(nextTexts[index]) });
2173
+ }
2174
+ let out = body;
2175
+ for (const edit of edits.reverse()) out = out.slice(0, edit.start) + edit.text + out.slice(edit.end);
2176
+ return out;
2177
+ }
2178
+
2179
+ // Fill legacy draft hashes, omit full kind, and sync stale scenario criteria[].text.
2180
+ export function fillHashes({ root, files = gitFiles(root), targets, compact = false,workspace=loadRuntimeWorkspace({root}) }, ports = {}) {
2181
+ const isTestFolderJsonFn = ports?.isTestFolderJson ?? defaultIsTestFolderJson;
2182
+ const isStoryPathFn = ports?.isStoryPath ?? defaultIsStoryPath;
2183
+ const matchTestsFn = ports?.matchTests ?? defaultMatchTests;
2184
+ workspace=boundedWorkspace(root,workspace);
2185
+ const result = { filled: [], current: [], refused: [], stale: [], warnings: [] }, synced = [];
2186
+ Object.defineProperty(result, 'synced', { value: synced });
2187
+ if (compact === true) result.compacted = [];
2188
+ const visibleSet = new Set(files);
2189
+ const targetSet = targets === undefined ? null : new Set(targets);
2190
+ const candidates = targetSet ? files.filter(path => targetSet.has(path)) : files;
2191
+ for (const path of candidates) {
2192
+ if (!allowsRuntimePath(workspace,path) || !path.endsWith('.prompt.md') || !statOf(join(root, path))?.isFile()) continue;
2193
+ let text;try{text=filePort(root,visibleSet,true,workspace).read({path}).content;}catch(error){result.refused.push({path,message:error.message});continue;}
2194
+ const blocks = interfaceBlocks(text);
2195
+ try {
2196
+ preparedText(root,visibleSet,path,text,'prompt',workspace);
2197
+ if(workspace.configured){const pending=[path],seen=new Set(),port=sourceFilePort(root,visibleSet);
2198
+ for(let i=0;i<pending.length;i++){const owner=pending[i];if(seen.has(owner))continue;seen.add(owner);const content=owner===path?text:port.read({path:owner}).content;
2199
+ for(const raw of markdownContext(content)){const target=contextPath(raw,owner,visibleSet);if(target){requireRuntimePath(workspace,{path:target,from:owner,chain:[path]});pending.push(target);}}
2200
+ if(owner.endsWith('.prompt.md'))for(const block of interfaceBlocks(content)){let doc;try{doc=JSON.parse(block[1]);}catch{continue;}for(const call of doc.calls??[])if(typeof call?.target==='string'){requireRuntimePath(workspace,{path:call.target,from:owner,chain:[path]});pending.push(call.target);}}
2201
+ }}
2202
+ }
2203
+ catch (error) { result.refused.push({path,message:error.message}); continue; }
2204
+ if (!blocks.length) continue;
2205
+ if (blocks.length > 1) { result.refused.push({ path, message: `${path} has more than one Runtime interface block. Keep one.` }); continue; }
2206
+ const [start, end] = blocks[0].indices[1], body = blocks[0][1];
2207
+ let value;
2208
+ try { value = JSON.parse(body); } catch { result.refused.push({ path, message: `The Runtime interface of ${path} is not valid JSON.` }); continue; }
2209
+ if (!isObject(value)) { result.refused.push({ path, message: `The Runtime interface of ${path} is not a JSON object.` }); continue; }
2210
+ if (!Object.hasOwn(value, 'status')) {
2211
+ if (Object.hasOwn(value, 'prose_sha256')) result.refused.push({ path, message: `The Runtime interface of ${path} has no status. Add "status": "draft" to its Runtime interface.` });
2212
+ else result.warnings.push({ path, message: `The Runtime interface of ${path} has no status and no prose_sha256, so pdd skipped it. Add "status": "draft" if this legacy interface block is active.` });
2213
+ continue;
2214
+ }
2215
+ const hash = proseSha256(text);
2216
+ if (value.status === 'approved') { (value.prose_sha256 === hash ? result.current : result.stale).push({ path }); continue; }
2217
+ if (value.status !== 'draft') { result.refused.push({ path, message: `${path} has status ${show(value.status)}. Use "draft" until the person approves it.` }); continue; }
2218
+ if (!Object.hasOwn(value, 'prose_sha256')) { result.refused.push({ path, message: `${path} has no "prose_sha256" key. Add "prose_sha256": "" to its Runtime interface.` }); continue; }
2219
+ const current = value.prose_sha256 === hash;
2220
+ let changed = body;
2221
+ if (!current) {
2222
+ const key = /("prose_sha256"\s*:\s*)"(?:[^"\\]|\\.)*"/g;
2223
+ changed = [...body.matchAll(key)].length === 1 ? body.replace(key, `$1"${hash}"`) : null;
2224
+ let same = false;
2225
+ try { same = changed !== null && isDeepStrictEqual(JSON.parse(changed), { ...value, prose_sha256: hash }); } catch { same = false; }
2226
+ if (!same) { result.refused.push({ path, message: `pdd could not fill "prose_sha256" in ${path}. Make it one string value, for example "prose_sha256": "".` }); continue; }
2227
+ }
2228
+ const normalized = value.kind === 'full';
2229
+ if (normalized) {
2230
+ const expected = { ...value, prose_sha256: hash };
2231
+ delete expected.kind;
2232
+ const omitted = omitFullKind(changed);
2233
+ if (!isDeepStrictEqual(JSON.parse(omitted), expected)) { result.refused.push({ path, message: `pdd could not remove /kind from ${path} safely.` }); continue; }
2234
+ changed = omitted;
2235
+ }
2236
+ const compacted = compact === true ? compactInterface(changed) : changed;
2237
+ const whitespaceChanged = compacted !== changed;
2238
+ changed = compacted;
2239
+ const next = text.slice(0, start) + changed + text.slice(end);
2240
+ if (proseSha256(next) !== hash) { result.refused.push({ path, message: `pdd could not fill "prose_sha256" in ${path} without a change to its text.` }); continue; }
2241
+ if (next !== text) {
2242
+ requireRuntimePath(loadRuntimeWorkspace({root}),{path,from:'Hash destination'});
2243
+ const safe=filePort(root,visibleSet,true);
2244
+ if(safe.read({path}).content!==text)throw new PreflightError(5,`${path}: changed before hash write.`);
2245
+ writeFileSync(join(root, path), next);
2246
+ }
2247
+ (current ? result.current : result.filled).push({ path });
2248
+ if (normalized) result.warnings.push({ path, message: `${path} /kind: removed redundant "kind": "full"; full interfaces omit kind.` });
2249
+ if (whitespaceChanged) result.compacted.push({ path });
2250
+ }
2251
+ const excludedRoots = targetSet ? [] : fixtureProjectRoots(root, files);
2252
+ const scenarioFiles = (targetSet ? candidates : outsideFixtureProjects(candidates, excludedRoots))
2253
+ .filter(path => isTestFolderJsonFn(path) && allowsRuntimePath(workspace, path));
2254
+ if (scenarioFiles.length) {
2255
+ const storyFiles = (targetSet ? files : outsideFixtureProjects(files, excludedRoots))
2256
+ .filter(path => isStoryPathFn(path) && allowsRuntimePath(workspace, path));
2257
+ const matchedByPath = new Map(matchTestsFn(storyFiles, [...new Set([...storyFiles, ...scenarioFiles])]).tests
2258
+ .flatMap(entry => (entry.files ?? [entry.path]).map(path => [path, entry])));
2259
+ for (const path of scenarioFiles) {
2260
+ if (!statOf(join(root, path))?.isFile()) continue;
2261
+ let rawText, doc;
2262
+ try {
2263
+ rawText = filePort(root, visibleSet, true, workspace).read({ path }).content;
2264
+ doc = parseScenarioJson(rawText);
2265
+ } catch { continue; }
2266
+ if (!isObject(doc) || doc.schema_version !== TEST_SCHEMA || typeof doc.story_path !== 'string' || !doc.story_path) continue;
2267
+ if (!visibleSet.has(doc.story_path) || !allowsRuntimePath(workspace, doc.story_path)) continue;
2268
+ const matched = matchedByPath.get(path);
2269
+ if (matched?.problem || (matched?.storyPath && matched.storyPath !== doc.story_path)) continue;
2270
+ let storySource;
2271
+ try { storySource = sourceFilePort(root, visibleSet, workspace).read({ path: doc.story_path }).content; } catch { continue; }
2272
+ const nextTexts = syncedCriteriaTexts(doc.criteria, numberedStoryCriteria(storySource, { requireHeading: true }));
2273
+ if (!nextTexts || nextTexts.every((text, index) => doc.criteria[index].text === text)) continue;
2274
+ const next = replaceCriteriaTexts(rawText, nextTexts);
2275
+ if (next === null || next === rawText) continue;
2276
+ const expectedDoc = { ...doc, criteria: doc.criteria.map((item, index) => ({ ...item, text: nextTexts[index] })) };
2277
+ let same = false;
2278
+ try { same = isDeepStrictEqual(parseScenarioJson(next), expectedDoc); } catch { same = false; }
2279
+ if (!same) continue;
2280
+ requireRuntimePath(loadRuntimeWorkspace({ root }), { path, from: 'Hash destination' });
2281
+ const safe = filePort(root, visibleSet, true);
2282
+ if (safe.read({ path }).content !== rawText) throw new PreflightError(5, `${path}: changed before hash write.`);
2283
+ writeFileSync(join(root, path), next);
2284
+ synced.push({ path });
2285
+ }
2286
+ }
2287
+ return result;
2288
+ }
2289
+
2290
+ const SECRET_NAME = /^(?:\.env.*|auth\.json|credentials\.json|id_rsa|id_ed25519|id_ecdsa|id_dsa|\.npmrc|\.netrc|\.git-credentials|\.pypirc|.+\.(?:pem|key|p12|pfx|keystore|tfstate|tfvars))$/;
2291
+ const SECRET_PART = new Set(['secrets', '.ssh', '.codex', '.terraform', '.aws']);
2292
+ export const isSecretPath = path => SECRET_NAME.test(basename(path)) || path.split('/').some(part => SECRET_PART.has(part))
2293
+ || /(?:^|\/)\.docker\/config\.json$/.test(path)
2294
+ || /(?:^|\/)(?:\.pdd\/agents\.json|\.config\/pdd\/agents\.json)$/i.test(path);
2295
+
2296
+ function octal(header, offset, length, value) { header.write(`${value.toString(8).padStart(length - 1, '0')}\0`, offset, length, 'latin1'); }
2297
+ function tarHeader(name, size, type) {
2298
+ const header = Buffer.alloc(512);
2299
+ header.write(name, 0, 100, 'utf8');
2300
+ octal(header, 100, 8, 0o600); octal(header, 108, 8, 0); octal(header, 116, 8, 0);
2301
+ octal(header, 124, 12, size); octal(header, 136, 12, 0);
2302
+ header.fill(0x20, 148, 156);
2303
+ header.write(type, 156, 1, 'latin1');
2304
+ header.write('ustar\0', 257, 6, 'latin1'); header.write('00', 263, 2, 'latin1');
2305
+ octal(header, 329, 8, 0); octal(header, 337, 8, 0);
2306
+ let sum = 0;
2307
+ for (const byte of header) sum += byte;
2308
+ header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 8, 'latin1');
2309
+ return header;
2310
+ }
2311
+ const pad = size => Buffer.alloc((512 - (size % 512)) % 512);
2312
+ function paxRecord(key, value) {
2313
+ const body = ` ${key}=${value}\n`;
2314
+ let length = Buffer.byteLength(body) + 1;
2315
+ while (Buffer.byteLength(`${length}${body}`) !== length) length += 1;
2316
+ return Buffer.from(`${length}${body}`, 'utf8');
2317
+ }
2318
+
2319
+ // A deterministic ustar archive: Git names, mode 0600, mtime 0, PAX path for long or non-ASCII names.
2320
+ export function tarFiles(entries) {
2321
+ const parts = [];
2322
+ for (const { path, bytes } of entries) {
2323
+ let name = path;
2324
+ if (Buffer.byteLength(path) > 100 || /[^\x20-\x7e]/.test(path)) {
2325
+ const record = paxRecord('path', path);
2326
+ parts.push(tarHeader('PaxHeader', record.length, 'x'), record, pad(record.length));
2327
+ name = path.replace(/[^\x20-\x7e]/g, '_').slice(-100);
2328
+ }
2329
+ parts.push(tarHeader(name, bytes.length, '0'), bytes, pad(bytes.length));
2330
+ }
2331
+ parts.push(Buffer.alloc(1024));
2332
+ return Buffer.concat(parts);
2333
+ }
2334
+
2335
+ export const formatSize = bytes => bytes < 1024 ? `${bytes} bytes` : bytes < 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1048576).toFixed(1)} MB`;
2336
+
2337
+ // Selection is metadata, not a rewritten project: every archive name remains authored in the repo.
2338
+ const SOURCE_CONFIG = 'pdd-source.json';
2339
+ const sameStat = (a, b) => a && b && a.ino === b.ino && a.dev === b.dev && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
2340
+ const unstableSource = Symbol('unstable source');
2341
+ const sourceProblem = (from, path, reason) => Object.assign(new PreflightError(4, `${from}: ${path}${reason.startsWith(':') ? '' : ' '}${reason}`),
2342
+ {selection:from === SOURCE_CONFIG || from === 'App map'});
2343
+
2344
+ function sourcePath(raw, from) {
2345
+ if (typeof raw !== 'string' || !raw || raw.includes('\\') || /[\0-\x1f]/.test(raw) || raw.startsWith('/') || /^[A-Za-z]:/.test(raw)
2346
+ || raw.split('/').includes('..')) throw sourceProblem(from, String(raw), 'must be a repository-relative file path with no traversal.');
2347
+ const path = posix.normalize(raw);
2348
+ if (path === '.' || path === '.git' || path.startsWith('.git/')) throw sourceProblem(from, raw, 'must be a repository-relative file path.');
2349
+ return path;
2350
+ }
2351
+
2352
+ // Markdown links are relative to their owner; repo-root spellings also work when Git names them.
2353
+ function contextPath(raw, from, visible) {
2354
+ if (!raw || raw.startsWith('#') || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(raw)) return null;
2355
+ let target;
2356
+ try { target = decodeURIComponent(raw.split('#')[0]); }
2357
+ catch { throw sourceProblem(from, raw, 'is not a valid local context path.'); }
2358
+ if (!target) return null;
2359
+ if (target.startsWith('/') || target.includes('\\')) throw sourceProblem(from, raw, 'must stay inside this repository.');
2360
+ const relative = posix.normalize(posix.join(posix.dirname(from), target));
2361
+ const path = visible.has(relative) ? relative : visible.has(target.replace(/^\.\//, '')) ? target.replace(/^\.\//, '') : relative;
2362
+ return sourcePath(path === '.' ? './' : path, from);
2363
+ }
2364
+
2365
+ // Read only a section name, never rewritten HTML. Ambiguous markup retains context.
2366
+ function markdownSectionTitle(text) {
2367
+ const tokens = /<\/(strong|em|b|i)\s*>|<(strong|em|b|i)(?:\s+[A-Za-z_:][A-Za-z0-9_.:-]*(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*\s*>|[^<>]+/giy;
2368
+ const parts = [], tags = [];
2369
+ let consumed = 0;
2370
+ for (let match; (match = tokens.exec(text));) {
2371
+ if (match[1]) {
2372
+ if (tags.pop() !== match[1].toLowerCase()) return null;
2373
+ } else if (match[2]) tags.push(match[2].toLowerCase());
2374
+ else parts.push(match[0]);
2375
+ consumed = tokens.lastIndex;
2376
+ }
2377
+ if (consumed !== text.length || tags.length) return null;
2378
+ return parts.join('').replace(/\s+/g, ' ').trim();
2379
+ }
2380
+
2381
+ function markdownContext(text) {
2382
+ const prose = text.replace(INTERFACE, ''), markdown = markdownSectionText(prose), definitions = markdownDefinitions(markdown);
2383
+ const heading = /^##[ \t]+Dependencies[ \t]*\r?$/im.exec(markdown);
2384
+ const rest = heading ? prose.slice(heading.index + heading[0].length) : '';
2385
+ const maskedRest = heading ? markdown.slice(heading.index + heading[0].length) : '';
2386
+ const end = /^#{1,2}[ \t]+/m.exec(maskedRest);
2387
+ let dependencies = end ? rest.slice(0, end.index) : rest;
2388
+ let maskedDependencies = end ? maskedRest.slice(0, end.index) : maskedRest;
2389
+ // Legacy prompts use collapsible rule/reference sections instead of Markdown headings.
2390
+ // Keep collapsible dependency context; only an explicitly named new section ends it.
2391
+ for (const match of maskedDependencies.matchAll(/^ {0,3}<details\b[^>]*>\s*<summary\b[^>]*>([\s\S]*?)<\/summary\s*>/gim)) {
2392
+ const title = markdownSectionTitle(match[1]);
2393
+ if (title !== null && /^(?:(?:required )?(?:module )?rules|(?:required )?interface reference|decision path)(?:\s*:|$)/i.test(title)) {
2394
+ dependencies = dependencies.slice(0, match.index);
2395
+ maskedDependencies = maskedDependencies.slice(0, match.index);
2396
+ break;
2397
+ }
2398
+ }
2399
+ const paths = [...markdownLinks(maskedDependencies, definitions), ...markdownLinks(markdown, definitions, true)];
2400
+ // A bare filename is shorthand for a dependency item, not every code span in its description.
2401
+ for (const match of dependencies.matchAll(/^ {0,3}(?:[-+*]|[0-9]+[.)])[ \t]+`([^`\n]+)`(?=[ \t:]|$)/gm)) {
2402
+ // The list marker must be prose, even though this shorthand's path is a code span.
2403
+ const prefix = match[0].slice(0, match[0].indexOf('`'));
2404
+ if (!maskedDependencies.startsWith(prefix, match.index)) continue;
2405
+ const path = match[1];
2406
+ const externalOrCode = /^[~/%$]/.test(path) || /[\s\\:$%~<>*?|[\]{}()]/.test(path);
2407
+ const fileName = /\.[A-Za-z][A-Za-z0-9_-]*$/.test(posix.basename(path));
2408
+ const commonFile = /\.(?:md|prompt|txt|json|svg|css|csv|ya?ml|toml|xml|html?|[cm]?js|[cm]?ts|jsx|tsx|py|sh|sql|ini|conf)$/i.test(path);
2409
+ if (!externalOrCode && ((path.includes('/') && fileName) || commonFile || isSecretPath(path))) paths.push(path);
2410
+ }
2411
+ return paths;
2412
+ }
2413
+
2414
+ function sourceLimit(files) {
2415
+ const total = files.reduce((sum, file) => sum + file.size, 0);
2416
+ if (files.length > LIMITS.files || total > LIMITS.bytes) {
2417
+ const largest = [...files].sort((a, b) => b.size - a.size).slice(0, 5).map(file => ` ${file.path} ${formatSize(file.size)}`);
2418
+ throw Object.assign(new PreflightError(4, [`The repository is too big to send: ${files.length} files, ${formatSize(total)}. The limit is ${LIMITS.files} files and 10 MB.`,
2419
+ 'The largest files:', ...largest].join('\n')), {selection:true});
2420
+ }
2421
+ return total;
2422
+ }
2423
+
2424
+ function snapshotReader(root, diskVisible, beforeRead = () => {}, strict = false, workspace=loadRuntimeWorkspace({root})) {
2425
+ const snapshots = new Map();
2426
+ let unstable = false;
2427
+ root = realpathSync(root);
2428
+ const observations = new Map();
2429
+ const dependencyRepair = ' List required files explicitly, or move navigation-only links outside ## Dependencies.';
2430
+ const changed = () => { unstable = true; throw unstableSource; };
2431
+ function observe(path) {
2432
+ const stat = statOf(join(root, path));
2433
+ let link = null;
2434
+ if (stat?.isSymbolicLink()) {
2435
+ try { link = readlinkSync(join(root, path)); }
2436
+ catch (error) { if (['ENOENT', 'EINVAL', 'ENOTDIR'].includes(error.code)) changed(); throw error; }
2437
+ }
2438
+ const prior = observations.get(path);
2439
+ if (prior && (!(stat === null && prior.stat === null) && !sameStat(stat, prior.stat) || link !== prior.link)) changed();
2440
+ observations.set(path, { stat, link });
2441
+ return { stat, link };
2442
+ }
2443
+ function stable(paths = observations.keys()) {
2444
+ for (const path of paths) {
2445
+ const before = observations.get(path);
2446
+ const after = statOf(join(root, path));
2447
+ if (before.stat === null ? after !== null : !sameStat(before.stat, after)) return false;
2448
+ if (before.link !== null) {
2449
+ try { if (readlinkSync(join(root, path)) !== before.link) return false; }
2450
+ catch (error) { if (['ENOENT', 'EINVAL', 'ENOTDIR'].includes(error.code)) return false; throw error; }
2451
+ }
2452
+ }
2453
+ return true;
2454
+ }
2455
+ observe('');
2456
+ function inspectRaw(path, from, allowMissing = false, noLinks = false, control = false, presenceOnly = false) {
2457
+ path = sourcePath(path, from);
2458
+ const repair = from === 'Source' ? '' : dependencyRepair;
2459
+ if(!control)requireRuntimePath(workspace,{path,from});
2460
+ if (isSecretPath(path)) {
2461
+ // Refusal is already decided. Enrich it only along non-following metadata
2462
+ // whose ancestors have each been checked as directories.
2463
+ let detail = '';
2464
+ try {
2465
+ const parts = path.split('/');
2466
+ for (let i = 1; i <= parts.length; i++) {
2467
+ const current = parts.slice(0, i).join('/');
2468
+ const stat = statOf(join(root, current));
2469
+ if (stat?.isSymbolicLink()) { detail = `link ${current} -> ${readlinkSync(join(root, current))}: `; break; }
2470
+ if (!stat?.isDirectory()) break;
2471
+ }
2472
+ } catch {} // Metadata failure cannot override the secret refusal.
2473
+ throw sourceProblem(from, path, `: ${detail}the name looks like a secret. pdd never sends it.`);
2474
+ }
2475
+ if (snapshots.has(path)) {
2476
+ const file = snapshots.get(path);
2477
+ if (!presenceOnly && file.presenceOnly) throw sourceProblem(from,path,'is not a Git-visible file.');
2478
+ if (noLinks && file.target) throw sourceProblem(from, path, ': symbolic links are not allowed for prepared output.');
2479
+ return file;
2480
+ }
2481
+ let pending = path.split('/').filter(Boolean).map(part => ({part, context:null})), resolved = [], lastLink = null, firstLink = null, linkedVisible = false, authored = true;
2482
+ const seen = new Set(), observed = new Set(['']);
2483
+ const refuse = (reason, context = lastLink, plain = false) => {
2484
+ throw sourceProblem(from, path, context ? `: link ${context.path} -> ${context.link}: ${reason}` : `${plain ? '' : ': '}${reason}`);
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
+ };
2492
+ // Resolve components individually: an ancestor link must be checked before any
2493
+ // descendant is inspected. No host lookup follows an unchecked link.
2494
+ while (pending.length) {
2495
+ const {part, context} = pending.shift();
2496
+ if (!part || part === '.') continue;
2497
+ if (part === '..') {
2498
+ if (!resolved.length) refuse('resolution is outside the repository.', context);
2499
+ resolved.pop(); continue;
2500
+ }
2501
+ resolved.push(part);
2502
+ const current = resolved.join('/');
2503
+ observed.add(current);
2504
+ const { stat, link } = observe(current);
2505
+ if (link !== null) {
2506
+ lastLink = { path: current, link };
2507
+ firstLink ??= lastLink;
2508
+ // Only an ancestor in the authored spelling can authorize that spelling.
2509
+ // Links encountered after substitution cannot grant authored visibility.
2510
+ linkedVisible ||= authored && current !== path && diskVisible.has(current);
2511
+ authored = false;
2512
+ if (strict) refuse(current === path ? 'symbolic links are not allowed.' : 'symbolic link ancestor: symbolic links are not allowed.');
2513
+ if (noLinks) refuse('symbolic links are not allowed for prepared output.');
2514
+ if (isSecretPath(path) || isSecretPath(current)) refuse('the name looks like a secret. pdd never sends it.');
2515
+ const state = `${current}\0${pending.map(item => item.part).join('/')}`;
2516
+ if (seen.has(state)) refuse('symbolic link loop.');
2517
+ if (seen.size >= 40) refuse('too many links (loop or chain longer than 40).');
2518
+ seen.add(state);
2519
+ resolved.pop();
2520
+ if (isAbsolute(link)) {
2521
+ if (!link.startsWith(`${root}/`)) refuse('resolution is outside the repository.');
2522
+ const local = link.slice(root.length + 1);
2523
+ resolved = []; pending = [...local.split('/').map(part => ({part, context:lastLink})), ...pending];
2524
+ } else pending = [...link.split('/').map(part => ({part, context:lastLink})), ...pending];
2525
+ if(!control)requireRuntimePath(workspace,{path:posix.normalize([...resolved,...pending.map(x=>x.part)].join('/')),from,chain:[path,current]});
2526
+ continue;
2527
+ }
2528
+ if (isSecretPath(current) || (!pending.length && isSecretPath(path))) refuse('the name looks like a secret. pdd never sends it.', context ?? lastLink);
2529
+ if (!stat) {
2530
+ if (lastLink) refuse('broken link: target does not exist.', context ?? lastLink);
2531
+ if (!allowMissing) refuse('is not a Git-visible file on disk. Restore it or correct the declared dependency.' + repair, null, true);
2532
+ const file = { path, stat: null, size: 0, observed }; snapshots.set(path, file); return file;
2533
+ }
2534
+ if (pending.length && !stat.isDirectory()) refuse(`${lastLink ? 'non-directory ancestor' : 'has a non-directory ancestor'} (${current}).`, context ?? lastLink, !lastLink);
2535
+ if (!pending.length) {
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);
2542
+ const file = { path, stat, size: Number(stat.size), observed, ...(presenceOnly && !diskVisible.has(current) ? {presenceOnly:true} : {}), ...(lastLink ? { target: current } : {}) };
2543
+ snapshots.set(path, file); return file;
2544
+ }
2545
+ }
2546
+ refuseDirectory(resolved.join('/'));
2547
+ }
2548
+ function bytes(file) {
2549
+ if (file.bytes) return file.bytes;
2550
+ sourceLimit([file]);
2551
+ beforeRead(file);
2552
+ let fd;
2553
+ try {
2554
+ fd = openSync(join(root, file.target ?? file.path), constants.O_RDONLY | constants.O_NOFOLLOW);
2555
+ if (!sameStat(file.stat, fstatSync(fd, { bigint: true }))) { unstable = true; throw unstableSource; }
2556
+ if (!stable(file.observed)) changed();
2557
+ file.bytes = readFileSync(fd);
2558
+ if (!stable(file.observed)) changed();
2559
+ if (!sameStat(file.stat, fstatSync(fd, { bigint: true })) || file.bytes.length !== file.size) { unstable = true; throw unstableSource; }
2560
+ return file.bytes;
2561
+ } catch (error) {
2562
+ if (['ENOENT', 'ELOOP', 'ENOTDIR'].includes(error.code)) { unstable = true; throw unstableSource; }
2563
+ throw error;
2564
+ } finally { if (fd !== undefined) closeSync(fd); }
2565
+ }
2566
+ return { inspectRaw, bytes, snapshots, stable, get unstable() { return unstable; } };
2567
+ }
2568
+
2569
+ export function sourceFilePort(root, visible = new Set(gitFiles(root)),workspace) {
2570
+ return filePort(root, visible,false,workspace);
2571
+ }
2572
+
2573
+ function filePort(root, visible, strict = false,workspace) {
2574
+ let policy=boundedWorkspace(root,workspace),key=JSON.stringify(policy),reader = snapshotReader(root, visible, undefined, strict,policy);
2575
+ const refresh=path=>{const current=boundedWorkspace(root,workspace),next=JSON.stringify(current);requireRuntimePath(current,{path,from:'Source'});if(next!==key){policy=current;key=next;reader=snapshotReader(root,visible,undefined,strict,policy);}};
2576
+ return {
2577
+ stat({path}) {
2578
+ if(path!=='pdd-bindings.json')refresh(path);
2579
+ const file = reader.inspectRaw(path, 'Source', true, path==='pdd-bindings.json',path==='pdd-bindings.json');
2580
+ return { exists: !!file.stat, is_symlink: false, size: file.size };
2581
+ },
2582
+ read({path}) {
2583
+ if(path!=='pdd-bindings.json')refresh(path);
2584
+ const file = reader.inspectRaw(path, 'Source',false,path==='pdd-bindings.json',path==='pdd-bindings.json');
2585
+ if (!file.stat) throw sourceProblem('Source',path,'is missing.');
2586
+ try { return { content: reader.bytes(file).toString('utf8') }; }
2587
+ catch (error) { if (error === unstableSource) throw new PreflightError(5, `${path}: the file changed while pdd read it.`); throw error; }
2588
+ },
2589
+ };
2590
+ }
2591
+
2592
+ function preparedText(root, visible, path, text, format,workspace) {
2593
+ try { return expandSource({path,text,format},sourceFilePort(root,visible,workspace)); }
2594
+ catch (error) {
2595
+ if (error.code) throw new PreflightError(4, `${error.code}: ${error.message}`);
2596
+ throw error;
2597
+ }
2598
+ }
2599
+
2600
+ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=true,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=tests === undefined,validateCriteria=true,allowMissingInterfaces=true,stepIds=[] }, strict = false, ports = {}) {
2601
+ const { isStoryPath, matchTests } = requireSelectionPorts(ports);
2602
+ const headBefore = gitHead(root);
2603
+ const policyBefore=JSON.stringify(loadRuntimeWorkspace({root}));workspace=boundedWorkspace(root,workspace);
2604
+ const names = gitFiles(root), visible = new Set(names), overlay = new Map(), payload = new Map(), queue = [], visited = new Set();
2605
+ const chains=new Map(),preparationReads=new Set(),referenceReads=new Set();
2606
+ const effective = new Map(), provenance = new Map(), edges = new Map(), shared = new Set(), footprintPayload = new Map(), storyContexts = new Map();
2607
+ let selecting = true;
2608
+ const unavailable = new Map();
2609
+ const markUnavailable = (path,error) => unavailable.set(path,{path,cause:String(error.message ?? error).replace(/[\r\n\x00-\x1f\x7f]/g,' ').slice(0,4000)});
2610
+ const reader = snapshotReader(root,new Set(names),file => { if (payload.has(file.path)) sourceLimit([...payload.values()]); }, strict,workspace);
2611
+ const { inspectRaw, bytes, snapshots } = reader;
2612
+ function inspect(path, from) {
2613
+ if (overlay.has(path)) return overlay.get(path);
2614
+ const file = inspectRaw(path, from);
2615
+ if (!file.stat) throw sourceProblem(from, path, 'is missing. Restore it or correct the declared dependency.');
2616
+ return file;
2617
+ }
2618
+ function add(raw, from, role = 'context') {
2619
+ const path = sourcePath(raw, from);
2620
+ const chain=chains.get(from)??[];requireRuntimePath(workspace,{path,from,chain});
2621
+ if(!chains.has(path))chains.set(path,[...chain,from]);
2622
+ const file = inspect(path, from);
2623
+ for (const selected of payload.keys()) if (selected.startsWith(`${path}/`) || path.startsWith(`${selected}/`)) {
2624
+ throw sourceProblem(from, path, `conflicts with selected file ${selected}.`);
2625
+ }
2626
+ if (!footprintPayload.has(path)) footprintPayload.set(path,file);
2627
+ if (selecting && !payload.has(path)) payload.set(path, file);
2628
+ if (visible.has(from)) {
2629
+ if (!edges.has(from)) edges.set(from,new Set());
2630
+ edges.get(from).add(path);
2631
+ }
2632
+ queue.push({ path, role, upload:selecting });
2633
+ }
2634
+ const referenceFiles = {
2635
+ stat({path}) {
2636
+ const file = overlay.get(path) ?? inspectRaw(path,'Reference',true);
2637
+ return {exists:overlay.has(path) || !!file.stat,is_symlink:false,size:file.size};
2638
+ },
2639
+ read({path}) {referenceReads.add(path); return {content:bytes(inspect(path,'Reference')).toString('utf8')}; },
2640
+ };
2641
+ function prepare(file, format) {
2642
+ if (effective.has(file.path)) return effective.get(file.path);
2643
+ let expanded;
2644
+ try { expanded = expandSource({path:file.path,text:bytes(file).toString('utf8'),format},referenceFiles); }
2645
+ catch (error) {
2646
+ if (reader.unstable || error === unstableSource) throw unstableSource;
2647
+ if (error.code) throw new PreflightError(4, `${error.code}: ${error.message}`);
2648
+ throw error;
2649
+ }
2650
+ let content = expanded.references.length ? Buffer.from(expanded.text,'utf8') : bytes(file);
2651
+ if (format === 'scenario') {
2652
+ let doc; try { doc = parseScenarioJson(content.toString('utf8')); } catch { /* Keep invalid-source handling. */ }
2653
+ const expected = matchTests(names.filter(isStoryPath), names).tests.find(test=>test.path===file.path);
2654
+ const authority = doc?.schema_version !== TEST_SCHEMA ? null : isObject(doc) && (typeof doc.story_path !== 'string' || !doc.story_path)
2655
+ ? refusal('pdd-no-story', 'story_path', 'The test has no story_path. Name its Story.')
2656
+ : discoveryRefusal({path:file.path,storyPath:expected?.storyPath,doc});
2657
+ if (authority) throw Object.assign(new PreflightError(4, `${file.path}: ${authority.message}`), authority,
2658
+ {message:`${file.path}: ${authority.message}`,hint:'Restore the Story path selected by the test name, then run the selection again.'});
2659
+ if (typeof doc?.story_path === 'string' && !documentRefusal(doc, file.path, { allowOmittedCriteria: true })) {
2660
+ add(doc.story_path, file.path, 'story');
2661
+ if (validateCriteria || stepIds.length) {
2662
+ const storySource = bytes(inspect(doc.story_path, file.path)).toString('utf8');
2663
+ const partial = partialTestRefusal(doc);
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
+ }
2686
+ if (resolved.refusal && needsCriteriaResolution(doc)) {
2687
+ throw Object.assign(new PreflightError(4, `${file.path}: ${resolved.refusal.message}`), resolved.refusal,
2688
+ { message: `${file.path}: ${resolved.refusal.message}`, hint: 'Fix the scenario criteria or Story acceptance list, then run the selection again.' });
2689
+ }
2690
+ if (resolved.changed && !resolved.refusal) content = Buffer.from(stringifyScenarioJson(resolved.doc), 'utf8');
2691
+ if (!resolved.refusal && !scenarioShapeRefusal(resolved.doc, file.path)) {
2692
+ const plan = capturedCriterionPlan(resolved.doc, storyCriteria(checkedStory), file.path);
2693
+ if (resolved.changed || (plan?.not_checked.length && plan.checked)) {
2694
+ content = Buffer.from(stringifyScenarioJson({ ...resolved.doc, criteria: plan.criteria,
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');
2696
+ }
2697
+ }
2698
+ }
2699
+ }
2700
+ }
2701
+ const result = {...file,bytes:content,size:content.length};
2702
+ effective.set(file.path,result); provenance.set(file.path,expanded.references);
2703
+ footprintPayload.set(file.path,result);
2704
+ if (selecting) payload.set(file.path,result);
2705
+ return result;
2706
+ }
2707
+ const addStrings = (values, from, role) => { if (Array.isArray(values)) for (const path of values) if (typeof path === 'string') add(path, from, role); };
2708
+ try {
2709
+ if (prepareSource !== undefined) {
2710
+ if (typeof prepareSource !== 'function') throw new PreflightError(4, 'prepareSource must be a synchronous function.');
2711
+ let active = true, prepared;
2712
+ const raw = (path, presenceOnly = false) => {
2713
+ if (!active) throw new PreflightError(4, 'Preparation ports are valid only during prepareSource.');
2714
+ return inspectRaw(sourcePath(path, 'prepareSource'), 'prepareSource', true, presenceOnly, false, presenceOnly);
2715
+ };
2716
+ try {
2717
+ prepared = prepareSource({
2718
+ readFile(path) {
2719
+ preparationReads.add(path);const file = raw(path);
2720
+ if (!file.stat) throw sourceProblem('prepareSource', path, 'is missing.');
2721
+ return Buffer.from(bytes(file));
2722
+ },
2723
+ statFile(path, options) {
2724
+ if(options !== undefined && (!isObject(options)||Object.keys(options).join(',')!=='presenceOnly'||options.presenceOnly!==true))throw new PreflightError(4,'Invalid presence-only stat option.');
2725
+ const file = raw(path, options?.presenceOnly===true);
2726
+ return { exists: !!file.stat, is_symlink: false, size: file.size };
2727
+ },
2728
+ });
2729
+ } finally { active = false; }
2730
+ if (reader.unstable) throw unstableSource;
2731
+ if (!Array.isArray(prepared)) throw new PreflightError(4, 'prepareSource must return an array of files synchronously.');
2732
+ for (const output of prepared) {
2733
+ if (!isObject(output) || !(typeof output.bytes === 'string' || output.bytes instanceof Uint8Array)) throw new PreflightError(4, 'prepareSource files need a path and Buffer, Uint8Array or UTF-8 string bytes.');
2734
+ const path = sourcePath(output.path, 'prepareSource');
2735
+ if (output.role !== undefined) {
2736
+ 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.');
2737
+ let map;try{map=JSON.parse(Buffer.from(output.bytes).toString('utf8'));}catch{throw new PreflightError(4,'Prepared app-map must be valid JSON.');}
2738
+ if(!isObject(map)||map.schema_version!=='prompt-runtime.app-map.v1')throw new PreflightError(4,'Prepared app-map must be a v1 app map.');
2739
+ appMap=path;
2740
+ }
2741
+ if (overlay.has(path)) throw sourceProblem('prepareSource', path, `duplicates prepared file ${path}.`);
2742
+ for (const other of overlay.keys()) if (other.startsWith(`${path}/`) || path.startsWith(`${other}/`)) throw sourceProblem('prepareSource', path, `conflicts with prepared file ${other}.`);
2743
+ inspectRaw(path, 'prepareSource', true, true);
2744
+ const content = Buffer.from(output.bytes), file = { path, bytes: content, size: content.length };
2745
+ overlay.set(path, file);
2746
+ visible.add(path);
2747
+ }
2748
+ for (const path of overlay.keys()) add(path, 'prepareSource');
2749
+ }
2750
+ if (sourceIncludes && visible.has(SOURCE_CONFIG)) {
2751
+ try {
2752
+ const config = overlay.get(SOURCE_CONFIG)??inspectRaw(SOURCE_CONFIG, SOURCE_CONFIG, false, false, true);
2753
+ let doc;
2754
+ try { doc = JSON.parse(bytes(config).toString('utf8')); } catch (error) {
2755
+ if (error === unstableSource) throw error;
2756
+ throw sourceProblem(SOURCE_CONFIG, '', 'must be valid JSON with only an include array.');
2757
+ }
2758
+ if (!isObject(doc) || Object.keys(doc).length !== 1 || !Array.isArray(doc.include)) throw sourceProblem(SOURCE_CONFIG, '', 'must contain only an include array of file paths.');
2759
+ for (const path of doc.include) { add(path, SOURCE_CONFIG); shared.add(sourcePath(path,SOURCE_CONFIG)); }
2760
+ } catch (error) { if (error !== unstableSource) error.selection = true; throw error; }
2761
+ }
2762
+ // The test name rule over the effective source (Git-visible files and prepared files); it opens no JSON file.
2763
+ const excluded = excludeFixtureProjects ? fixtureProjectRoots(root, names) : [];
2764
+ const discoveryNames = outsideFixtureProjects(names, excluded);
2765
+ const onDisk = discoverStories(root,discoveryNames,strict,workspace,null,ports);
2766
+ const named = matchTests(onDisk.storyFiles, outsideFixtureProjects([...onDisk.visible, ...overlay.keys()], excluded)).tests.filter(test=>!test.problem);
2767
+ const allNamed=matchTests(onDisk.storyFiles,discoveryNames).tests.flatMap(test=>(test.files??[test.path]).map(path=>({...test,path})));
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'});
2770
+ for (const path of selected) add(path, 'Selected test',path.endsWith('.prompt.md')?'context':isStoryPath(path)?'story':'test');
2771
+ if (appMap) { add(appMap, 'App map', 'app-map'); shared.add(sourcePath(appMap,'App map')); }
2772
+ const storyTests = new Map(), boundaries = new Map();
2773
+ let siblingsAdded = false;
2774
+ for (let index = 0; index < queue.length || !siblingsAdded; index++) {
2775
+ if (index === queue.length && !siblingsAdded) {
2776
+ siblingsAdded = true; selecting = false;
2777
+ const selectedStories = new Set(storyTests.keys());
2778
+ for (const test of allNamed) {
2779
+ if (!selectedStories.has(test.storyPath)) continue;
2780
+ if (!storyTests.get(test.storyPath).includes(test.path)) storyTests.get(test.storyPath).push(test.path);
2781
+ try { if(test.problem)markUnavailable(test.path,new Error(test.problem));add(test.path,'Story footprint','test'); } catch (error) { if (reader.unstable || error === unstableSource) throw error; markUnavailable(test.path,error); }
2782
+ }
2783
+ if (index === queue.length) break;
2784
+ }
2785
+ const { path, role, upload } = queue[index], key = `${path}\0${role}\0${upload}`;
2786
+ selecting = upload;
2787
+ if (visited.has(key)) continue;
2788
+ visited.add(key);
2789
+ try {
2790
+ let file = effective.get(path) ?? footprintPayload.get(path);
2791
+ if (selecting) payload.set(path,file);
2792
+ if (path.endsWith('.prompt.md')) file = prepare(file,'prompt');
2793
+ else if (role === 'test') file = prepare(file,'scenario');
2794
+ if (role === 'test' || role === 'app-map' || path.endsWith('.prompt.md') || path.endsWith('.md')) {
2795
+ const text = bytes(file).toString('utf8');
2796
+ if (role === 'test') {
2797
+ let doc;
2798
+ try { doc = JSON.parse(text); } catch { continue; } // Format refusals belong to preflight or server lint.
2799
+ if (!isObject(doc)) continue;
2800
+ const mapRefusal=appMapsRefusal(doc);
2801
+ if (mapRefusal) throw Object.assign(new PreflightError(4,path+': '+mapRefusal.section+': '+mapRefusal.message),
2802
+ {code:mapRefusal.code,section:mapRefusal.section});
2803
+ if (typeof doc.story_path === 'string') {
2804
+ 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); }
2805
+ add(doc.story_path, path, 'story');
2806
+ }
2807
+ addStrings(doc.entry_paths, path);
2808
+ addStrings(doc.app_maps, path, 'app-map');
2809
+ for (const step of Array.isArray(doc.steps) ? doc.steps : []) if (typeof step?.entry_path === 'string') add(step.entry_path, path);
2810
+ for (const item of Array.isArray(doc.context) ? doc.context : []) {
2811
+ if (typeof item?.prompt_path === 'string') add(item.prompt_path, path);
2812
+ addStrings(item?.paths, path);
2813
+ }
2814
+ } else if (role === 'app-map') {
2815
+ let map;
2816
+ try { map = JSON.parse(text); } catch { throw sourceProblem(path, '', 'must be valid app-map JSON.'); }
2817
+ const walk = value => {
2818
+ if (Array.isArray(value)) { for (const item of value) walk(item); return; }
2819
+ if (!isObject(value)) return;
2820
+ if (typeof value.prompt_path === 'string') add(value.prompt_path, path);
2821
+ if (typeof value.owner_prompt === 'string') add(value.owner_prompt, path);
2822
+ addStrings(value.stylesheets, path);
2823
+ for (const key of ['screens', 'router', 'routes', 'handlers', 'handler', 'after', 'timers', 'host_regions', 'helpers']) walk(value[key]);
2824
+ };
2825
+ walk(map);
2826
+ } else {
2827
+ if (role === 'story') {
2828
+ const notes=[];
2829
+ let boundary=runtimeBoundary(path,storyContexts.get(path) ?? text,{notes});
2830
+ if (boundary) {
2831
+ try {
2832
+ // Validate all members before admitting any boundary-only source.
2833
+ for (const member of boundary) {
2834
+ requireRuntimePath(workspace,{path:member,from:path,chain:chains.get(path)??[]});
2835
+ bytes(inspect(member,path));
2836
+ }
2837
+ } catch (error) {
2838
+ if (reader.unstable || error === unstableSource) throw error;
2839
+ boundary=null;
2840
+ notes.push({code:'boundary-not-applied',reason:'unreadable-path',
2841
+ message:'boundary not applied: unreadable-path; full dependency closure is required'});
2842
+ }
2843
+ }
2844
+ boundaries.set(path,{boundary,notes});
2845
+ for (const member of boundary ?? []) add(member,path);
2846
+ }
2847
+ for (const raw of markdownContext(storyContexts.get(path) ?? text)) { const context = contextPath(raw, path, visible); if (context) add(context, path); }
2848
+ if (path.endsWith('.prompt.md')) {
2849
+ for (const block of interfaceBlocks(text)) {
2850
+ let doc;
2851
+ try { doc = JSON.parse(block[1]); } catch { continue; }
2852
+ for (const call of Array.isArray(doc?.calls) ? doc.calls : []) if (typeof call?.target === 'string') add(call.target, path);
2853
+ }
2854
+ }
2855
+ }
2856
+ }
2857
+ // Footprint-only binary/plain inputs still need bounded bytes for hashes.
2858
+ if (!selecting) bytes(file);
2859
+ } catch (error) {
2860
+ if (role === 'app-map' && error !== unstableSource) error.selection = true;
2861
+ if (selecting || reader.unstable || error === unstableSource) throw error;
2862
+ markUnavailable(path,error);
2863
+ }
2864
+ }
2865
+ // A Story boundary selects executable interfaces, while preserving context prose.
2866
+ const bindingPrompts = new Map();
2867
+ for (const [path,file] of footprintPayload) if (path.endsWith('.prompt.md')) {
2868
+ const promptText = bytes(file).toString('utf8'), blocks = interfaceBlocks(promptText), frontmatter = parsePromptFrontmatter(promptText);
2869
+ if (!blocks.length && frontmatter.hasFrontmatter && !frontmatter.error && frontmatter.kind === 'native-only') { bindingPrompts.set(path, { kind: 'native-only', reason: frontmatter.reason }); continue; }
2870
+ if (!blocks.length && !frontmatter.hasFrontmatter && allowMissingInterfaces) { bindingPrompts.set(path, { entries: [], calls: [], resources: [] }); continue; }
2871
+ try { bindingPrompts.set(path,JSON.parse(blocks[0][1])); } catch { /* Admission reports malformed interfaces. */ }
2872
+ }
2873
+ const bindingPlans = [];
2874
+ for (const path of selected) {
2875
+ const file = payload.get(path); if (!file) continue;
2876
+ let doc; try { doc=JSON.parse(bytes(file).toString('utf8')); } catch { continue; }
2877
+ if (!doc?.story_path || !Array.isArray(doc.steps)) continue;
2878
+ try {
2879
+ const reached=new Set(), pending=[path,...shared];
2880
+ for (let index=0;index<pending.length;index++) {
2881
+ const dependency=pending[index];
2882
+ if (reached.has(dependency)) continue;
2883
+ reached.add(dependency);pending.push(...(edges.get(dependency)??[]));
2884
+ }
2885
+ bindingPlans.push(buildBindingPlan({test:{path,storyPath:doc.story_path,doc},
2886
+ storyText:bytes(inspect(doc.story_path,path)).toString('utf8'),prompts:bindingPrompts,
2887
+ dependencyPaths:[...reached].filter(dependency=>dependency.endsWith('.prompt.md')).sort(),
2888
+ boundaryState:boundaries.get(doc.story_path)}));
2889
+ } catch (error) { throw Object.assign(new PreflightError(4,error.message),{code:error.code}); }
2890
+ }
2891
+ const scoped = bindingPlans.filter(plan=>plan.boundary !== null);
2892
+ for (const plan of scoped) {
2893
+ for (const path of plan.boundary) inspect(path,plan.story);
2894
+ const crossing=plan.problems[0];
2895
+ if (crossing) throw Object.assign(new PreflightError(4,`${plan.story}: ${crossing.step_id}: ${crossing.prompt_path}: ${crossing.code}. Correct the Runtime interface boundary or call target.`),{code:'binding-boundary-invalid'});
2896
+ }
2897
+ const required = new Set(scoped.flatMap(plan=>plan.boundary));
2898
+ if (scoped.length === bindingPlans.length && scoped.length) for (const [path,file] of payload) {
2899
+ if (!path.endsWith('.prompt.md') || required.has(path)) continue;
2900
+ const projected=Buffer.from(bytes(file).toString('utf8').replace(INTERFACE,''),'utf8');
2901
+ const next={...file,bytes:projected,size:projected.length};
2902
+ payload.set(path,next); footprintPayload.set(path,next); effective.set(path,next);
2903
+ }
2904
+ // Project only effective executable bytes, after ordinary closure/boundary
2905
+ // handling. Authored readers and raw hashes retain the local classification.
2906
+ for (const [path, file] of footprintPayload) {
2907
+ if (!path.endsWith('.prompt.md') || unavailable.has(path)) continue;
2908
+ const original = bytes(file), text = original.toString('utf8'), projected = executableInterfaceText(text);
2909
+ // Invalid source must retain its original refusal, not become valid text
2910
+ // through UTF-8 replacement while removing unrelated metadata.
2911
+ if (projected === text || !original.equals(Buffer.from(text, 'utf8'))) continue;
2912
+ const content = Buffer.from(projected, 'utf8'), next = { ...file, bytes: content, size: content.length };
2913
+ footprintPayload.set(path, next); effective.set(path, next);
2914
+ if (payload.has(path)) payload.set(path, next);
2915
+ }
2916
+ const files = [...payload.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0), total = sourceLimit(files);
2917
+ const entries = files.map(file => ({ path: file.path, bytes: bytes(file) }));
2918
+ const rawFileHashes = Object.fromEntries([...footprintPayload.values()].flatMap(file=>{
2919
+ if (unavailable.has(file.path)) return [];
2920
+ try {
2921
+ // Cache metadata reuses observed raw bytes; it must not read an unread
2922
+ // replacement original merely to make a Story eligible for reuse.
2923
+ if (!file.path.endsWith('.prompt.md')) {
2924
+ const original = snapshots.get(file.path);
2925
+ return original?.bytes ? [[file.path,sha256(original.bytes)]] : [];
2926
+ }
2927
+ const original=inspectRaw(file.path,'Prompt snapshot',true);
2928
+ return original.stat ? [[file.path,sha256(bytes(original))]] : [];
2929
+ } catch (error) {
2930
+ if (payload.has(file.path) || reader.unstable || error === unstableSource) throw error;
2931
+ markUnavailable(file.path,error);
2932
+ return [];
2933
+ }
2934
+ }));
2935
+ const tar = tarFiles(entries);
2936
+ if (tar.length > LIMITS.bytes) throw Object.assign(new PreflightError(4, `The source archive is ${formatSize(tar.length)}. The limit is 10 MB.`), {selection:true});
2937
+ const same = !reader.unstable && gitHead(root) === headBefore && isDeepStrictEqual(gitFiles(root), names) && reader.stable() && JSON.stringify(loadRuntimeWorkspace({root}))===policyBefore;
2938
+ if (!same) return null;
2939
+ let sourceCommit = headBefore, sourceDirty = null, dirtyFiles = [];
2940
+ if (sourceCommit !== null) {
2941
+ const tree = gitTreeBlobs(root, sourceCommit);
2942
+ if (!tree) {
2943
+ sourceCommit = null;
2944
+ } else {
2945
+ const algo = sourceCommit.length === 64 ? 'sha256' : 'sha1';
2946
+ const checkedPaths = [...new Set([...files.map(file => file.path), ...referenceReads, ...preparationReads])].sort();
2947
+ for (const path of checkedPaths) {
2948
+ const rawBytes = overlay.has(path) ? overlay.get(path).bytes : snapshots.get(path)?.bytes;
2949
+ if (!rawBytes) { dirtyFiles.push(path); continue; }
2950
+ const oid = gitBlobOid(rawBytes, algo);
2951
+ const entry = tree.get(path);
2952
+ if (!entry) { dirtyFiles.push(path); continue; }
2953
+ if (entry.mode === '120000') {
2954
+ const target = snapshots.get(path)?.target;
2955
+ if (!target || tree.get(target)?.oid !== oid) dirtyFiles.push(path);
2956
+ continue;
2957
+ }
2958
+ if (entry.oid !== oid) dirtyFiles.push(path);
2959
+ }
2960
+ sourceDirty = dirtyFiles.length > 0;
2961
+ }
2962
+ }
2963
+ const stories = new Map();
2964
+ for (const path of selected) {
2965
+ let doc; try { doc = JSON.parse(bytes(payload.get(sourcePath(path,'Selected test'))).toString('utf8')); } catch { continue; }
2966
+ if (typeof doc?.story_path !== 'string') continue;
2967
+ if (!stories.has(doc.story_path)) stories.set(doc.story_path,{story_path:doc.story_path,tests:[],selected:new Set(shared)});
2968
+ const story = stories.get(doc.story_path);
2969
+ story.tests = storyTests.get(doc.story_path) ?? [path];
2970
+ for (const sibling of story.tests) story.selected.add(sibling);
2971
+ }
2972
+ const footprints = [...stories.values()].map(story => {
2973
+ const reached = new Set(), pending = [...story.selected];
2974
+ for (let i=0;i<pending.length;i++) {
2975
+ const path=pending[i]; if (reached.has(path)) continue;
2976
+ reached.add(path); pending.push(...(edges.get(path) ?? []));
2977
+ }
2978
+ const failures = [...reached].sort().filter(path=>unavailable.has(path)).map(path=>unavailable.get(path));
2979
+ if (failures.length) return {story_path:story.story_path,tests:story.tests.sort(),unavailable:failures};
2980
+ return {story_path:story.story_path,tests:story.tests.sort(),files:[...reached].sort().filter(path=>footprintPayload.has(path)).map(path=>({path,sha256:sha256(bytes(footprintPayload.get(path)))})),references:[...reached].sort().flatMap(path=>provenance.get(path) ?? [])};
2981
+ });
2982
+ return { appMap, tar, sha256: sha256(tar), files: files.map(({ path, size, target }) => ({ path, size, ...(target ? { target } : {}) })), bytes: total,
2983
+ references:[...provenance.keys()].filter(path=>payload.has(path)).sort().flatMap(path=>provenance.get(path)), stories:footprints,
2984
+ warnings:footprints.flatMap(story=>(story.unavailable ?? []).map(item=>`Warning: ${story.story_path}: footprint unavailable: ${item.cause}`)),
2985
+ raw_file_hashes:rawFileHashes,
2986
+ raw_prompt_hashes:Object.fromEntries(Object.entries(rawFileHashes).filter(([path])=>path.endsWith('.prompt.md'))),
2987
+ source_commit:sourceCommit,
2988
+ source_dirty:sourceDirty,
2989
+ dirty_files:dirtyFiles,
2990
+ reads:[...new Set([...onDisk.storyFiles,...snapshots.keys()])].filter(path=>path!==SOURCE_CONFIG&&!payload.has(path)&&(snapshots.get(path)?.bytes||onDisk.storyFiles.includes(path))).sort().map(path=>({path,roles:[...(onDisk.storyFiles.includes(path)?['discovery']:[]),...(referenceReads.has(path)?['reference']:[]),...(preparationReads.has(path)?['preparation']:[]),...(!onDisk.storyFiles.includes(path)&&!referenceReads.has(path)&&!preparationReads.has(path)?['footprint']:[])].sort()})),
2991
+ bindingPlans,
2992
+ sources:entries.map(file=>({path:file.path,bytes:Buffer.from(file.bytes)})) };
2993
+ } catch (error) { if (reader.unstable || error === unstableSource) return null; throw error; }
2994
+ }
2995
+
2996
+ // Rebuild the selection on each attempt, including metadata and newly declared dependencies.
2997
+ export function captureSource(root, { attempts = 3, ...selection } = {}, ports = {}) {
2998
+ return captureWithPolicy(root, { attempts, ...selection }, false, ports);
2999
+ }
3000
+
3001
+ // Resolve a scoped hash request before mutation. Capture remains the one owner
3002
+ // of source closure, availability, workspace and reference validation.
3003
+ captureSource.isDefaultCapture = true;
3004
+
3005
+ export function prepareHashSelection({ root, cwd, words }, ports = {}) {
3006
+ const explicitCapture = ports.capture ?? ports.captureSource;
3007
+ const isBuiltInCapture = !explicitCapture || explicitCapture === captureSource || explicitCapture.isDefaultCapture === true;
3008
+ const capture = explicitCapture ?? ((r, opts) => captureSource(r, opts, ports));
3009
+ const find = ports.findTests ?? (input => findTests(input, ports));
3010
+ const files = gitFiles(root), visible = new Set(files), workspace = loadRuntimeWorkspace({root});
3011
+ const realRoot = realpathSync(root), realCwd = realpathSync(cwd);
3012
+ const normalized = words.map(word => {
3013
+ const candidate = relative(realRoot, resolve(realCwd, word)).split(sep).join('/');
3014
+ return visible.has(candidate) || (!candidate.startsWith('../') && candidate !== '..' && statOf(resolve(realCwd, word))?.isDirectory()) ? (candidate || '.') : word;
3015
+ });
3016
+ for (const path of normalized) if (visible.has(path)) requireRuntimePath(workspace,{path,from:'Selected source'});
3017
+ const found = find({root,files,workspace,excludeFixtureProjects:false});
3018
+ const promptTargets = normalized.filter(path => visible.has(path) && path.endsWith('.prompt.md'));
3019
+ const testWords = normalized.filter(path => !promptTargets.includes(path));
3020
+ let selection = {selected:[],unknown:[],untested:[]};
3021
+ if (testWords.length) {
3022
+ if (typeof ports.selectTests !== 'function') {
3023
+ throw Object.assign(new Error('Test selection port (selectTests) is not bound.'), { unboundPort: true });
3024
+ }
3025
+ selection = ports.selectTests(found, testWords, { captureSource: capture });
3026
+ }
3027
+ if (selection.untested.length) throw new PreflightError(2, selection.untested.join('\n'));
3028
+ if (selection.unknown.length) {
3029
+ if ((found.untested ?? []).length && typeof ports.expectedTestPath !== 'function') {
3030
+ throw Object.assign(new Error('Test selection port (expectedTestPath) is not bound.'), { unboundPort: true });
3031
+ }
3032
+ const stories = [...found.tests.map(test => ` ${test.story} ${test.path}${test.title && test.title !== test.story ? ` (${test.title})` : ''}`),
3033
+ ...(found.untested ?? []).map(item => ` ${item.story} no test (expected ${ports.expectedTestPath(item.storyPath)})`)];
3034
+ throw new PreflightError(2, [`Unknown story ${selection.unknown.map(word => JSON.stringify(word)).join(', ')}. Stories:`, ...stories].join('\n'));
3035
+ }
3036
+ for (const test of selection.selected) {
3037
+ const problem = discoveryRefusal(test);
3038
+ if (problem) throw new PreflightError(4, problem.message);
3039
+ }
3040
+ const selectedTests = selection.selected.map(test => test.path);
3041
+ const captured = capture(root,{tests:[...selectedTests,...promptTargets],appMap:null,workspace,...(isBuiltInCapture?{validateCriteria:false}:{})});
3042
+ const inventory = captured.files.map(file => typeof file === 'string' ? file : file.path);
3043
+ return { files: [...new Set([...files, ...inventory])], targets: [...new Set([...inventory.filter(path => path.endsWith('.prompt.md')), ...selectedTests])] };
3044
+ }
3045
+
3046
+ function captureWithPolicy(root, { attempts = 3, ...selection } = {}, strict = false, ports = {}) {
3047
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
3048
+ const captured = captureOnce(root, selection, strict, ports);
3049
+ if (captured) return captured;
3050
+ }
3051
+ throw new PreflightError(5, `The files changed while pdd read them (${attempts} times). Stop other edits, then run pdd test again.`);
3052
+ }
3053
+
3054
+ // A bound capability keeps strict command reads isolated from source-upload reads.
3055
+ export function createStrictSourceAccess(root, workspace, ports = {}) {
3056
+ requireSelectionPorts(ports);
3057
+ return {
3058
+ sourceFilePort(visible = new Set(gitFiles(root))) { return filePort(root, visible, true, workspace); },
3059
+ findTests({ files = gitFiles(root) } = {}) { return discoverTests(root, files, true, workspace, false, ports); },
3060
+ captureSource(options = {}) { return captureWithPolicy(root, { ...options, ...(workspace ? { workspace } : {}) }, true, ports); },
3061
+ };
3062
+ }
3063
+
3064
+ const PROSE_NON_SOURCE_FILE = /(?:^|\/)\.[^/]+$|\.(?:json|jsonl|ndjson|ya?ml|toml|ini|cfg|conf|lock|md|txt|csv|tsv|xml|svg|png|jpe?g|gif|webp|ico|pdf|woff2?)$/i;
3065
+
3066
+ const defaultIsStoryPath = path =>
3067
+ path.endsWith('.md') && path.split('/').slice(0, -1).includes('user_stories') && !/^(?:plan|readme)\.md$/i.test(basename(path));
3068
+
3069
+ const defaultHasAcceptance = text => AC_HEADING.test(text);
3070
+
3071
+ const defaultIsTestFolderJson = path =>
3072
+ path.endsWith('.json') && path.split('/').slice(0, -1).some(part => part === 'test' || part === 'tests');
3073
+
3074
+ function defaultExpectedTestPath(storyPath) {
3075
+ const parts = storyPath.split('/').slice(0, -1);
3076
+ return [...parts.slice(0, parts.lastIndexOf('user_stories')), 'tests', `${storyName(storyPath)}.json`].join('/');
3077
+ }
3078
+
3079
+ function defaultMatchTests(storyPaths, files) {
3080
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
3081
+ const listed = items => (items.length < 3 ? items.join(' and ') : `${items.slice(0, -1).join(', ')} and ${items.at(-1)}`);
3082
+ const ownerNames = (name, names) => {
3083
+ const fits = names.has(name) ? [name] : [];
3084
+ for (let at = name.lastIndexOf('.'); at > 0; at = name.lastIndexOf('.', at - 1)) {
3085
+ if (names.has(name.slice(0, at))) fits.push(name.slice(0, at));
3086
+ }
3087
+ return fits;
3088
+ };
3089
+ const groups = new Map(), names = new Set();
3090
+ for (const path of [...new Set(storyPaths)].sort(byText)) {
3091
+ const name = storyName(path);
3092
+ names.add(name);
3093
+ if (!groups.has(name)) groups.set(name, { stories: [], files: new Map() });
3094
+ groups.get(name).stories.push(path);
3095
+ }
3096
+ const tests = [], untested = [], orphans = [], claimed = new Set();
3097
+ for (const path of [...new Set(files)].sort(byText)) {
3098
+ if (!defaultIsTestFolderJson(path)) continue;
3099
+ const base = basename(path, '.json'), owners = ownerNames(base, names);
3100
+ if (!owners.length) {
3101
+ orphans.push({ path, line: `${path} matches no Story (user_stories/**/${base}.md).` });
3102
+ continue;
3103
+ }
3104
+ if (owners.length > 1) {
3105
+ const stories = owners.flatMap(name => groups.get(name).stories).sort(byText);
3106
+ for (const name of owners) claimed.add(name);
3107
+ tests.push({
3108
+ path,
3109
+ files: [path],
3110
+ story: base,
3111
+ storyPath: null,
3112
+ storyPaths: stories,
3113
+ problem: `${path} matches ${stories.length} Stories: ${listed(stories)}. Rename one.`,
3114
+ });
3115
+ continue;
3116
+ }
3117
+ const same = groups.get(owners[0]).files;
3118
+ same.set(base, [...(same.get(base) ?? []), path]);
3119
+ }
3120
+ for (const [story, { stories, files: byName }] of groups) {
3121
+ if (!byName.size) {
3122
+ if (!claimed.has(story)) {
3123
+ untested.push(
3124
+ ...stories.map(storyPath => ({
3125
+ story,
3126
+ storyPath,
3127
+ line: `${storyPath} has no test: expected ${defaultExpectedTestPath(storyPath)} (or ${story}.json in any test or tests folder).`,
3128
+ })),
3129
+ );
3130
+ }
3131
+ continue;
3132
+ }
3133
+ const entry = (found, problem) => ({
3134
+ path: found[0],
3135
+ files: found,
3136
+ story,
3137
+ storyPath: stories.length === 1 ? stories[0] : null,
3138
+ storyPaths: stories,
3139
+ problem,
3140
+ });
3141
+ if (stories.length > 1) {
3142
+ const found = [...byName.values()].flat().sort(byText);
3143
+ tests.push(
3144
+ entry(found, `${listed(found)} ${found.length > 1 ? 'match' : 'matches'} ${stories.length} Stories: ${listed(stories)}. Rename one.`),
3145
+ );
3146
+ continue;
3147
+ }
3148
+ for (const [base, found] of byName) {
3149
+ tests.push(entry(found, found.length > 1 ? `${stories[0]} has ${found.length} files named ${base}.json: ${listed(found)}. Keep one.` : null));
3150
+ }
3151
+ }
3152
+ const sorted = (items, key) => items.sort((a, b) => byText(a[key], b[key]));
3153
+ return { tests: sorted(tests, 'path'), untested: sorted(untested, 'storyPath'), orphans: sorted(orphans, 'path') };
3154
+ }
3155
+
3156
+ const canonicalClaimPath = value => typeof value === 'string' && value.trim().length > 0 && value.length <= 1000 && !isAbsolute(value)
3157
+ && !/[\\\x00-\x1f\x7f]/.test(value) && !value.split('/').some(part => !part || part === '.' || part === '..' || part.toLowerCase() === '.git');
3158
+
3159
+ function openingClaimSentence(text) {
3160
+ const lines = text.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '').split(/\r?\n/);
3161
+ let at = 0;
3162
+ const blanks = () => { while (at < lines.length && !lines[at].trim()) at++; };
3163
+ blanks();
3164
+ if (/^# /.test(lines[at] ?? '')) { at++; blanks(); }
3165
+ const stop = line => !line.trim() || /^\s*#/.test(line) || /^\s*(?:```|~~~)/.test(line);
3166
+ const paragraph = [];
3167
+ while (at < lines.length && !stop(lines[at])) paragraph.push(lines[at++].trim());
3168
+ const joined = paragraph.join(' ');
3169
+ let code = false;
3170
+ for (let i = 0; i < joined.length; i++) {
3171
+ if (joined[i] === '`') code = !code;
3172
+ else if (!code && '.!?'.includes(joined[i]) && (i + 1 === joined.length || /\s/.test(joined[i + 1]))) return joined.slice(0, i + 1);
3173
+ }
3174
+ return joined;
3175
+ }
3176
+
3177
+ function localPromptClaims(promptPath, content) {
3178
+ if (!content) return [];
3179
+ const decoded = typeof content === 'string' ? content.slice(0, 65_536) : new TextDecoder().decode(content.subarray(0, 65_536));
3180
+ const folder = posix.dirname(promptPath), near = target => posix.normalize(posix.join(folder, target));
3181
+ let sentence = openingClaimSentence(decoded);
3182
+ const claims = [];
3183
+ sentence = sentence.replace(/\]\(([^)\s]+)\)/g, (_, target) => {
3184
+ const file = target.split('#')[0];
3185
+ if (file && !/^[a-z][a-z0-9+.-]*:/i.test(file)) claims.push(near(file));
3186
+ return ']';
3187
+ });
3188
+ for (let [run] of sentence.matchAll(/[A-Za-z0-9_@+~./-]+/g)) {
3189
+ run = run.replace(/\.+$/, '');
3190
+ if (run.includes('/') || run.includes('.')) claims.push(/^\.\.?\//.test(run) ? near(run) : run);
3191
+ }
3192
+ return [...new Set(claims.filter(path => canonicalClaimPath(path) && !path.endsWith('.prompt.md')))].sort();
3193
+ }
3194
+
3195
+ function localBindingTable(text) {
3196
+ if (text === null || text === undefined) return new Map();
3197
+ try {
3198
+ const doc = JSON.parse(text);
3199
+ if (!doc || typeof doc !== 'object' || doc.schema_version !== 'pdd.bindings.v1' || !Array.isArray(doc.modules)) return null;
3200
+ const table = new Map();
3201
+ for (const item of doc.modules) {
3202
+ if (!item || typeof item !== 'object' || typeof item.module !== 'string') continue;
3203
+ table.set(item.module, [...(table.get(item.module) ?? []), ...(typeof item.prompt === 'string' ? [item.prompt] : [])]);
3204
+ }
3205
+ return table;
3206
+ } catch { return null; }
3207
+ }
3208
+
3209
+ const OWNER_HEADER = /^\s*(?:\/\/+|#+|--|;+|\/\*+|\*+|<!--|"""|''')?\s*Generated from (\S+\.prompt\.md)(?: \(sha256: ([a-f0-9]{64})\))?\.?\s*(?:\*\/|-->|"""|''')?\s*$/;
3210
+ function localHeaderPrompts(content) {
3211
+ if (!content) return [];
3212
+ const bytes = typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
3213
+ const lines = new TextDecoder().decode(bytes.subarray(0, 4096)).split(/\r?\n/), seen = new Set();
3214
+ if (bytes.length > 4096) lines.pop();
3215
+ for (const line of lines.filter(item => item.length <= 1100)) {
3216
+ const match = OWNER_HEADER.exec(line);
3217
+ if (match && canonicalClaimPath(match[1])) seen.add(match[1]);
3218
+ }
3219
+ return [...seen];
3220
+ }
3221
+
3222
+ function defaultResolveOwners({ paths = [], bindings = null, heads = [], prompts = [] } = {}) {
3223
+ const table = bindings === false ? null : localBindingTable(bindings);
3224
+ const content = new Map(heads.map(row => [row.path, row.content]));
3225
+ const claims = prompts.map(row => [row.path, new Set(localPromptClaims(row.path, row.content))]);
3226
+ const files = [...new Set(paths)].map(path => {
3227
+ const bound = table?.get(path), head = content.get(path);
3228
+ const recorded = [...new Set([...(bound ?? []), ...localHeaderPrompts(head || null)])];
3229
+ const owners = recorded.length ? recorded : claims.filter(([, set]) => set.has(path)).map(([prompt]) => prompt).sort();
3230
+ const source = owners.length ? (bound?.includes(owners[0]) ? 'binding' : recorded.length ? 'header' : 'prose') : bound ? 'binding' : null;
3231
+ return { path, owners, source };
3232
+ });
3233
+ return { files };
3234
+ }
3235
+
3236
+ function readRegularPrefix(root, path, limit) {
3237
+ const stat = statOf(join(root, path));
3238
+ if (!stat?.isFile()) return null;
3239
+ let fd;
3240
+ try { fd = openSync(join(root, path), constants.O_RDONLY | constants.O_NOFOLLOW); }
3241
+ catch (error) {
3242
+ if (['ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code)) return null;
3243
+ if (['EACCES', 'EPERM', 'EISDIR'].includes(error.code)) return false;
3244
+ throw error;
3245
+ }
3246
+ try {
3247
+ const buffer = Buffer.alloc(Math.min(limit, Number(fstatSync(fd).size) + 1));
3248
+ let total = 0;
3249
+ while (total < buffer.length) {
3250
+ const count = readSync(fd, buffer, total, buffer.length - total, total);
3251
+ if (!count) break;
3252
+ total += count;
3253
+ }
3254
+ return buffer.subarray(0, total);
3255
+ } finally { closeSync(fd); }
3256
+ }
3257
+
3258
+ function safeClosureTarget(raw, from, allowedSet) {
3259
+ if (typeof raw !== 'string') return null;
3260
+ try {
3261
+ const resolved = from ? contextPath(raw, from, allowedSet) : sourcePath(raw, 'Selected source');
3262
+ return resolved && allowedSet.has(resolved) ? resolved : null;
3263
+ } catch { return null; }
3264
+ }
3265
+
3266
+ // Source files owned by more than one prompt: one warning line each, scoped to selected tests when supplied.
3267
+ export function sharedSourceFiles(root, visible, { tests = null, prompts: selectedPrompts = null, workspace = loadRuntimeWorkspace({ root }) } = {}, ports = {}) {
3268
+ const resolveOwnersFn = ports?.resolveOwners ?? defaultResolveOwners;
3269
+ const isStoryPathFn = ports?.isStoryPath ?? defaultIsStoryPath;
3270
+ const policy = boundedWorkspace(root, workspace);
3271
+ const allowedSet = new Set([...visible].filter(path => allowsRuntimePath(policy, path)));
3272
+ const promptPaths = [...allowedSet].filter(path => path.endsWith('.prompt.md')).sort();
3273
+ const promptTexts = new Map(), warnings = [];
3274
+ let linkedPort;
3275
+ for (const prompt of promptPaths) {
3276
+ const stat = statOf(join(root, prompt));
3277
+ if (Number(stat?.size ?? 0) > LIMITS.bytes) continue;
3278
+ let text;
3279
+ try { text = stat?.isSymbolicLink() ? (linkedPort ??= sourceFilePort(root, allowedSet, policy)).read({ path: prompt }).content : readText(root, prompt); }
3280
+ catch (error) {
3281
+ if (!(error instanceof PreflightError && error.exitCode === 4) && !['EACCES', 'EPERM', 'EISDIR', 'ENOENT'].includes(error.code)) throw error;
3282
+ warnings.push(`Warning: ${prompt}: source ownership advice unavailable (${error.code ?? error.message}).`); continue;
3283
+ }
3284
+ promptTexts.set(prompt, text);
3285
+ }
3286
+ let scope = null;
3287
+ if (tests !== null || selectedPrompts !== null) {
3288
+ scope = new Set();
3289
+ const queue = [], visited = new Set();
3290
+ const enqueue = (raw, from = null, role = 'context') => {
3291
+ const target = safeClosureTarget(raw, from, allowedSet);
3292
+ if (target && !visited.has(`${role}:${target}`)) queue.push({ path: target, role });
3293
+ };
3294
+ const readSafe = path => {
3295
+ if (promptTexts.has(path)) return promptTexts.get(path);
3296
+ const stat = statOf(join(root, path));
3297
+ if (!stat || Number(stat.size) > LIMITS.bytes) return null;
3298
+ try { return stat.isSymbolicLink() ? (linkedPort ??= sourceFilePort(root, allowedSet, policy)).read({ path }).content : readText(root, path); }
3299
+ catch { return null; }
3300
+ };
3301
+ for (const raw of selectedPrompts ?? []) {
3302
+ const target = safeClosureTarget(raw, null, allowedSet);
3303
+ if (target?.endsWith('.prompt.md')) { scope.add(target); enqueue(target); }
3304
+ }
3305
+ for (const entry of tests ?? []) {
3306
+ const testPath = typeof entry === 'string' ? safeClosureTarget(entry, null, allowedSet) : safeClosureTarget(entry?.path, null, allowedSet);
3307
+ let doc = isObject(entry?.doc) ? entry.doc : null;
3308
+ if (!doc && testPath) {
3309
+ const raw = readSafe(testPath);
3310
+ if (raw) { try { const parsed = JSON.parse(raw); if (isObject(parsed)) doc = parsed; } catch {} }
3311
+ }
3312
+ if (typeof entry?.storyPath === 'string') enqueue(entry.storyPath, null, 'story');
3313
+ if (!doc) continue;
3314
+ if (typeof doc.story_path === 'string') enqueue(doc.story_path, null, 'story');
3315
+ for (const item of Array.isArray(doc.entry_paths) ? doc.entry_paths : []) enqueue(item);
3316
+ for (const item of Array.isArray(doc.app_maps) ? doc.app_maps : []) enqueue(item, null, 'app-map');
3317
+ for (const step of Array.isArray(doc.steps) ? doc.steps : []) if (typeof step?.entry_path === 'string') enqueue(step.entry_path);
3318
+ for (const item of Array.isArray(doc.context) ? doc.context : []) {
3319
+ if (typeof item?.prompt_path === 'string') enqueue(item.prompt_path);
3320
+ for (const contextItem of Array.isArray(item?.paths) ? item.paths : []) enqueue(contextItem);
3321
+ }
3322
+ }
3323
+ while (queue.length) {
3324
+ const { path, role } = queue.shift(), key = `${role}:${path}`;
3325
+ if (visited.has(key)) continue;
3326
+ visited.add(key);
3327
+ if (path.endsWith('.prompt.md')) scope.add(path);
3328
+ if (role === 'app-map') {
3329
+ const text = readSafe(path); if (!text) continue;
3330
+ let map; try { map = JSON.parse(text); } catch { continue; }
3331
+ const walk = value => {
3332
+ if (Array.isArray(value)) { for (const item of value) walk(item); return; }
3333
+ if (!isObject(value)) return;
3334
+ if (typeof value.prompt_path === 'string') enqueue(value.prompt_path);
3335
+ if (typeof value.owner_prompt === 'string') enqueue(value.owner_prompt);
3336
+ for (const field of ['screens', 'router', 'routes', 'handlers', 'handler', 'after', 'timers', 'host_regions', 'helpers']) walk(value[field]);
3337
+ };
3338
+ walk(map);
3339
+ } else if (path.endsWith('.md')) {
3340
+ const text = readSafe(path); if (!text) continue;
3341
+ if (role === 'story' || isStoryPathFn(path)) {
3342
+ for (const member of runtimeBoundary(path, text) ?? []) enqueue(member);
3343
+ }
3344
+ for (const raw of markdownContext(text)) enqueue(raw, path);
3345
+ if (path.endsWith('.prompt.md')) {
3346
+ for (const block of interfaceBlocks(text)) {
3347
+ let doc; try { doc = JSON.parse(block[1]); } catch { continue; }
3348
+ for (const call of Array.isArray(doc?.calls) ? doc.calls : []) if (typeof call?.target === 'string') enqueue(call.target, path);
3349
+ }
3350
+ }
3351
+ }
3352
+ }
3353
+ }
3354
+ const candidatePaths = [...allowedSet].filter(path => !path.endsWith('.md')).sort((a, b) => a.localeCompare(b));
3355
+ const rawBindings = allowedSet.has('pdd-bindings.json') ? readRegularPrefix(root, 'pdd-bindings.json', 65_536) : null;
3356
+ const bindings = rawBindings ? rawBindings.toString('utf8') : rawBindings;
3357
+ const heads = candidatePaths.map(path => ({ path, content: readRegularPrefix(root, path, 4097) }));
3358
+ const prompts = [...promptTexts.entries()].map(([path, content]) => ({ path, content }));
3359
+ const allowedPromptSet = new Set(promptPaths);
3360
+ const resolved = resolveOwnersFn({ paths: candidatePaths, bindings, heads, prompts });
3361
+ const conflicts = [];
3362
+ for (const row of resolved.files) {
3363
+ if (row.source === 'prose' && PROSE_NON_SOURCE_FILE.test(row.path)) continue;
3364
+ const owners = [...new Set(row.owners.filter(prompt => allowedPromptSet.has(prompt)))].sort();
3365
+ if (owners.length < 2) continue;
3366
+ if (scope && !owners.some(prompt => scope.has(prompt))) continue;
3367
+ conflicts.push(`Warning: ${row.path} is named by ${owners.length} prompts (${owners.join(', ')}). One prompt should own each source file.`);
3368
+ }
3369
+ return [...warnings, ...conflicts];
3370
+ }
3371
+
3372
+ // Files sent that are not prompt, story or test files.
3373
+ export function otherFiles(files, found) {
3374
+ const known = new Set([...found.tests.map(test => test.path), ...found.stories.map(story => story.path)]);
3375
+ return files.filter(file => !file.path.endsWith('.prompt.md') && !known.has(file.path));
3376
+ }
3377
+
3378
+ const MISPLACED_CI = /^(?:\.github)\//i;
3379
+ const MISPLACED_CONFIG = /(?:^|\/)(?:package(?:-lock)?\.json|pdd\.json|tsconfig(?:\.[^/]+)?\.json|jsconfig\.json)$/i;
3380
+ const NON_CODE_ASSET = /(?:^|\/)\.[^/]+$|\.(?:json|jsonl|ndjson|ya?ml|toml|ini|cfg|conf|lock|md|txt|csv|tsv|xml|svg|png|jpe?g|gif|webp|ico|pdf|woff2?)$/i;
3381
+ const HEADER_COMMENT = /^\s*(?:\/\/+|#+|--|;+|\/\*+|\*+|<!--|"""|''')?\s*Generated from (\S+\.prompt\.md)(?: \(sha256: ([a-f0-9]{64})\))?\.?\s*(?:\*\/|-->|"""|''')?\s*$/;
3382
+ const EXCUSE_CLAUSE = /(?:^|;\s*)(?:(TODO|FIXME|HACK|XXX)(?:\([^)\r\n]*\))?(?=$|[\s:—–-])|(todo|fixme|hack)(?:\([^)\r\n]*\))?\s*[:—–-])/;
3383
+ const PROMPT_PROSE_LINE_LIMIT = 500;
3384
+ const PROMPT_PROSE_ELEVATED_LIMIT = 1000;
3385
+ const STORY_STEP_LIMIT = 15;
3386
+ const STORY_LINE_LIMIT = 1000;
3387
+
3388
+ function promptProseLineCount(text) {
3389
+ const prose = text.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '').replace(INTERFACE, '').trimEnd();
3390
+ return prose ? prose.split(/\r?\n/).length : 0;
3391
+ }
3392
+
3393
+ function promptProseWarningLine(promptPath, promptText) {
3394
+ if (typeof promptText !== 'string') return null;
3395
+ const proseLines = promptProseLineCount(promptText);
3396
+ if (proseLines > PROMPT_PROSE_ELEVATED_LIMIT) {
3397
+ return `Warning: oversized prompt (elevated): ${promptPath} has ${proseLines} prose lines (limit: ${PROMPT_PROSE_LINE_LIMIT}; elevated above ${PROMPT_PROSE_ELEVATED_LIMIT}). Split the module into focused contracts or mark native-only YAML frontmatter (kind: native-only) with deterministic code tests.`;
3398
+ }
3399
+ if (proseLines > PROMPT_PROSE_LINE_LIMIT) {
3400
+ return `Warning: oversized prompt: ${promptPath} has ${proseLines} prose lines (limit: ${PROMPT_PROSE_LINE_LIMIT}). Keep prompt prose focused on WHAT, WHY and failure boundaries; let shared $contract schemas own field inventories.`;
3401
+ }
3402
+ return null;
3403
+ }
3404
+
3405
+ function textLineCount(text) {
3406
+ if (typeof text !== 'string' || !text.length) return 0;
3407
+ const trimmed = text.replace(/\r?\n$/, '');
3408
+ return trimmed ? trimmed.split(/\r?\n/).length : 0;
3409
+ }
3410
+
3411
+ function storyComplexityWarningLine({ path, storyPath, doc }, rawText) {
3412
+ if (!isObject(doc) || (Object.hasOwn(doc, 'schema_version') && doc.schema_version !== TEST_SCHEMA)) return null;
3413
+ const steps = Array.isArray(doc.steps) ? doc.steps.length : 0;
3414
+ const lines = typeof rawText === 'string' ? textLineCount(rawText) : 0;
3415
+ const reasons = [];
3416
+ if (steps > STORY_STEP_LIMIT) reasons.push(`${steps} scenario steps (limit: ${STORY_STEP_LIMIT})`);
3417
+ if (lines > STORY_LINE_LIMIT) reasons.push(`${lines} lines (limit: ${STORY_LINE_LIMIT})`);
3418
+ if (!reasons.length) return null;
3419
+ const storyLabel = storyPath ?? (typeof doc.story_path === 'string' && doc.story_path.trim() ? doc.story_path.trim() : null) ?? path;
3420
+ return `Warning: oversized Story: ${storyLabel} (${path}) has ${reasons.join(' and ')}. Keep prompt scenarios focused on policy and authority boundaries and move multi-step state-machine or wire-protocol sequences to native tests (RUNBOOK.md §17, §18).`;
3421
+ }
3422
+
3423
+ function promptOpeningSentence(text) {
3424
+ const lines = new TextDecoder().decode(Buffer.from(text, 'utf8').subarray(0, 65_536)).replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '').split(/\r?\n/);
3425
+ let at = 0;
3426
+ const blanks = () => { while (at < lines.length && !lines[at].trim()) at++; };
3427
+ blanks();
3428
+ if (/^# /.test(lines[at] ?? '')) { at++; blanks(); }
3429
+ const stop = line => !line.trim() || /^\s*#/.test(line) || /^\s*(?:```|~~~)/.test(line);
3430
+ const paragraph = [];
3431
+ while (at < lines.length && !stop(lines[at])) paragraph.push(lines[at++].trim());
3432
+ const joined = paragraph.join(' ');
3433
+ let code = false;
3434
+ for (let i = 0; i < joined.length; i++) {
3435
+ if (joined[i] === '`') code = !code;
3436
+ else if (!code && '.!?'.includes(joined[i]) && (i + 1 === joined.length || /\s/.test(joined[i + 1]))) return joined.slice(0, i + 1);
3437
+ }
3438
+ return joined;
3439
+ }
3440
+
3441
+ function readOnlyConfigMention(promptPath, promptText, configPath) {
3442
+ const opening = promptOpeningSentence(promptText);
3443
+ const folder = posix.dirname(promptPath), near = target => posix.normalize(posix.join(folder, target));
3444
+ const positions = [];
3445
+ const masked = opening.replace(/\]\(([^)\s]+)\)/g, (full, target, index) => {
3446
+ const file = target.split('#')[0];
3447
+ if (file && !/^[a-z][a-z0-9+.-]*:/i.test(file) && near(file) === configPath) positions.push(index);
3448
+ return `]${' '.repeat(full.length - 1)}`;
3449
+ });
3450
+ for (const match of masked.matchAll(/[A-Za-z0-9_@+~./-]+/g)) {
3451
+ const run = match[0].replace(/\.+$/, '');
3452
+ if (!run.includes('/') && !run.includes('.')) continue;
3453
+ const resolved = /^\.\.?\//.test(run) ? near(run) : run;
3454
+ if (resolved === configPath) positions.push(match.index);
3455
+ }
3456
+ if (!positions.length) return false;
3457
+ const readVerb = /\b(?:read(?:s|ing)?|load(?:s|ing)?|pars(?:es?|ing)|inspect(?:s|ing)?|from)\b/gi;
3458
+ const ownVerb = /\b(?:owns?|owning|generates?|generating|writes?|writing|maintains?|maintaining|produces?|producing)\b/i;
3459
+ return positions.every(pos => {
3460
+ const prefix = opening.slice(0, pos);
3461
+ const matches = [...prefix.matchAll(readVerb)];
3462
+ if (!matches.length) return false;
3463
+ const last = matches.at(-1);
3464
+ const between = prefix.slice(last.index + last[0].length);
3465
+ return !ownVerb.test(between) && !/;/.test(between);
3466
+ });
3467
+ }
3468
+
3469
+ function scanExcuseComments(source, filePath) {
3470
+ if (!source || source.includes('\0')) return [];
3471
+ const hashComments = /\.(?:py|pyw|sh|bash|zsh|ksh|rb|pl|pm|r|jl|tcl|awk|sed|mk)$/i.test(filePath)
3472
+ || /(?:^|\/)(?:Makefile|Dockerfile|Containerfile|Justfile)$/i.test(filePath);
3473
+ const dashComments = /\.(?:sql|lua|hs|elm|ada)$/i.test(filePath);
3474
+ const slashComments = !hashComments && !dashComments;
3475
+ const jsLike = /\.(?:[cm]?[jt]sx?)$/i.test(filePath);
3476
+ const goFile = /\.go$/i.test(filePath);
3477
+ const rustFile = /\.rs$/i.test(filePath);
3478
+ const hits = [];
3479
+ const checkComment = (rawLine, body, lineNumber) => {
3480
+ if (HEADER_COMMENT.test(rawLine)) return;
3481
+ if (!EXCUSE_CLAUSE.test(body.trim())) return;
3482
+ hits.push({ line: lineNumber, text: rawLine.trim().replace(/\s+/g, ' ').slice(0, 160) });
3483
+ };
3484
+ let i = 0, line = 1, canStartRegex = true, afterDot = false;
3485
+ const templateBraces = [];
3486
+ if (source.startsWith('#!')) {
3487
+ const end = source.indexOf('\n');
3488
+ if (end < 0) return [];
3489
+ i = end + 1; line = 2;
3490
+ }
3491
+ const consumeJsTemplateBody = () => {
3492
+ while (i < source.length) {
3493
+ const ch = source[i];
3494
+ if (ch === '\\') { if (source[i + 1] === '\n') line++; i += 2; continue; }
3495
+ if (ch === '\n') { line++; i++; continue; }
3496
+ if (ch === '`') { i++; canStartRegex = false; afterDot = false; return; }
3497
+ if (ch === '$' && source[i + 1] === '{') { i += 2; templateBraces.push(0); canStartRegex = true; afterDot = false; return; }
3498
+ i++;
3499
+ }
3500
+ };
3501
+ while (i < source.length) {
3502
+ const ch = source[i], next = source[i + 1];
3503
+ if (ch === '\n') { line++; i++; continue; }
3504
+ if (ch === ' ' || ch === '\t' || ch === '\r') { i++; continue; }
3505
+ if (hashComments && (source.startsWith('"""', i) || source.startsWith("'''", i))) {
3506
+ const quote = source.slice(i, i + 3); i += 3;
3507
+ while (i < source.length && !source.startsWith(quote, i)) {
3508
+ if (source[i] === '\\') { if (source[i + 1] === '\n') line++; i += 2; continue; }
3509
+ if (source[i] === '\n') line++;
3510
+ i++;
3511
+ }
3512
+ i = Math.min(source.length, i + 3);
3513
+ continue;
3514
+ }
3515
+ if (rustFile && (ch === 'r' || (ch === 'b' && next === 'r'))) {
3516
+ const rawMatch = /^b?r(#*)"/.exec(source.slice(i));
3517
+ if (rawMatch) {
3518
+ const closing = `"${rawMatch[1]}`;
3519
+ i += rawMatch[0].length;
3520
+ const end = source.indexOf(closing, i);
3521
+ const body = source.slice(i, end < 0 ? source.length : end);
3522
+ for (let k = 0; k < body.length; k++) if (body[k] === '\n') line++;
3523
+ i = end < 0 ? source.length : end + closing.length;
3524
+ continue;
3525
+ }
3526
+ }
3527
+ if (rustFile && ch === "'") {
3528
+ if (next === '\\') {
3529
+ i += 2;
3530
+ while (i < source.length && source[i] !== "'" && source[i] !== '\n') {
3531
+ if (source[i] === '\\') i += 2;
3532
+ else i++;
3533
+ }
3534
+ if (source[i] === "'") i++;
3535
+ continue;
3536
+ }
3537
+ if (next && next !== "'" && next !== '\n') {
3538
+ const cp = source.codePointAt(i + 1);
3539
+ const cpLen = cp > 0xffff ? 2 : 1;
3540
+ if (source[i + 1 + cpLen] === "'") { i += 2 + cpLen; continue; }
3541
+ }
3542
+ let j = i + 1;
3543
+ while (j < source.length && /[A-Za-z0-9_]/.test(source[j])) j++;
3544
+ i = j;
3545
+ continue;
3546
+ }
3547
+ if (ch === "'" || ch === '"') {
3548
+ const quote = ch; i++;
3549
+ while (i < source.length && source[i] !== quote) {
3550
+ if (source[i] === '\\') { if (source[i + 1] === '\n') line++; i += 2; continue; }
3551
+ if (source[i] === '\n') { line++; if (!hashComments && !rustFile) { i++; break; } }
3552
+ i++;
3553
+ }
3554
+ if (source[i] === quote) i++;
3555
+ canStartRegex = false; afterDot = false;
3556
+ continue;
3557
+ }
3558
+ if (jsLike && ch === '`') {
3559
+ i++; consumeJsTemplateBody(); continue;
3560
+ }
3561
+ if (goFile && ch === '`') {
3562
+ i++;
3563
+ while (i < source.length && source[i] !== '`') {
3564
+ if (source[i] === '\n') line++;
3565
+ i++;
3566
+ }
3567
+ if (source[i] === '`') i++;
3568
+ continue;
3569
+ }
3570
+ if ((slashComments && ch === '/' && next === '/') || (hashComments && ch === '#') || (dashComments && ch === '-' && next === '-')) {
3571
+ const prefixLen = ch === '#' ? 1 : 2;
3572
+ let end = source.indexOf('\n', i);
3573
+ if (end < 0) end = source.length;
3574
+ const raw = source.slice(i, end).replace(/\r$/, '');
3575
+ const body = raw.slice(prefixLen).replace(/^[/#-]+/, '');
3576
+ checkComment(raw, body, line);
3577
+ i = end;
3578
+ continue;
3579
+ }
3580
+ if (slashComments && ch === '/' && next === '*') {
3581
+ const close = source.indexOf('*/', i + 2);
3582
+ const end = close < 0 ? source.length : close + 2;
3583
+ const parts = source.slice(i, end).split('\n');
3584
+ parts.forEach((part, offset) => {
3585
+ const clean = part.replace(/\r$/, '');
3586
+ const body = clean.replace(/^\s*\/\*+\s?/, '').replace(/\s?\*+\/\s*$/, '').replace(/^\s*\*+\s?/, '');
3587
+ if (body.trim()) checkComment(clean, body, line + offset);
3588
+ });
3589
+ line += parts.length - 1;
3590
+ i = end;
3591
+ continue;
3592
+ }
3593
+ if (jsLike && ch === '/' && canStartRegex) {
3594
+ let j = i + 1, inClass = false, closed = false;
3595
+ while (j < source.length && source[j] !== '\n') {
3596
+ if (source[j] === '\\') { j += 2; continue; }
3597
+ if (source[j] === '[') inClass = true;
3598
+ else if (source[j] === ']') inClass = false;
3599
+ else if (source[j] === '/' && !inClass) { closed = true; j++; break; }
3600
+ j++;
3601
+ }
3602
+ if (closed) {
3603
+ while (j < source.length && /[A-Za-z]/.test(source[j])) j++;
3604
+ i = j; canStartRegex = false; afterDot = false; continue;
3605
+ }
3606
+ }
3607
+ if (jsLike && templateBraces.length) {
3608
+ if (ch === '{') templateBraces[templateBraces.length - 1]++;
3609
+ else if (ch === '}') {
3610
+ if (templateBraces[templateBraces.length - 1] === 0) {
3611
+ templateBraces.pop(); i++; consumeJsTemplateBody(); continue;
3612
+ }
3613
+ templateBraces[templateBraces.length - 1]--;
3614
+ }
3615
+ }
3616
+ if (/[A-Za-z_$]/.test(ch)) {
3617
+ let j = i + 1;
3618
+ while (j < source.length && /[A-Za-z0-9_$]/.test(source[j])) j++;
3619
+ const word = source.slice(i, j);
3620
+ canStartRegex = !afterDot && /^(?:return|throw|case|delete|void|typeof|instanceof|in|of|new|yield|await|else|do)$/.test(word);
3621
+ afterDot = false;
3622
+ i = j;
3623
+ continue;
3624
+ }
3625
+ if (/[0-9]/.test(ch)) {
3626
+ let j = i + 1;
3627
+ while (j < source.length && /[0-9A-Za-z_.]/.test(source[j])) j++;
3628
+ canStartRegex = false; afterDot = false; i = j; continue;
3629
+ }
3630
+ if ((ch === '+' && next === '+') || (ch === '-' && next === '-')) {
3631
+ canStartRegex = false; afterDot = false; i += 2; continue;
3632
+ }
3633
+ if (ch === '?' && next === '.') {
3634
+ afterDot = true; canStartRegex = true; i += 2; continue;
3635
+ }
3636
+ if (ch === '!' && next !== '=' && !canStartRegex) {
3637
+ afterDot = false; i++; continue;
3638
+ }
3639
+ afterDot = ch === '.';
3640
+ canStartRegex = !/[)\]]/.test(ch);
3641
+ i++;
3642
+ }
3643
+ return hits;
3644
+ }
3645
+
3646
+ const defaultIsTestOwnedPath = path => canonicalClaimPath(path) && !path.endsWith('.prompt.md')
3647
+ && (/(?:^|\/)(?:tests?|__tests__)\//i.test(path) || /(?:^|\/)(?:[^/]+\.(?:test|spec)\.[^/]+|test_[^/]+\.[^/]+|[^/]+_test\.[^/]+)$/i.test(path));
3648
+
3649
+ export function lintLocalHygiene({ root, files = gitFiles(root), promptPaths, tests, workspace = loadRuntimeWorkspace({ root }) } = {}, ports = {}) {
3650
+ const resolveOwnersFn = ports?.resolveOwners ?? defaultResolveOwners;
3651
+ const promptClaimsFn = ports?.promptClaims ?? localPromptClaims;
3652
+ const isTestOwnedPathFn = ports?.isTestOwnedPath ?? defaultIsTestOwnedPath;
3653
+ const isStoryPathFn = ports?.isStoryPath ?? defaultIsStoryPath;
3654
+ const hasAcceptanceFn = ports?.hasAcceptance ?? defaultHasAcceptance;
3655
+ const matchTestsFn = ports?.matchTests ?? defaultMatchTests;
3656
+ const orphanSummaryFn = ports?.orphanSummary ?? (() => []);
3657
+ const policy = boundedWorkspace(root, workspace);
3658
+ const allowedFiles = [...new Set(files)].filter(path => !isSecretPath(path) && allowsRuntimePath(policy, path)).sort();
3659
+ const selectedPaths = [
3660
+ ...(promptPaths ?? []).map(path => path.replace(/^\.\//, '')),
3661
+ ...(tests ?? []).map(entry => typeof entry === 'string' ? entry.replace(/^\.\//, '') : entry?.path).filter(Boolean),
3662
+ ];
3663
+ const allFixtureRoots = fixtureProjectRoots(root, allowedFiles);
3664
+ const excluded = allFixtureRoots
3665
+ .filter(fixtureRoot => !selectedPaths.some(path => path === fixtureRoot || path.startsWith(`${fixtureRoot}/`)));
3666
+ const activeFixtureRoots = allFixtureRoots.filter(fixtureRoot => !excluded.includes(fixtureRoot));
3667
+ const projectRelativePath = path => {
3668
+ const ownerRoot = activeFixtureRoots.find(fixtureRoot => path.startsWith(`${fixtureRoot}/`));
3669
+ return ownerRoot ? path.slice(ownerRoot.length + 1) : path;
3670
+ };
3671
+ const scopedFiles = outsideFixtureProjects(allowedFiles, excluded);
3672
+ const visibleSet = new Set(scopedFiles);
3673
+ const inspectedPrompts = [...new Set((promptPaths ?? scopedFiles.filter(path => path.endsWith('.prompt.md')))
3674
+ .map(path => path.replace(/^\.\//, ''))
3675
+ .filter(path => visibleSet.has(path) && !isSecretPath(path) && path.endsWith('.prompt.md')))].sort();
3676
+ const inspectedSet = new Set(inspectedPrompts);
3677
+
3678
+ const realRoot = realpathSync(root);
3679
+ const strictReader = snapshotReader(realRoot, visibleSet, undefined, true, policy);
3680
+ const inspectStrict = (path, isControl = false) => {
3681
+ if (!visibleSet.has(path) || isSecretPath(path)) return null;
3682
+ try {
3683
+ const file = strictReader.inspectRaw(path, 'Source', true, isControl, isControl);
3684
+ return file.stat ? file : null;
3685
+ } catch { return null; }
3686
+ };
3687
+ const readStrictPrefix = (path, limit, isControl = false) => {
3688
+ const file = inspectStrict(path, isControl);
3689
+ if (!file) return null;
3690
+ let fd;
3691
+ try {
3692
+ fd = openSync(join(realRoot, file.path), constants.O_RDONLY | constants.O_NOFOLLOW);
3693
+ if (!sameStat(file.stat, fstatSync(fd, { bigint: true })) || !strictReader.stable(file.observed)) return null;
3694
+ const buffer = Buffer.alloc(Math.min(limit, file.size + 1));
3695
+ let total = 0;
3696
+ while (total < buffer.length) {
3697
+ const count = readSync(fd, buffer, total, buffer.length - total, total);
3698
+ if (!count) break;
3699
+ total += count;
3700
+ }
3701
+ if (!strictReader.stable(file.observed) || !sameStat(file.stat, fstatSync(fd, { bigint: true }))) return null;
3702
+ return buffer.subarray(0, total);
3703
+ } catch (error) {
3704
+ if (['ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code)) return null;
3705
+ if (['EACCES', 'EPERM', 'EISDIR'].includes(error.code)) return false;
3706
+ throw error;
3707
+ } finally { if (fd !== undefined) closeSync(fd); }
3708
+ };
3709
+ const readStrictText = path => {
3710
+ const file = inspectStrict(path);
3711
+ if (!file || file.size > LIMITS.bytes) return null;
3712
+ try { return strictReader.bytes(file).toString('utf8'); }
3713
+ catch { return null; }
3714
+ };
3715
+
3716
+ const allPromptPaths = [...visibleSet].filter(path => path.endsWith('.prompt.md')).sort();
3717
+ const promptTexts = new Map();
3718
+ const extraClaims = [];
3719
+ for (const prompt of allPromptPaths) {
3720
+ const text = readStrictText(prompt);
3721
+ if (typeof text !== 'string') continue;
3722
+ promptTexts.set(prompt, text);
3723
+ if (inspectedSet.has(prompt)) for (const claim of promptClaimsFn(prompt, text)) {
3724
+ if (!isSecretPath(claim) && allowsRuntimePath(policy, claim) && !claim.endsWith('.md')) extraClaims.push(claim);
3725
+ }
3726
+ }
3727
+
3728
+ const canonicalRepoPath = value => typeof value === 'string' && value.trim().length > 0 && value.length <= 1000 && !isAbsolute(value)
3729
+ && !/[\\\x00-\x1f\x7f]/.test(value) && !value.split('/').some(part => !part || part === '.' || part === '..' || part.toLowerCase() === '.git');
3730
+ const rawBindings = visibleSet.has('pdd-bindings.json') ? readStrictPrefix('pdd-bindings.json', 65_537, true) : null;
3731
+ const bindings = rawBindings ? (rawBindings.length > 65_536 ? false : rawBindings.toString('utf8')) : rawBindings;
3732
+ if (typeof bindings === 'string') {
3733
+ try {
3734
+ const doc = JSON.parse(bindings);
3735
+ if (isObject(doc) && doc.schema_version === 'pdd.bindings.v1' && Array.isArray(doc.modules)) {
3736
+ for (const item of doc.modules) {
3737
+ const mod = item?.module;
3738
+ if (typeof mod === 'string' && typeof item?.prompt === 'string' && inspectedSet.has(item.prompt)
3739
+ && canonicalRepoPath(mod) && !mod.endsWith('.md') && !isSecretPath(mod) && allowsRuntimePath(policy, mod)) {
3740
+ extraClaims.push(mod);
3741
+ }
3742
+ }
3743
+ }
3744
+ } catch { /* invalid JSON is handled by resolveOwners */ }
3745
+ }
3746
+ const candidatePaths = [...new Set([...[...visibleSet].filter(path => !path.endsWith('.md')), ...outsideFixtureProjects(extraClaims, excluded)])].sort();
3747
+ const heads = candidatePaths.map(path => ({ path, content: visibleSet.has(path) ? readStrictPrefix(path, 4097) : null }));
3748
+ const prompts = [...promptTexts.entries()].map(([path, content]) => ({ path, content }));
3749
+ const resolved = resolveOwnersFn({ paths: candidatePaths, bindings, heads, prompts });
3750
+
3751
+ const rawRowsByPrompt = new Map(), codeRowMap = new Map();
3752
+ for (const row of resolved.files) {
3753
+ const validOwners = row.owners.filter(prompt => promptTexts.has(prompt));
3754
+ if (!validOwners.length) continue;
3755
+ const classifiedPath = projectRelativePath(row.path);
3756
+ const isMisplacedTest = isTestOwnedPathFn(classifiedPath) || MISPLACED_CI.test(classifiedPath);
3757
+ const isConfig = MISPLACED_CONFIG.test(classifiedPath);
3758
+ const isCode = !isMisplacedTest && !isConfig && !NON_CODE_ASSET.test(classifiedPath);
3759
+ const fileInfo = isCode ? inspectStrict(row.path) : null;
3760
+ for (const owner of validOwners) {
3761
+ if (!rawRowsByPrompt.has(owner)) rawRowsByPrompt.set(owner, []);
3762
+ rawRowsByPrompt.get(owner).push({ row, isCode, isMisplacedTest, isConfig });
3763
+ }
3764
+ if (fileInfo && validOwners.some(owner => inspectedSet.has(owner))) {
3765
+ codeRowMap.set(row.path, [...new Set(validOwners)].sort());
3766
+ }
3767
+ }
3768
+
3769
+ const warnings = [];
3770
+ for (const prompt of inspectedPrompts) {
3771
+ const promptText = promptTexts.get(prompt);
3772
+ if (typeof promptText !== 'string') continue;
3773
+ const promptRows = rawRowsByPrompt.get(prompt) ?? [];
3774
+ const claimsProductionCode = promptRows.some(item => item.isCode);
3775
+ const misplaced = [];
3776
+ for (const { row, isMisplacedTest, isConfig } of promptRows) {
3777
+ if (isMisplacedTest) misplaced.push(row.path);
3778
+ else if (isConfig) {
3779
+ if (row.source === 'prose' && claimsProductionCode && readOnlyConfigMention(prompt, promptText, row.path)) continue;
3780
+ misplaced.push(row.path);
3781
+ }
3782
+ }
3783
+ if (misplaced.length) {
3784
+ const uniqueTargets = [...new Set(misplaced)].sort();
3785
+ warnings.push(`Warning: misplaced prompt owner: ${prompt} claims ${uniqueTargets.join(', ')}. Prompts own production modules, not test suites, CI workflows or repository config files.`);
3786
+ }
3787
+ const proseWarning = promptProseWarningLine(prompt, promptText);
3788
+ if (proseWarning) warnings.push(proseWarning);
3789
+ }
3790
+
3791
+ const matchedStoryByTest = new Map(
3792
+ matchTestsFn(scopedFiles.filter(isStoryPathFn), scopedFiles).tests.map(item => [item.path, item.storyPath]),
3793
+ );
3794
+ const inspectedTests = tests === undefined
3795
+ ? discoverTests(root, scopedFiles, true, policy, true, {
3796
+ isStoryPath: isStoryPathFn,
3797
+ hasAcceptance: hasAcceptanceFn,
3798
+ matchTests: matchTestsFn,
3799
+ orphanSummary: orphanSummaryFn,
3800
+ }).tests.map(item => ({ ...item, raw: readStrictText(item.path) }))
3801
+ : tests.map(entry => {
3802
+ const rawPath = typeof entry === 'string' ? entry : entry?.path;
3803
+ if (typeof rawPath !== 'string') return null;
3804
+ const clean = rawPath.replace(/^\.\//, '');
3805
+ if (!inspectStrict(clean)) return null;
3806
+ const raw = readStrictText(clean);
3807
+ if (!raw) return null;
3808
+ let doc;
3809
+ try { doc = JSON.parse(raw); } catch { return null; }
3810
+ const docStory = typeof doc?.story_path === 'string' && doc.story_path.trim() ? doc.story_path.trim() : null;
3811
+ const storyPath = (isObject(entry) && typeof entry.storyPath === 'string' && entry.storyPath)
3812
+ ? entry.storyPath
3813
+ : (matchedStoryByTest.get(clean) ?? docStory);
3814
+ return { path: clean, storyPath, doc, raw };
3815
+ }).filter(Boolean);
3816
+
3817
+ for (const testEntry of [...inspectedTests].sort((a, b) => String(a?.path ?? '').localeCompare(String(b?.path ?? '')))) {
3818
+ const storyWarning = storyComplexityWarningLine(testEntry, testEntry?.raw);
3819
+ if (storyWarning) warnings.push(storyWarning);
3820
+ }
3821
+
3822
+ for (const filePath of [...codeRowMap.keys()].sort()) {
3823
+ const sourceText = readStrictText(filePath);
3824
+ if (typeof sourceText !== 'string') continue;
3825
+ const owners = codeRowMap.get(filePath);
3826
+ for (const hit of scanExcuseComments(sourceText, filePath)) {
3827
+ warnings.push(`Warning: excuse comment in ${filePath}:${hit.line} (owned by ${owners.join(', ')}): ${hit.text}`);
3828
+ }
3829
+ }
3830
+
3831
+ return warnings;
3832
+ }