@promptdriven/runtime-client 1.1.2 → 1.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/runtime/contract-refs.mjs +4 -0
- package/src/runtime/index.mjs +27 -0
- package/src/runtime/prompt-clauses.mjs +290 -0
- package/src/runtime/run-program.mjs +13 -8
- package/src/runtime/runtime-binding-plan.mjs +116 -15
- package/src/runtime/runtime-bindings.mjs +11 -5
- package/src/runtime/runtime-check-plan.mjs +40 -14
- package/src/runtime/runtime-client.mjs +559 -154
- package/src/runtime/runtime-markdown.mjs +95 -41
- package/src/runtime/runtime-outcome.mjs +156 -5
- package/src/runtime/runtime-output.mjs +54 -9
- package/src/runtime/runtime-preflight.mjs +1176 -39
- package/src/runtime/try-doors.mjs +105 -23
- package/src/runtime/try-http.mjs +232 -10
- package/src/runtime/try-mcp.mjs +7 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
// Generated from prompts/cli/runtime-preflight.prompt.md (sha256:
|
|
1
|
+
// Generated from prompts/cli/runtime-preflight.prompt.md (sha256: b6e0d2ce079946533ab6b638592f1c0a0908b4a46da32e522ecdae3576bd6573).
|
|
2
2
|
import { markdownLinks, markdownDefinitions, markdownSectionText } from './runtime-markdown.mjs';
|
|
3
|
-
import {
|
|
3
|
+
import { buildClauseTable } from './prompt-clauses.mjs';
|
|
4
|
+
import { buildBindingPlan, runtimeBoundary, stepSimulation, simulationGraph, isMockedPortCall } from './runtime-binding-plan.mjs';
|
|
4
5
|
import { createHash } from 'node:crypto';
|
|
5
6
|
import { spawnSync } from 'node:child_process';
|
|
6
7
|
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readSync, readlinkSync, realpathSync, writeFileSync } from 'node:fs';
|
|
@@ -332,7 +333,7 @@ function interpreterIntegerWarning(doc, path) {
|
|
|
332
333
|
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. ';
|
|
333
334
|
return `Warning: ${path} scenario-integer-out-of-range: ${section} is ${found.value}, outside the PDD interpreter's integer range ${INTERPRETER_INTEGERS.text}, `
|
|
334
335
|
+ 'so the interpreter refuses this test before execution (0 AI calls). ' + spelling
|
|
335
|
-
+ "Check the exact value in the repository's own vector test (
|
|
336
|
+
+ "Check the exact value in the repository's own vector test (see the pdd skill reference verification.md, or run pdd help prompting); do not change the input type or the expected value to fit the interpreter.";
|
|
336
337
|
}
|
|
337
338
|
// Advice only: integer schema bound tokens that the interpreter refuses (graph-schema-invalid).
|
|
338
339
|
function schemaBoundWarnings(prompt) {
|
|
@@ -632,7 +633,7 @@ export function interfaceKindProblems(iface) {
|
|
|
632
633
|
if (!isObject(iface)) return [{code:'invalid-interface',pointer:'',rule:'must be an object.'}];
|
|
633
634
|
const kind = Object.hasOwn(iface, 'kind') ? iface.kind : 'full';
|
|
634
635
|
if (!['full', 'partial', 'native-only'].includes(kind)) return [{code:'interface-kind-invalid',pointer:'/kind',rule:'must be full, partial or native-only.'}];
|
|
635
|
-
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 (
|
|
636
|
+
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 (see the pdd skill reference prompting.md, or run pdd help prompting).'}];
|
|
636
637
|
return [];
|
|
637
638
|
}
|
|
638
639
|
// Local format advice (#3206): a draft that spells "kind": "full" still works, because
|
|
@@ -724,11 +725,12 @@ export function parsePromptFrontmatter(text) {
|
|
|
724
725
|
}
|
|
725
726
|
|
|
726
727
|
// The prompt file of an entry: {path, text, blocks, interface, error}.
|
|
727
|
-
export function readPrompt(root, visible, path,workspace=loadRuntimeWorkspace({root})) {
|
|
728
|
-
workspace
|
|
729
|
-
if(typeof path==='string')requireRuntimePath(
|
|
728
|
+
export function readPrompt(root, visible, path,workspace=loadRuntimeWorkspace({root}), sharedPort = null) {
|
|
729
|
+
const policy = sharedPort ? workspace : boundedWorkspace(root,workspace);
|
|
730
|
+
if(typeof path==='string')requireRuntimePath(policy,{path,from:'Prompt'});
|
|
730
731
|
if (typeof path !== 'string' || !path.endsWith('.prompt.md') || !visible.has(path)) return { path, error: 'entry-missing' };
|
|
731
|
-
const
|
|
732
|
+
const port = sharedPort ?? sourceFilePort(root,visible,policy);
|
|
733
|
+
const rawText = port.read({path}).content, prepared = preparedText(root,visible,path,rawText,'prompt',policy,port), text = prepared.text, blocks = interfaceBlocks(text);
|
|
732
734
|
const frontmatter = parsePromptFrontmatter(text);
|
|
733
735
|
const source = { path, rawText, text, blocks, references: prepared.references };
|
|
734
736
|
if (frontmatter.hasFrontmatter) {
|
|
@@ -912,13 +914,350 @@ export function analyzePromptSelectorWords(prompt, { appMapScreens = [] } = {})
|
|
|
912
914
|
return { kinds: [...kinds], items, duplicates, collisions, tableLines, warnings, programName };
|
|
913
915
|
}
|
|
914
916
|
|
|
917
|
+
const BUILTIN_STDLIB_PORTS = new Set([
|
|
918
|
+
'calc.eval', 'bytes.measure', 'hash.sha256', 'json.query', 'text.template',
|
|
919
|
+
'json.pick', 'json.merge', 'regex.extract', 'csv.parse',
|
|
920
|
+
'crypto.sha256_canonical_json', 'id.random',
|
|
921
|
+
]);
|
|
922
|
+
const DEFAULT_STATE_PORTS = new Set(['kv.get', 'kv.put', 'world.read', 'world.write']);
|
|
923
|
+
const GENERIC_SECTION_HEADINGS = new Set([
|
|
924
|
+
'operations', 'ports', 'calls', 'dependencies', 'behavior', 'rules', 'errors',
|
|
925
|
+
'state', 'examples', 'notes', 'overview', 'summary', 'context', 'constraints',
|
|
926
|
+
'inputs', 'outputs', 'interface', 'contract', 'contracts', 'appearance',
|
|
927
|
+
]);
|
|
928
|
+
|
|
929
|
+
function stripFencesAndComments(text) {
|
|
930
|
+
const withoutInterface = String(text ?? '').replace(INTERFACE, '');
|
|
931
|
+
const lines = withoutInterface.split(/\r?\n/);
|
|
932
|
+
const out = [];
|
|
933
|
+
let fence = null, inComment = false;
|
|
934
|
+
for (let line of lines) {
|
|
935
|
+
if (fence) {
|
|
936
|
+
out.push('');
|
|
937
|
+
const close = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(line);
|
|
938
|
+
if (close && close[1][0] === fence[0] && close[1].length >= fence.length) fence = null;
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
if (inComment) {
|
|
942
|
+
const endIdx = line.indexOf('-->');
|
|
943
|
+
if (endIdx < 0) { out.push(''); continue; }
|
|
944
|
+
line = line.slice(endIdx + 3);
|
|
945
|
+
inComment = false;
|
|
946
|
+
}
|
|
947
|
+
line = line.replace(/<!--[\s\S]*?-->/g, '');
|
|
948
|
+
const openComment = line.indexOf('<!--');
|
|
949
|
+
if (openComment >= 0) {
|
|
950
|
+
line = line.slice(0, openComment);
|
|
951
|
+
inComment = true;
|
|
952
|
+
}
|
|
953
|
+
const openFence = /^ {0,3}(`{3,}|~{3,})/.exec(line);
|
|
954
|
+
if (openFence) {
|
|
955
|
+
fence = openFence[1];
|
|
956
|
+
out.push('');
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
out.push(line);
|
|
960
|
+
}
|
|
961
|
+
return out;
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function splitCallsList(raw) {
|
|
965
|
+
const items = [];
|
|
966
|
+
let current = '', parenDepth = 0, bracketDepth = 0, inTick = false;
|
|
967
|
+
for (let i = 0; i < raw.length; i++) {
|
|
968
|
+
const ch = raw[i];
|
|
969
|
+
if (ch === '`') { inTick = !inTick; current += ch; continue; }
|
|
970
|
+
if (!inTick) {
|
|
971
|
+
if (ch === '(') parenDepth++;
|
|
972
|
+
else if (ch === ')' && parenDepth > 0) parenDepth--;
|
|
973
|
+
else if (ch === '[') bracketDepth++;
|
|
974
|
+
else if (ch === ']' && bracketDepth > 0) bracketDepth--;
|
|
975
|
+
else if ((ch === ',' || ch === ';') && parenDepth === 0 && bracketDepth === 0) {
|
|
976
|
+
if (current.trim()) items.push(current.trim());
|
|
977
|
+
current = '';
|
|
978
|
+
continue;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
current += ch;
|
|
982
|
+
}
|
|
983
|
+
if (current.trim()) items.push(current.trim());
|
|
984
|
+
return items;
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
function parseSingleCallToken(rawItem) {
|
|
988
|
+
let item = String(rawItem ?? '').trim();
|
|
989
|
+
if (!item) return null;
|
|
990
|
+
if (/^(?:none\.?|n\/a\.?|\(none\)|—|-)$/i.test(item)) return null;
|
|
991
|
+
const trailingPeriod = item.endsWith('.') && !item.endsWith('..');
|
|
992
|
+
const candidate = trailingPeriod ? item.slice(0, -1).trim() : item;
|
|
993
|
+
if (!candidate || /^(?:none|n\/a|\(none\)|—|-)$/i.test(candidate)) return null;
|
|
994
|
+
const unwrapped = /^`([^`]+)`$/.exec(candidate)?.[1] ?? null;
|
|
995
|
+
const token = unwrapped ?? candidate;
|
|
996
|
+
const strict = /^([A-Za-z_][A-Za-z0-9_/-]*)\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(token);
|
|
997
|
+
if (strict && !candidate.includes('(') && !candidate.includes(')') && (unwrapped !== null || !candidate.includes('`'))) {
|
|
998
|
+
return { valid: true, raw: item, module: strict[1], operation: strict[2], full: `${strict[1]}.${strict[2]}` };
|
|
999
|
+
}
|
|
1000
|
+
const hasParen = /[()]/.test(candidate);
|
|
1001
|
+
const reason = hasParen
|
|
1002
|
+
? `Calls entry ${show(item)} contains parenthetical prose or malformed syntax; write strictly <module>.<op> without inline annotations.`
|
|
1003
|
+
: `Calls entry ${show(item)} is malformed; write strictly <module>.<op>.`;
|
|
1004
|
+
return { valid: false, raw: item, reason };
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
export function parsePlainMarkdownCalls(text) {
|
|
1008
|
+
const lines = stripFencesAndComments(text);
|
|
1009
|
+
const entries = [];
|
|
1010
|
+
let sectionKind = null; // 'ops' | 'calls' | null
|
|
1011
|
+
let sectionLevel = 0;
|
|
1012
|
+
let inCallsListIndent = null;
|
|
1013
|
+
|
|
1014
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1015
|
+
const line = lines[i];
|
|
1016
|
+
const heading = /^(#{1,6})[ \t]+(.+?)[ \t]*#*$/.exec(line);
|
|
1017
|
+
if (heading) {
|
|
1018
|
+
const level = heading[1].length;
|
|
1019
|
+
const title = heading[2].trim().toLowerCase();
|
|
1020
|
+
inCallsListIndent = null;
|
|
1021
|
+
if (/^calls$/.test(title)) {
|
|
1022
|
+
sectionKind = 'calls';
|
|
1023
|
+
sectionLevel = level;
|
|
1024
|
+
} else if (level === 2 && /^(?:public\s+)?(?:operations(?:\s+(?:and|&)\s+ports)?|ports)$/.test(title)) {
|
|
1025
|
+
sectionKind = 'ops';
|
|
1026
|
+
sectionLevel = level;
|
|
1027
|
+
} else if (sectionKind && level <= sectionLevel) {
|
|
1028
|
+
sectionKind = null;
|
|
1029
|
+
sectionLevel = 0;
|
|
1030
|
+
}
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
if (sectionKind === 'calls') {
|
|
1035
|
+
const trimmed = line.trim();
|
|
1036
|
+
if (!trimmed) continue;
|
|
1037
|
+
const bullet = /^[ \t]*[-*+][ \t]+(.+)$/.exec(line);
|
|
1038
|
+
if (bullet) {
|
|
1039
|
+
for (const piece of splitCallsList(bullet[1])) {
|
|
1040
|
+
const parsed = parseSingleCallToken(piece);
|
|
1041
|
+
if (parsed) entries.push({ ...parsed, line: i + 1 });
|
|
1042
|
+
}
|
|
1043
|
+
} else if (!/^(?:none\.?|n\/a\.?|\(none\)|—|-)$/i.test(trimmed)) {
|
|
1044
|
+
for (const piece of splitCallsList(trimmed)) {
|
|
1045
|
+
const parsed = parseSingleCallToken(piece);
|
|
1046
|
+
if (parsed) entries.push({ ...parsed, line: i + 1 });
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (sectionKind === 'ops') {
|
|
1053
|
+
if (inCallsListIndent !== null) {
|
|
1054
|
+
const trimmed = line.trim();
|
|
1055
|
+
if (!trimmed) { inCallsListIndent = null; continue; }
|
|
1056
|
+
const indent = /^([ \t]*)/.exec(line)[1].length;
|
|
1057
|
+
const subBullet = /^[ \t]*[-*+][ \t]+(.+)$/.exec(line);
|
|
1058
|
+
if (subBullet && indent > inCallsListIndent) {
|
|
1059
|
+
for (const piece of splitCallsList(subBullet[1])) {
|
|
1060
|
+
const parsed = parseSingleCallToken(piece);
|
|
1061
|
+
if (parsed) entries.push({ ...parsed, line: i + 1 });
|
|
1062
|
+
}
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
inCallsListIndent = null;
|
|
1066
|
+
}
|
|
1067
|
+
const callsLine = /^([ \t]*)(?:[-*+][ \t]+)?(?:\*\*calls:\*\*|\*\*calls\*\*[ \t]*:|calls[ \t]*:)[ \t]*(.*)$/i.exec(line);
|
|
1068
|
+
if (callsLine) {
|
|
1069
|
+
const rest = callsLine[2].trim();
|
|
1070
|
+
if (rest) {
|
|
1071
|
+
for (const piece of splitCallsList(rest)) {
|
|
1072
|
+
const parsed = parseSingleCallToken(piece);
|
|
1073
|
+
if (parsed) entries.push({ ...parsed, line: i + 1 });
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
inCallsListIndent = callsLine[1].length;
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
return entries;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
function parsePlainMarkdownPorts(text) {
|
|
1084
|
+
const lines = stripFencesAndComments(text);
|
|
1085
|
+
const ports = new Set();
|
|
1086
|
+
const addTokens = raw => {
|
|
1087
|
+
for (const piece of splitCallsList(raw)) {
|
|
1088
|
+
const cleaned = piece.replace(/^`([^`]+)`$/, '$1').replace(/\.$/, '').trim();
|
|
1089
|
+
const match = /^([A-Za-z_][A-Za-z0-9_-]*)(?:\.([A-Za-z_][A-Za-z0-9_-]*))?/.exec(cleaned);
|
|
1090
|
+
if (match) {
|
|
1091
|
+
ports.add(match[1]);
|
|
1092
|
+
if (match[2]) ports.add(`${match[1]}.${match[2]}`);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
let inPortsSection = false, inPortsListIndent = null;
|
|
1097
|
+
for (const line of lines) {
|
|
1098
|
+
const heading = /^(#{1,6})[ \t]+(.+?)[ \t]*#*$/.exec(line);
|
|
1099
|
+
if (heading) {
|
|
1100
|
+
inPortsSection = /^(?:ports|resources|external\s+ports)$/i.test(heading[2].trim());
|
|
1101
|
+
inPortsListIndent = null;
|
|
1102
|
+
continue;
|
|
1103
|
+
}
|
|
1104
|
+
if (inPortsSection) {
|
|
1105
|
+
const bullet = /^[ \t]*[-*+][ \t]+(.+)$/.exec(line);
|
|
1106
|
+
if (bullet) addTokens(bullet[1]);
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
if (inPortsListIndent !== null) {
|
|
1110
|
+
const indent = /^([ \t]*)/.exec(line)[1].length;
|
|
1111
|
+
const sub = /^[ \t]*[-*+][ \t]+(.+)$/.exec(line);
|
|
1112
|
+
if (sub && indent > inPortsListIndent) { addTokens(sub[1]); continue; }
|
|
1113
|
+
inPortsListIndent = null;
|
|
1114
|
+
}
|
|
1115
|
+
const portsLine = /^([ \t]*)(?:[-*+][ \t]+)?(?:\*\*(?:ports|resources):\*\*|\*\*(?:ports|resources)\*\*[ \t]*:|(?:ports|resources)[ \t]*:)[ \t]*(.*)$/i.exec(line);
|
|
1116
|
+
if (portsLine) {
|
|
1117
|
+
if (portsLine[2].trim()) addTokens(portsLine[2]);
|
|
1118
|
+
inPortsListIndent = portsLine[1].length;
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
return ports;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
export function parsePlainMarkdownOperations(promptOrText) {
|
|
1125
|
+
if (isObject(promptOrText) && Array.isArray(promptOrText.interface?.entries) && promptOrText.interface.entries.length) {
|
|
1126
|
+
return new Set(promptOrText.interface.entries.map(e => e?.operation).filter(op => typeof op === 'string' && op));
|
|
1127
|
+
}
|
|
1128
|
+
const text = typeof promptOrText === 'string' ? promptOrText : String(promptOrText?.text ?? '');
|
|
1129
|
+
const lines = stripFencesAndComments(text);
|
|
1130
|
+
const ops = new Set();
|
|
1131
|
+
let inOpsSection = false;
|
|
1132
|
+
for (const line of lines) {
|
|
1133
|
+
const heading = /^(#{2,4})[ \t]+(.+?)[ \t]*#*$/.exec(line);
|
|
1134
|
+
if (heading) {
|
|
1135
|
+
const level = heading[1].length;
|
|
1136
|
+
const rawTitle = heading[2].trim();
|
|
1137
|
+
if (level === 2) {
|
|
1138
|
+
inOpsSection = /^(?:public\s+)?operations(?:\s+(?:and|&)\s+ports)?$/i.test(rawTitle);
|
|
1139
|
+
}
|
|
1140
|
+
const opHeading = /^`?([A-Za-z_][A-Za-z0-9_-]*)`?(?:[ \t]*\([^)]*\))?$/.exec(rawTitle);
|
|
1141
|
+
if (opHeading && !GENERIC_SECTION_HEADINGS.has(opHeading[1].toLowerCase())) {
|
|
1142
|
+
ops.add(opHeading[1]);
|
|
1143
|
+
}
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
for (const match of line.matchAll(/\b(?:export|operation)[ \t]+`?([A-Za-z_$][\w$]*)`?/gi)) {
|
|
1147
|
+
ops.add(match[1]);
|
|
1148
|
+
}
|
|
1149
|
+
if (inOpsSection) {
|
|
1150
|
+
if (/^[ \t]*(?:[-*+][ \t]+)?(?:\*\*(?:calls|ports|resources):?\*\*|(?:calls|ports|resources)[ \t]*:)/i.test(line)) continue;
|
|
1151
|
+
const sigBullet = /^[ \t]*[-*+][ \t]+`?([A-Za-z_][A-Za-z0-9_-]*)`?[ \t]*\(/.exec(line);
|
|
1152
|
+
if (sigBullet && !GENERIC_SECTION_HEADINGS.has(sigBullet[1].toLowerCase())) {
|
|
1153
|
+
ops.add(sigBullet[1]);
|
|
1154
|
+
continue;
|
|
1155
|
+
}
|
|
1156
|
+
const codeBullet = /^[ \t]*[-*+][ \t]+`([A-Za-z_][A-Za-z0-9_-]*)`(?:[ \t]*(?:—|--|-|:|->|=>|\())/.exec(line);
|
|
1157
|
+
if (codeBullet && !GENERIC_SECTION_HEADINGS.has(codeBullet[1].toLowerCase())) {
|
|
1158
|
+
ops.add(codeBullet[1]);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
return ops;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
function resolvePlainMarkdownCallTarget(moduleName, callerPath, callerText, visible) {
|
|
1166
|
+
const cleaned = String(moduleName ?? '').trim().replaceAll('\\', '/');
|
|
1167
|
+
if (!cleaned || cleaned.startsWith('/') || cleaned.split('/').includes('..')) return null;
|
|
1168
|
+
const callerDir = posix.dirname(callerPath);
|
|
1169
|
+
const candidates = [cleaned];
|
|
1170
|
+
if (!cleaned.endsWith('.prompt.md')) candidates.push(`${cleaned}.prompt.md`);
|
|
1171
|
+
if (callerDir && callerDir !== '.') {
|
|
1172
|
+
candidates.push(`${callerDir}/${cleaned}`);
|
|
1173
|
+
if (!cleaned.endsWith('.prompt.md')) candidates.push(`${callerDir}/${cleaned}.prompt.md`);
|
|
1174
|
+
}
|
|
1175
|
+
candidates.push(`prompts/${cleaned}`);
|
|
1176
|
+
if (!cleaned.endsWith('.prompt.md')) candidates.push(`prompts/${cleaned}.prompt.md`);
|
|
1177
|
+
for (const cand of candidates) {
|
|
1178
|
+
if (visible.has(cand)) return cand;
|
|
1179
|
+
}
|
|
1180
|
+
const linked = promptMarkdownTargets(callerText, callerPath, visible);
|
|
1181
|
+
for (const target of linked) {
|
|
1182
|
+
const stem = posix.basename(target, '.prompt.md');
|
|
1183
|
+
if (stem === cleaned || target === cleaned) return target;
|
|
1184
|
+
}
|
|
1185
|
+
const targetStem = posix.basename(cleaned, '.prompt.md');
|
|
1186
|
+
const sortedPrompts = [...visible].filter(p => p.endsWith('.prompt.md')).sort();
|
|
1187
|
+
for (const p of sortedPrompts) {
|
|
1188
|
+
if (posix.basename(p, '.prompt.md') === targetStem) return p;
|
|
1189
|
+
}
|
|
1190
|
+
return null;
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
export function plainMarkdownCallsProblems(root, visible, prompt, prompts = new Map(), workspace = loadRuntimeWorkspace({ root }), { simPorts = null } = {}) {
|
|
1194
|
+
if (!prompt || typeof prompt.text !== 'string' || prompt.interface?.kind === 'native-only' || prompt.frontmatter) return [];
|
|
1195
|
+
const calls = parsePlainMarkdownCalls(prompt.text);
|
|
1196
|
+
if (!calls.length) return [];
|
|
1197
|
+
const declaredResources = new Set();
|
|
1198
|
+
for (const res of Array.isArray(prompt.interface?.resources) ? prompt.interface.resources : []) {
|
|
1199
|
+
if (typeof res?.name === 'string' && res.name) {
|
|
1200
|
+
declaredResources.add(res.name);
|
|
1201
|
+
for (const op of Array.isArray(res.operations) ? res.operations : []) {
|
|
1202
|
+
if (typeof op?.name === 'string' && op.name) declaredResources.add(`${res.name}.${op.name}`);
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
const prosePorts = parsePlainMarkdownPorts(prompt.text);
|
|
1207
|
+
const problems = [];
|
|
1208
|
+
for (const entry of calls) {
|
|
1209
|
+
if (!entry.valid) {
|
|
1210
|
+
problems.push(refusal('invalid-calls-syntax', 'Operations and ports.Calls',
|
|
1211
|
+
`${prompt.path} Operations and ports.Calls: ${entry.reason}`,
|
|
1212
|
+
{ path: prompt.path, hint: 'Write each Calls entry strictly as <module>.<op> with no trailing parenthetical prose.' }));
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
const { module: mod, operation: op, full } = entry;
|
|
1216
|
+
if (BUILTIN_STDLIB_PORTS.has(full) || full.startsWith('compute.') || DEFAULT_STATE_PORTS.has(full)
|
|
1217
|
+
|| declaredResources.has(full) || declaredResources.has(mod)
|
|
1218
|
+
|| prosePorts.has(full) || prosePorts.has(mod)
|
|
1219
|
+
|| (simPorts && (simPorts.has(full) || simPorts.has(mod)))) {
|
|
1220
|
+
continue;
|
|
1221
|
+
}
|
|
1222
|
+
const targetPath = resolvePlainMarkdownCallTarget(mod, prompt.path, prompt.text, visible);
|
|
1223
|
+
if (!targetPath) {
|
|
1224
|
+
problems.push(refusal('unknown-target', 'Operations and ports.Calls',
|
|
1225
|
+
`${prompt.path} Operations and ports.Calls: Unknown target ${show(full)} — no prompt file matches module ${show(mod)}.`,
|
|
1226
|
+
{ path: prompt.path, hint: `Link or add a matching <module>.prompt.md file, or fix the Calls target ${show(full)}.` }));
|
|
1227
|
+
continue;
|
|
1228
|
+
}
|
|
1229
|
+
let targetPrompt = prompts.get(targetPath);
|
|
1230
|
+
if (!targetPrompt) {
|
|
1231
|
+
try { targetPrompt = readPrompt(root, visible, targetPath, workspace); prompts.set(targetPath, targetPrompt); }
|
|
1232
|
+
catch { targetPrompt = null; }
|
|
1233
|
+
}
|
|
1234
|
+
if (targetPrompt && typeof targetPrompt.text === 'string') {
|
|
1235
|
+
const targetOps = parsePlainMarkdownOperations(targetPrompt);
|
|
1236
|
+
if (targetOps.size > 0 && !targetOps.has(op)) {
|
|
1237
|
+
problems.push(refusal('unknown-target-operation', 'Operations and ports.Calls',
|
|
1238
|
+
`${prompt.path} Operations and ports.Calls: Unknown target operation ${show(full)} — ${targetPath} declares ${[...targetOps].sort().join(', ')}.`,
|
|
1239
|
+
{ path: prompt.path, hint: `Call one of the operations declared in ${targetPath} (${[...targetOps].sort().join(', ')}), or add ${show(op)} to ${targetPath}.` }));
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
return problems;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
915
1246
|
export function interfaceFindings({ root, paths = discoveryPromptPaths(root) }) {
|
|
916
1247
|
const visible = new Set(gitFiles(root));
|
|
917
1248
|
const appMapScreens = readAppMapScreens(root, visible);
|
|
1249
|
+
const prompts = new Map();
|
|
918
1250
|
return paths.flatMap(path => {
|
|
919
1251
|
try {
|
|
920
1252
|
const prompt = readPrompt(root, visible, path), problem = promptRefusal(prompt, 'interface');
|
|
921
|
-
|
|
1253
|
+
prompts.set(path, prompt);
|
|
1254
|
+
const callsProblems = plainMarkdownCallsProblems(root, visible, prompt, prompts).map(item => ({
|
|
1255
|
+
code: item.code,
|
|
1256
|
+
path: item.path ?? path,
|
|
1257
|
+
section: item.section ?? 'Operations and ports.Calls',
|
|
1258
|
+
message: item.hint ? `${item.message} ${item.hint}` : item.message,
|
|
1259
|
+
}));
|
|
1260
|
+
if (!prompt.interface) return [...(problem ? [{ ...problem, path }] : []), ...callsProblems];
|
|
922
1261
|
const schema = interfaceSchemaProblems(prompt.interface).map(item => ({ code: item.code, path, section: item.pointer, message: `${path} ${item.pointer} ${item.rule}` }));
|
|
923
1262
|
const selectorDupes = analyzePromptSelectorWords(prompt, { appMapScreens }).duplicates.map(({ word, labels }) => ({
|
|
924
1263
|
code: 'duplicate-selector-word',
|
|
@@ -926,7 +1265,7 @@ export function interfaceFindings({ root, paths = discoveryPromptPaths(root) })
|
|
|
926
1265
|
section: '/entries',
|
|
927
1266
|
message: `${path} /entries duplicate-selector-word: Selector word ${JSON.stringify(word)} is used by multiple kinds or operations (${labels.join(' and ')}). Give each kind and operation its own selector word.`,
|
|
928
1267
|
}));
|
|
929
|
-
const all = [...schema, ...selectorDupes];
|
|
1268
|
+
const all = [...schema, ...selectorDupes, ...callsProblems];
|
|
930
1269
|
return problem && !all.some(item => item.code === problem.code) ? [{ ...problem, path }, ...all] : all;
|
|
931
1270
|
} catch (error) {
|
|
932
1271
|
return [{ code: error.code ?? 'interface-unreadable', path, message: error.message }];
|
|
@@ -936,10 +1275,12 @@ export function interfaceFindings({ root, paths = discoveryPromptPaths(root) })
|
|
|
936
1275
|
|
|
937
1276
|
export function runtimeCoverage({ root, paths = discoveryPromptPaths(root), allowMissingInterfaces = true }) {
|
|
938
1277
|
const visible = new Set(gitFiles(root));
|
|
1278
|
+
const workspace = boundedWorkspace(root, loadRuntimeWorkspace({ root }));
|
|
1279
|
+
const sharedPort = sourceFilePort(root, visible, workspace);
|
|
939
1280
|
let checkable = 0, native_only = 0;
|
|
940
1281
|
for (const path of paths) {
|
|
941
1282
|
try {
|
|
942
|
-
const prompt = readPrompt(root, visible, path);
|
|
1283
|
+
const prompt = readPrompt(root, visible, path, workspace, sharedPort);
|
|
943
1284
|
if (prompt.error === 'interface-missing') {
|
|
944
1285
|
if (allowMissingInterfaces && typeof prompt.text === 'string' && prompt.text.trim()) checkable++;
|
|
945
1286
|
continue;
|
|
@@ -1039,7 +1380,7 @@ export function numberWarnings(doc, { testPath, testSha, reviews = [] } = {}) {
|
|
|
1039
1380
|
if (reviews.some(row => validNumericReview(row) && row.test_path === testPath && row.test_sha256.toLowerCase() === testSha
|
|
1040
1381
|
&& row.step_id === step.step_id && row.criterion_id === check.criterion_id && row.target === check.target && row.path === check.path && row.value === value)) continue;
|
|
1041
1382
|
const location = `${testPath ?? 'test'} steps[${stepIndex}].checks[${checkIndex}] (${check.target} ${check.path})`;
|
|
1042
|
-
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 (
|
|
1383
|
+
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 (see the pdd skill reference stories.md, or run pdd help prompting).`);
|
|
1043
1384
|
}
|
|
1044
1385
|
}
|
|
1045
1386
|
return [...warnings];
|
|
@@ -1223,7 +1564,7 @@ export function promptMarkdownTargets(text, fromPath, visible) {
|
|
|
1223
1564
|
}
|
|
1224
1565
|
|
|
1225
1566
|
// The schema rules of a prompt and of the prompts it calls, all at once (cached per prompt).
|
|
1226
|
-
export function promptSchemaRefusals(root, found, prompt, prompts, seen = new Set(), { allowMissingInterfaces = false } = {}) {
|
|
1567
|
+
export function promptSchemaRefusals(root, found, prompt, prompts, seen = new Set(), { allowMissingInterfaces = false, simPorts = null } = {}) {
|
|
1227
1568
|
const visit = (current, contextOnly = false) => {
|
|
1228
1569
|
if (!current) return [];
|
|
1229
1570
|
const identity = contextOnly ? `context:${current.path}` : current.path;
|
|
@@ -1236,9 +1577,10 @@ export function promptSchemaRefusals(root, found, prompt, prompts, seen = new Se
|
|
|
1236
1577
|
if (current.error && !(current.error === 'interface-missing' && (contextOnly || allowMissingInterfaces))) {
|
|
1237
1578
|
return [{ ...promptRefusal(current, 'interface'), path: current.path }];
|
|
1238
1579
|
}
|
|
1580
|
+
const callsIssues = plainMarkdownCallsProblems(root, found.visible, current, prompts, found.workspace, { simPorts });
|
|
1239
1581
|
const contexts = promptMarkdownTargets(current.text, current.path, found.visible)
|
|
1240
1582
|
.flatMap(target => visit(load(target), true));
|
|
1241
|
-
if (!current.interface) return contexts;
|
|
1583
|
+
if (!current.interface) return [...callsIssues, ...contexts];
|
|
1242
1584
|
current.schemaIssues ??= interfaceSchemaProblems(current.interface).map(problem =>
|
|
1243
1585
|
refusal(problem.code, problem.pointer, `${current.path} ${problem.pointer} ${problem.rule}`, {path:current.path, ...(problem.hint ? {hint:problem.hint} : {})}));
|
|
1244
1586
|
const ownRefusal = current.frontmatter || !['draft', 'approved'].includes(current.interface.status)
|
|
@@ -1246,7 +1588,7 @@ export function promptSchemaRefusals(root, found, prompt, prompts, seen = new Se
|
|
|
1246
1588
|
const statusProblems = ownRefusal ? [{ ...ownRefusal, path: current.path }] : [];
|
|
1247
1589
|
const called = (Array.isArray(current.interface.calls) ? current.interface.calls : [])
|
|
1248
1590
|
.flatMap(call => typeof call?.target === 'string' ? visit(load(call.target), contextOnly) : []);
|
|
1249
|
-
return [...statusProblems, ...current.schemaIssues, ...called, ...contexts];
|
|
1591
|
+
return [...statusProblems, ...current.schemaIssues, ...callsIssues, ...called, ...contexts];
|
|
1250
1592
|
};
|
|
1251
1593
|
return visit(prompt);
|
|
1252
1594
|
}
|
|
@@ -1940,7 +2282,16 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false,
|
|
|
1940
2282
|
const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
|
|
1941
2283
|
const broken = lazyMissing ? null : promptRefusal(prompt, section);
|
|
1942
2284
|
if (broken) return done({ ...broken, ...at }, story);
|
|
1943
|
-
const
|
|
2285
|
+
const simPorts = new Set();
|
|
2286
|
+
for (const bag of [doc.simulation, step.simulation_overrides]) {
|
|
2287
|
+
if (!isObject(bag)) continue;
|
|
2288
|
+
for (const key of Object.keys(bag)) {
|
|
2289
|
+
simPorts.add(key);
|
|
2290
|
+
const dot = key.indexOf('.');
|
|
2291
|
+
if (dot > 0) simPorts.add(key.slice(0, dot));
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
const schemaIssues = promptSchemaRefusals(root, found, prompt, prompts, new Set(), { allowMissingInterfaces, simPorts })
|
|
1944
2295
|
.filter(problem => !localLint || !problem.code?.startsWith('graph-schema-'));
|
|
1945
2296
|
if (schemaIssues.length) return done(schemaIssues, story);
|
|
1946
2297
|
const entry = lazyMissing ? null : (Array.isArray(prompt.interface.entries) ? prompt.interface.entries : []).find(item => item?.operation === step.operation);
|
|
@@ -2084,9 +2435,41 @@ function summarizePromptClosure(doc, { prompts, visible, root, workspace, allowM
|
|
|
2084
2435
|
|
|
2085
2436
|
// Rules P1-P10 for the selected tests. Returns rows and warnings; never throws for a test problem.
|
|
2086
2437
|
export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false, localLint = false, stepIds = [] }) {
|
|
2087
|
-
|
|
2438
|
+
const policy = boundedWorkspace(root, workspace);
|
|
2439
|
+
found={...found,workspace:policy};for(const test of selected)requireRuntimePath(policy,{path:test.path,from:'Selected test'});
|
|
2088
2440
|
const warnings = [];
|
|
2089
2441
|
const reviews = numericReviews(root, found, warnings);
|
|
2442
|
+
const sharedPort = sourceFilePort(root, found.visible, policy);
|
|
2443
|
+
const sharedPromptCache = new Map();
|
|
2444
|
+
const sharedMarkdownTargets = new Map();
|
|
2445
|
+
const sharedStoryCriteria = new Map();
|
|
2446
|
+
const loadPrompt = path => {
|
|
2447
|
+
if (sharedPromptCache.has(path)) {
|
|
2448
|
+
const cached = sharedPromptCache.get(path);
|
|
2449
|
+
if (cached.errorObj) throw cached.errorObj;
|
|
2450
|
+
return cached.value;
|
|
2451
|
+
}
|
|
2452
|
+
try {
|
|
2453
|
+
const value = readPrompt(root, found.visible, path, policy, sharedPort);
|
|
2454
|
+
sharedPromptCache.set(path, { value });
|
|
2455
|
+
return value;
|
|
2456
|
+
} catch (errorObj) {
|
|
2457
|
+
sharedPromptCache.set(path, { errorObj });
|
|
2458
|
+
throw errorObj;
|
|
2459
|
+
}
|
|
2460
|
+
};
|
|
2461
|
+
const targetsForPrompt = (prompt, path) => {
|
|
2462
|
+
if (!sharedMarkdownTargets.has(path)) {
|
|
2463
|
+
sharedMarkdownTargets.set(path, promptMarkdownTargets(prompt.text, path, found.visible));
|
|
2464
|
+
}
|
|
2465
|
+
return sharedMarkdownTargets.get(path);
|
|
2466
|
+
};
|
|
2467
|
+
const criteriaForStory = storyPath => {
|
|
2468
|
+
if (!sharedStoryCriteria.has(storyPath)) {
|
|
2469
|
+
sharedStoryCriteria.set(storyPath, storyCriteria(sharedPort.read({ path: storyPath }).content));
|
|
2470
|
+
}
|
|
2471
|
+
return sharedStoryCriteria.get(storyPath);
|
|
2472
|
+
};
|
|
2090
2473
|
const rows = selected.map(test => {
|
|
2091
2474
|
const prompts = new Map(), executablePaths = new Set(), visited = new Set();
|
|
2092
2475
|
// Discover identity independently of validation: an early criterion error or
|
|
@@ -2097,10 +2480,10 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
|
|
|
2097
2480
|
if (visited.has(identity)) return;
|
|
2098
2481
|
visited.add(identity);
|
|
2099
2482
|
if (executable) executablePaths.add(path);
|
|
2100
|
-
if (!prompts.has(path)) prompts.set(path,
|
|
2483
|
+
if (!prompts.has(path)) prompts.set(path, loadPrompt(path));
|
|
2101
2484
|
const prompt = prompts.get(path);
|
|
2102
2485
|
for (const call of Array.isArray(prompt.interface?.calls) ? prompt.interface.calls : []) visit(call?.target, executable);
|
|
2103
|
-
for (const target of
|
|
2486
|
+
for (const target of targetsForPrompt(prompt, path)) visit(target, false);
|
|
2104
2487
|
};
|
|
2105
2488
|
let refused, plan, testSha = null, effectiveDoc = test.doc;
|
|
2106
2489
|
try {
|
|
@@ -2113,7 +2496,7 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
|
|
|
2113
2496
|
.map(prompt => promptRefusal(prompt,'interface')).filter(Boolean);
|
|
2114
2497
|
if (nativeProblems.length) refused = [...(refused ? [refused].flat() : []),...nativeProblems];
|
|
2115
2498
|
if (!refused || refused.code === 'unchecked-criteria') {
|
|
2116
|
-
plan = criterionPlan(effectiveDoc, checked.story ??
|
|
2499
|
+
plan = criterionPlan(effectiveDoc, checked.story ?? criteriaForStory(effectiveDoc.story_path));
|
|
2117
2500
|
}
|
|
2118
2501
|
if (!refused && reviews.length) testSha = sha256(readFileSync(join(root,test.path)));
|
|
2119
2502
|
} catch (error) {
|
|
@@ -2121,7 +2504,7 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
|
|
|
2121
2504
|
refused = refusal(error.code ?? 'source-unavailable', 'source', error.message,
|
|
2122
2505
|
{hint:'Restore the named dependency, make it readable, or correct its declared path.'});
|
|
2123
2506
|
}
|
|
2124
|
-
const closure = summarizePromptClosure(effectiveDoc, { prompts, visible: found.visible, root, workspace, allowMissingInterfaces });
|
|
2507
|
+
const closure = summarizePromptClosure(effectiveDoc, { prompts, visible: found.visible, root, workspace: policy, allowMissingInterfaces });
|
|
2125
2508
|
const row = { test: test.path, story: test.story, title: test.title, refusals: refused ? [refused].flat() : [], warnings: numberWarnings(effectiveDoc, { testPath: test.path, testSha, reviews }),
|
|
2126
2509
|
...(stepIds.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:(effectiveDoc?.steps ?? []).filter(step=>stepIds.includes(step?.step_id)).map(step=>step.step_id)} : {}),
|
|
2127
2510
|
max_calls: defaultMaxCalls(effectiveDoc, closure), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
|
|
@@ -2156,6 +2539,23 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
|
|
|
2156
2539
|
}
|
|
2157
2540
|
const storyWarning = storyComplexityWarningLine({ path: test.path, storyPath: test.storyPath, doc: test.doc }, rawTestText);
|
|
2158
2541
|
if (storyWarning && !warnings.includes(storyWarning)) warnings.push(storyWarning);
|
|
2542
|
+
if (!row.native_only.length && !row.refusals.some(item => item.section === 'source')) {
|
|
2543
|
+
const port = sourceFilePort(root, found.visible, workspace);
|
|
2544
|
+
const readClosureText = filePath => {
|
|
2545
|
+
if (prompts.has(filePath)) {
|
|
2546
|
+
const cached = prompts.get(filePath);
|
|
2547
|
+
if (typeof cached?.rawText === 'string') return cached.rawText;
|
|
2548
|
+
if (typeof cached?.text === 'string') return cached.text;
|
|
2549
|
+
}
|
|
2550
|
+
if (!found.visible.has(filePath)) return null;
|
|
2551
|
+
try { return port.read({ path: filePath }).content; } catch { return null; }
|
|
2552
|
+
};
|
|
2553
|
+
const closureWarning = storyClosureWarningLine(
|
|
2554
|
+
{ path: test.path, storyPath: test.storyPath, doc: effectiveDoc },
|
|
2555
|
+
{ readText: readClosureText, visible: found.visible },
|
|
2556
|
+
);
|
|
2557
|
+
if (closureWarning && !warnings.includes(closureWarning)) warnings.push(closureWarning);
|
|
2558
|
+
}
|
|
2159
2559
|
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.`);
|
|
2160
2560
|
return row;
|
|
2161
2561
|
});
|
|
@@ -2574,7 +2974,12 @@ function markdownSectionTitle(text) {
|
|
|
2574
2974
|
return parts.join('').replace(/\s+/g, ' ').trim();
|
|
2575
2975
|
}
|
|
2576
2976
|
|
|
2977
|
+
const MARKDOWN_CONTEXT_CACHE = new Map();
|
|
2978
|
+
const MARKDOWN_CONTEXT_CACHE_MAX = 1024;
|
|
2577
2979
|
function markdownContext(text) {
|
|
2980
|
+
if (typeof text !== 'string') return [];
|
|
2981
|
+
const cached = MARKDOWN_CONTEXT_CACHE.get(text);
|
|
2982
|
+
if (cached !== undefined) return cached;
|
|
2578
2983
|
const prose = text.replace(INTERFACE, ''), markdown = markdownSectionText(prose), definitions = markdownDefinitions(markdown);
|
|
2579
2984
|
const heading = /^##[ \t]+Dependencies[ \t]*\r?$/im.exec(markdown);
|
|
2580
2985
|
const rest = heading ? prose.slice(heading.index + heading[0].length) : '';
|
|
@@ -2604,9 +3009,142 @@ function markdownContext(text) {
|
|
|
2604
3009
|
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);
|
|
2605
3010
|
if (!externalOrCode && ((path.includes('/') && fileName) || commonFile || isSecretPath(path))) paths.push(path);
|
|
2606
3011
|
}
|
|
3012
|
+
if (MARKDOWN_CONTEXT_CACHE.size >= MARKDOWN_CONTEXT_CACHE_MAX) MARKDOWN_CONTEXT_CACHE.clear();
|
|
3013
|
+
MARKDOWN_CONTEXT_CACHE.set(text, paths);
|
|
2607
3014
|
return paths;
|
|
2608
3015
|
}
|
|
2609
3016
|
|
|
3017
|
+
const CONTRACT_ALIAS_LINK = /\[[^\]\n]*\]\(([^)\n]+)\)/g;
|
|
3018
|
+
const CONTRACT_ALIAS_BARE = /(?<![A-Za-z0-9_./:-])(contracts\/[A-Za-z0-9_./-]+\.md)#([A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9_-])?)/g;
|
|
3019
|
+
const CONTRACT_ALIAS_FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
3020
|
+
const PDD_INTERFACE_BLOCK = /<pdd-interface\b[^>]*>[\s\S]*?<\/pdd-interface\s*>/gi;
|
|
3021
|
+
const HTML_COMMENT_BLOCK = /<!--[\s\S]*?-->/g;
|
|
3022
|
+
|
|
3023
|
+
// Collect Git-visible contracts/**/*.md files referenced by named schema aliases
|
|
3024
|
+
// (contracts/<file>.md#TypeName or Markdown anchor links) outside fenced blocks.
|
|
3025
|
+
function contractAliasContext(text, from, visible) {
|
|
3026
|
+
if (typeof text !== 'string' || !text || !text.includes('#') || !text.includes('.md')) return [];
|
|
3027
|
+
const prose = text.replace(INTERFACE, '').replace(PDD_INTERFACE_BLOCK, '').replace(HTML_COMMENT_BLOCK, '');
|
|
3028
|
+
const found = [];
|
|
3029
|
+
const seen = new Set();
|
|
3030
|
+
const parentDir = posix.dirname(from);
|
|
3031
|
+
const record = target => {
|
|
3032
|
+
if (!target || !target.startsWith('contracts/') || !target.endsWith('.md') || target.endsWith('.prompt.md')) return;
|
|
3033
|
+
if (target.startsWith('../') || target.split('/').includes('..')) return;
|
|
3034
|
+
if (!visible.has(target) || seen.has(target)) return;
|
|
3035
|
+
seen.add(target);
|
|
3036
|
+
found.push(target);
|
|
3037
|
+
};
|
|
3038
|
+
let fence = null;
|
|
3039
|
+
for (const line of prose.split(/\r?\n/)) {
|
|
3040
|
+
const marker = CONTRACT_ALIAS_FENCE.exec(line);
|
|
3041
|
+
if (fence) {
|
|
3042
|
+
if (marker && marker[1][0] === fence.char && marker[1].length >= fence.length && !marker[2].trim()) fence = null;
|
|
3043
|
+
continue;
|
|
3044
|
+
}
|
|
3045
|
+
if (marker) { fence = { char: marker[1][0], length: marker[1].length }; continue; }
|
|
3046
|
+
if (!line.includes('#') || !line.includes('.md')) continue;
|
|
3047
|
+
for (const match of line.matchAll(CONTRACT_ALIAS_LINK)) {
|
|
3048
|
+
const token = match[1].trim().split(/\s+/)[0] ?? '';
|
|
3049
|
+
const hash = token.indexOf('#');
|
|
3050
|
+
if (hash <= 0 || hash === token.length - 1) continue;
|
|
3051
|
+
const rawPath = token.slice(0, hash);
|
|
3052
|
+
if (rawPath.startsWith('/') || rawPath.includes('\\') || rawPath.includes('://')) continue;
|
|
3053
|
+
const relNorm = posix.normalize(posix.join(parentDir, rawPath));
|
|
3054
|
+
if (relNorm.startsWith('contracts/')) record(relNorm);
|
|
3055
|
+
else record(posix.normalize(rawPath));
|
|
3056
|
+
}
|
|
3057
|
+
for (const match of line.matchAll(CONTRACT_ALIAS_BARE)) {
|
|
3058
|
+
record(posix.normalize(match[1]));
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
return found;
|
|
3062
|
+
}
|
|
3063
|
+
|
|
3064
|
+
function markdownSectionSlice(prose, masked, headingPattern) {
|
|
3065
|
+
const heading = headingPattern.exec(masked);
|
|
3066
|
+
if (!heading) return null;
|
|
3067
|
+
const rest = prose.slice(heading.index + heading[0].length);
|
|
3068
|
+
const maskedRest = masked.slice(heading.index + heading[0].length);
|
|
3069
|
+
const end = /^#{1,2}[ \t]+/m.exec(maskedRest);
|
|
3070
|
+
return {
|
|
3071
|
+
raw: end ? rest.slice(0, end.index) : rest,
|
|
3072
|
+
masked: end ? maskedRest.slice(0, end.index) : maskedRest,
|
|
3073
|
+
};
|
|
3074
|
+
}
|
|
3075
|
+
|
|
3076
|
+
function extractSectionPromptCalls(rawSection, maskedSection, definitions, fromPath, visible) {
|
|
3077
|
+
const calls = [], seen = new Set();
|
|
3078
|
+
const promptStem = target => {
|
|
3079
|
+
const base = target.slice(target.lastIndexOf('/') + 1);
|
|
3080
|
+
return base.endsWith('.prompt.md') ? base.slice(0, -'.prompt.md'.length) : base;
|
|
3081
|
+
};
|
|
3082
|
+
const record = (rawTarget, lineText = '') => {
|
|
3083
|
+
let target;
|
|
3084
|
+
try { target = contextPath(rawTarget, fromPath, visible); } catch { return; }
|
|
3085
|
+
if (!target || !target.endsWith('.prompt.md')) return;
|
|
3086
|
+
const opMatch = /\boperation\s+`([A-Za-z0-9_.-]+)`/i.exec(lineText);
|
|
3087
|
+
const targetOperation = opMatch ? opMatch[1] : null;
|
|
3088
|
+
const key = `${target}\0${targetOperation ?? ''}`;
|
|
3089
|
+
if (seen.has(key)) return;
|
|
3090
|
+
seen.add(key);
|
|
3091
|
+
calls.push({
|
|
3092
|
+
operation: promptStem(target),
|
|
3093
|
+
target,
|
|
3094
|
+
...(targetOperation ? { target_operation: targetOperation } : {}),
|
|
3095
|
+
});
|
|
3096
|
+
};
|
|
3097
|
+
const rawLines = rawSection.split(/\r?\n/);
|
|
3098
|
+
const maskedLines = maskedSection.split(/\r?\n/);
|
|
3099
|
+
for (let i = 0; i < maskedLines.length; i++) {
|
|
3100
|
+
const lineRaw = rawLines[i] ?? '';
|
|
3101
|
+
const lineMasked = maskedLines[i] ?? '';
|
|
3102
|
+
for (const rawTarget of markdownLinks(lineMasked, definitions)) record(rawTarget, lineRaw);
|
|
3103
|
+
const shorthand = /^ {0,3}(?:[-+*]|[0-9]+[.)])[ \t]+`([^`\n]+)`(?=[ \t:]|$)/.exec(lineRaw);
|
|
3104
|
+
if (shorthand) {
|
|
3105
|
+
const prefix = shorthand[0].slice(0, shorthand[0].indexOf('`'));
|
|
3106
|
+
if (lineMasked.startsWith(prefix)) record(shorthand[1], lineRaw);
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
// Catch any multi-line markdown links that span line breaks.
|
|
3110
|
+
for (const rawTarget of markdownLinks(maskedSection, definitions)) {
|
|
3111
|
+
let target;
|
|
3112
|
+
try { target = contextPath(rawTarget, fromPath, visible); } catch { continue; }
|
|
3113
|
+
if (!target || !target.endsWith('.prompt.md')) continue;
|
|
3114
|
+
if (!calls.some(item => item.target === target)) record(rawTarget, '');
|
|
3115
|
+
}
|
|
3116
|
+
return calls;
|
|
3117
|
+
}
|
|
3118
|
+
|
|
3119
|
+
function plainProseCalls(promptText, fromPath, visible) {
|
|
3120
|
+
if (typeof promptText !== 'string') return [];
|
|
3121
|
+
const prose = promptText.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '').replace(INTERFACE, '');
|
|
3122
|
+
const masked = markdownSectionText(prose);
|
|
3123
|
+
const definitions = markdownDefinitions(masked);
|
|
3124
|
+
const callsSection = markdownSectionSlice(prose, masked, /^##[ \t]+Calls[ \t]*\r?$/im);
|
|
3125
|
+
if (callsSection) {
|
|
3126
|
+
const explicit = extractSectionPromptCalls(callsSection.raw, callsSection.masked, definitions, fromPath, visible);
|
|
3127
|
+
if (explicit.length) return explicit;
|
|
3128
|
+
const stripped = callsSection.raw.replace(/^[\s\-*+.]+|[\s.]+$/g, '').toLowerCase();
|
|
3129
|
+
if (stripped === 'none' || stripped === 'no calls') return [];
|
|
3130
|
+
}
|
|
3131
|
+
const depsSection = markdownSectionSlice(prose, masked, /^##[ \t]+Dependencies[ \t]*\r?$/im);
|
|
3132
|
+
if (depsSection) {
|
|
3133
|
+
let rawDeps = depsSection.raw, maskedDeps = depsSection.masked;
|
|
3134
|
+
for (const match of maskedDeps.matchAll(/^ {0,3}<details\b[^>]*>\s*<summary\b[^>]*>([\s\S]*?)<\/summary\s*>/gim)) {
|
|
3135
|
+
const title = markdownSectionTitle(match[1]);
|
|
3136
|
+
if (title !== null && /^(?:(?:required )?(?:module )?rules|(?:required )?interface reference|decision path)(?:\s*:|$)/i.test(title)) {
|
|
3137
|
+
rawDeps = rawDeps.slice(0, match.index);
|
|
3138
|
+
maskedDeps = maskedDeps.slice(0, match.index);
|
|
3139
|
+
break;
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
return extractSectionPromptCalls(rawDeps, maskedDeps, definitions, fromPath, visible)
|
|
3143
|
+
.map(call => ({ ...call, from_dependencies: true }));
|
|
3144
|
+
}
|
|
3145
|
+
return [];
|
|
3146
|
+
}
|
|
3147
|
+
|
|
2610
3148
|
function sourceLimit(files) {
|
|
2611
3149
|
const total = files.reduce((sum, file) => sum + file.size, 0);
|
|
2612
3150
|
if (files.length > LIMITS.files || total > LIMITS.bytes) {
|
|
@@ -2785,25 +3323,54 @@ function filePort(root, visible, strict = false,workspace) {
|
|
|
2785
3323
|
};
|
|
2786
3324
|
}
|
|
2787
3325
|
|
|
2788
|
-
function preparedText(root, visible, path, text, format,workspace) {
|
|
2789
|
-
try { return expandSource({path,text,format},sourceFilePort(root,visible,workspace)); }
|
|
3326
|
+
function preparedText(root, visible, path, text, format,workspace, sharedPort = null) {
|
|
3327
|
+
try { return expandSource({path,text,format},sharedPort ?? sourceFilePort(root,visible,workspace)); }
|
|
2790
3328
|
catch (error) {
|
|
2791
3329
|
if (error.code) throw new PreflightError(4, `${error.code}: ${error.message}`);
|
|
2792
3330
|
throw error;
|
|
2793
3331
|
}
|
|
2794
3332
|
}
|
|
2795
3333
|
|
|
3334
|
+
function addPathPrefixTracking(ancestors, path) {
|
|
3335
|
+
for (let slash = path.indexOf('/'); slash >= 0; slash = path.indexOf('/', slash + 1)) {
|
|
3336
|
+
ancestors.add(path.slice(0, slash));
|
|
3337
|
+
}
|
|
3338
|
+
}
|
|
3339
|
+
function hasPathPrefixConflict(existingMap, ancestors, path) {
|
|
3340
|
+
if (ancestors.has(path)) return true;
|
|
3341
|
+
for (let slash = path.indexOf('/'); slash >= 0; slash = path.indexOf('/', slash + 1)) {
|
|
3342
|
+
if (existingMap.has(path.slice(0, slash))) return true;
|
|
3343
|
+
}
|
|
3344
|
+
return false;
|
|
3345
|
+
}
|
|
3346
|
+
|
|
2796
3347
|
function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=true,workspace=loadRuntimeWorkspace({root}),excludeFixtureProjects=tests === undefined,validateCriteria=true,allowMissingInterfaces=true,stepIds=[] }, strict = false, ports = {}) {
|
|
2797
3348
|
const { isStoryPath, matchTests } = requireSelectionPorts(ports);
|
|
2798
3349
|
const headBefore = gitHead(root);
|
|
2799
3350
|
const policyBefore=JSON.stringify(loadRuntimeWorkspace({root}));workspace=boundedWorkspace(root,workspace);
|
|
2800
|
-
const names = gitFiles(root), visible = new Set(names), overlay = new Map(), payload = new Map(), queue = [], visited = new Set();
|
|
3351
|
+
const names = gitFiles(root), visible = new Set(names), overlay = new Map(), payload = new Map(), payloadAncestors = new Set(), queue = [], visited = new Set();
|
|
3352
|
+
let payloadBytes = 0;
|
|
3353
|
+
const setPayload = (p, file) => {
|
|
3354
|
+
const prev = payload.get(p);
|
|
3355
|
+
if (prev) payloadBytes -= prev.size;
|
|
3356
|
+
else addPathPrefixTracking(payloadAncestors, p);
|
|
3357
|
+
payload.set(p, file);
|
|
3358
|
+
payloadBytes += file.size;
|
|
3359
|
+
};
|
|
2801
3360
|
const chains=new Map(),preparationReads=new Set(),referenceReads=new Set();
|
|
2802
3361
|
const effective = new Map(), provenance = new Map(), edges = new Map(), shared = new Set(), footprintPayload = new Map(), storyContexts = new Map();
|
|
3362
|
+
const markdownCache = new Map();
|
|
3363
|
+
let expectedByTestCache = null;
|
|
3364
|
+
const expectedTestFor = testPath => {
|
|
3365
|
+
if (!expectedByTestCache) {
|
|
3366
|
+
expectedByTestCache = new Map(matchTests(names.filter(isStoryPath), names).tests.map(test => [test.path, test]));
|
|
3367
|
+
}
|
|
3368
|
+
return expectedByTestCache.get(testPath);
|
|
3369
|
+
};
|
|
2803
3370
|
let selecting = true;
|
|
2804
3371
|
const unavailable = new Map();
|
|
2805
3372
|
const markUnavailable = (path,error) => unavailable.set(path,{path,cause:String(error.message ?? error).replace(/[\r\n\x00-\x1f\x7f]/g,' ').slice(0,4000)});
|
|
2806
|
-
const reader = snapshotReader(root,new Set(names),file => { if (payload.has(file.path)) sourceLimit([...payload.values()]); }, strict,workspace);
|
|
3373
|
+
const reader = snapshotReader(root,new Set(names),file => { if (payload.has(file.path) && (payload.size > LIMITS.files || payloadBytes > LIMITS.bytes)) sourceLimit([...payload.values()]); }, strict,workspace);
|
|
2807
3374
|
const { inspectRaw, bytes, snapshots } = reader;
|
|
2808
3375
|
function inspect(path, from) {
|
|
2809
3376
|
if (overlay.has(path)) return overlay.get(path);
|
|
@@ -2816,11 +3383,13 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
2816
3383
|
const chain=chains.get(from)??[];requireRuntimePath(workspace,{path,from,chain});
|
|
2817
3384
|
if(!chains.has(path))chains.set(path,[...chain,from]);
|
|
2818
3385
|
const file = inspect(path, from);
|
|
2819
|
-
|
|
2820
|
-
|
|
3386
|
+
if (!payload.has(path) && hasPathPrefixConflict(payload, payloadAncestors, path)) {
|
|
3387
|
+
for (const selected of payload.keys()) if (selected.startsWith(`${path}/`) || path.startsWith(`${selected}/`)) {
|
|
3388
|
+
throw sourceProblem(from, path, `conflicts with selected file ${selected}.`);
|
|
3389
|
+
}
|
|
2821
3390
|
}
|
|
2822
3391
|
if (!footprintPayload.has(path)) footprintPayload.set(path,file);
|
|
2823
|
-
if (selecting && !payload.has(path))
|
|
3392
|
+
if (selecting && !payload.has(path)) setPayload(path, file);
|
|
2824
3393
|
if (visible.has(from)) {
|
|
2825
3394
|
if (!edges.has(from)) edges.set(from,new Set());
|
|
2826
3395
|
edges.get(from).add(path);
|
|
@@ -2846,7 +3415,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
2846
3415
|
let content = expanded.references.length ? Buffer.from(expanded.text,'utf8') : bytes(file);
|
|
2847
3416
|
if (format === 'scenario') {
|
|
2848
3417
|
let doc; try { doc = parseScenarioJson(content.toString('utf8')); } catch { /* Keep invalid-source handling. */ }
|
|
2849
|
-
const expected =
|
|
3418
|
+
const expected = expectedTestFor(file.path);
|
|
2850
3419
|
const authority = doc?.schema_version !== TEST_SCHEMA ? null : isObject(doc) && (typeof doc.story_path !== 'string' || !doc.story_path)
|
|
2851
3420
|
? refusal('pdd-no-story', 'story_path', 'The test has no story_path. Name its Story.')
|
|
2852
3421
|
: discoveryRefusal({path:file.path,storyPath:expected?.storyPath,doc});
|
|
@@ -2876,7 +3445,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
2876
3445
|
const storyFile = inspect(doc.story_path, file.path), storyBytes = Buffer.from(checkedStory, 'utf8');
|
|
2877
3446
|
const projected = {...storyFile,bytes:storyBytes,size:storyBytes.length};
|
|
2878
3447
|
effective.set(doc.story_path, projected); footprintPayload.set(doc.story_path, projected);
|
|
2879
|
-
if (selecting)
|
|
3448
|
+
if (selecting) setPayload(doc.story_path, projected);
|
|
2880
3449
|
resolved = {...resolved,doc:projection.doc,changed:true};
|
|
2881
3450
|
}
|
|
2882
3451
|
if (resolved.refusal && needsCriteriaResolution(doc)) {
|
|
@@ -2897,7 +3466,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
2897
3466
|
const result = {...file,bytes:content,size:content.length};
|
|
2898
3467
|
effective.set(file.path,result); provenance.set(file.path,expanded.references);
|
|
2899
3468
|
footprintPayload.set(file.path,result);
|
|
2900
|
-
if (selecting)
|
|
3469
|
+
if (selecting) setPayload(file.path,result);
|
|
2901
3470
|
return result;
|
|
2902
3471
|
}
|
|
2903
3472
|
const addStrings = (values, from, role) => { if (Array.isArray(values)) for (const path of values) if (typeof path === 'string') add(path, from, role); };
|
|
@@ -2984,7 +3553,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
2984
3553
|
visited.add(key);
|
|
2985
3554
|
try {
|
|
2986
3555
|
let file = effective.get(path) ?? footprintPayload.get(path);
|
|
2987
|
-
if (selecting)
|
|
3556
|
+
if (selecting) setPayload(path,file);
|
|
2988
3557
|
if (path.endsWith('.prompt.md')) file = prepare(file,'prompt');
|
|
2989
3558
|
else if (role === 'test') file = prepare(file,'scenario');
|
|
2990
3559
|
if (role === 'test' || role === 'app-map' || path.endsWith('.prompt.md') || path.endsWith('.md')) {
|
|
@@ -3007,7 +3576,11 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
3007
3576
|
if (typeof doc.entry_path === 'string' && doc.entry_path) add(doc.entry_path, path);
|
|
3008
3577
|
addStrings(doc.entry_paths, path);
|
|
3009
3578
|
addStrings(doc.app_maps, path, 'app-map');
|
|
3010
|
-
for (const
|
|
3579
|
+
for (const target of simulationGraph(doc.simulation).promptTargets) add(target, path);
|
|
3580
|
+
for (const step of Array.isArray(doc.steps) ? doc.steps : []) {
|
|
3581
|
+
if (typeof step?.entry_path === 'string') add(step.entry_path, path);
|
|
3582
|
+
for (const target of simulationGraph(stepSimulation(null, step?.simulation_overrides)).promptTargets) add(target, path);
|
|
3583
|
+
}
|
|
3011
3584
|
for (const item of Array.isArray(doc.context) ? doc.context : []) {
|
|
3012
3585
|
if (typeof item?.prompt_path === 'string') add(item.prompt_path, path);
|
|
3013
3586
|
addStrings(item?.paths, path);
|
|
@@ -3045,7 +3618,14 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
3045
3618
|
boundaries.set(path,{boundary,notes});
|
|
3046
3619
|
for (const member of boundary ?? []) add(member,path);
|
|
3047
3620
|
}
|
|
3048
|
-
|
|
3621
|
+
const mdSource = storyContexts.get(path) ?? text;
|
|
3622
|
+
let mdTargets = markdownCache.get(path);
|
|
3623
|
+
if (!mdTargets || mdTargets.source !== mdSource) {
|
|
3624
|
+
mdTargets = { source: mdSource, targets: markdownContext(mdSource) };
|
|
3625
|
+
markdownCache.set(path, mdTargets);
|
|
3626
|
+
}
|
|
3627
|
+
for (const raw of mdTargets.targets) { const context = contextPath(raw, path, visible); if (context) add(context, path); }
|
|
3628
|
+
for (const aliasFile of contractAliasContext(mdSource, path, visible)) add(aliasFile, path);
|
|
3049
3629
|
if (path.endsWith('.prompt.md')) {
|
|
3050
3630
|
for (const block of interfaceBlocks(text)) {
|
|
3051
3631
|
let doc;
|
|
@@ -3068,7 +3648,15 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
3068
3648
|
for (const [path,file] of footprintPayload) if (path.endsWith('.prompt.md')) {
|
|
3069
3649
|
const promptText = bytes(file).toString('utf8'), blocks = interfaceBlocks(promptText), frontmatter = parsePromptFrontmatter(promptText);
|
|
3070
3650
|
if (!blocks.length && frontmatter.hasFrontmatter && !frontmatter.error && frontmatter.kind === 'native-only') { bindingPrompts.set(path, { kind: 'native-only', reason: frontmatter.reason }); continue; }
|
|
3071
|
-
if (!blocks.length && !frontmatter.hasFrontmatter && allowMissingInterfaces) {
|
|
3651
|
+
if (!blocks.length && !frontmatter.hasFrontmatter && allowMissingInterfaces) {
|
|
3652
|
+
bindingPrompts.set(path, {
|
|
3653
|
+
entries: [],
|
|
3654
|
+
calls: plainProseCalls(promptText, path, visible),
|
|
3655
|
+
resources: [],
|
|
3656
|
+
plain_prose: true,
|
|
3657
|
+
});
|
|
3658
|
+
continue;
|
|
3659
|
+
}
|
|
3072
3660
|
try { bindingPrompts.set(path,JSON.parse(blocks[0][1])); } catch { /* Admission reports malformed interfaces. */ }
|
|
3073
3661
|
}
|
|
3074
3662
|
const bindingPlans = [];
|
|
@@ -3095,12 +3683,17 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
3095
3683
|
const crossing=plan.problems[0];
|
|
3096
3684
|
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'});
|
|
3097
3685
|
}
|
|
3686
|
+
// Snapshot pre-projection prompt text before boundary/interface stripping so clause line numbers match authored prompts.
|
|
3687
|
+
const promptTextsForClauses = new Map();
|
|
3688
|
+
for (const [path, file] of payload) {
|
|
3689
|
+
if (path.endsWith('.prompt.md')) promptTextsForClauses.set(path, bytes(file).toString('utf8'));
|
|
3690
|
+
}
|
|
3098
3691
|
const required = new Set(scoped.flatMap(plan=>plan.boundary));
|
|
3099
3692
|
if (scoped.length === bindingPlans.length && scoped.length) for (const [path,file] of payload) {
|
|
3100
3693
|
if (!path.endsWith('.prompt.md') || required.has(path)) continue;
|
|
3101
3694
|
const projected=Buffer.from(bytes(file).toString('utf8').replace(INTERFACE,''),'utf8');
|
|
3102
3695
|
const next={...file,bytes:projected,size:projected.length};
|
|
3103
|
-
|
|
3696
|
+
setPayload(path,next); footprintPayload.set(path,next); effective.set(path,next);
|
|
3104
3697
|
}
|
|
3105
3698
|
// Project only effective executable bytes, after ordinary closure/boundary
|
|
3106
3699
|
// handling. Authored readers and raw hashes retain the local classification.
|
|
@@ -3112,7 +3705,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
3112
3705
|
if (projected === text || !original.equals(Buffer.from(text, 'utf8'))) continue;
|
|
3113
3706
|
const content = Buffer.from(projected, 'utf8'), next = { ...file, bytes: content, size: content.length };
|
|
3114
3707
|
footprintPayload.set(path, next); effective.set(path, next);
|
|
3115
|
-
if (payload.has(path))
|
|
3708
|
+
if (payload.has(path)) setPayload(path, next);
|
|
3116
3709
|
}
|
|
3117
3710
|
const files = [...payload.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0), total = sourceLimit(files);
|
|
3118
3711
|
const entries = files.map(file => ({ path: file.path, bytes: bytes(file) }));
|
|
@@ -3180,7 +3773,11 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
|
|
|
3180
3773
|
if (failures.length) return {story_path:story.story_path,tests:story.tests.sort(),unavailable:failures};
|
|
3181
3774
|
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) ?? [])};
|
|
3182
3775
|
});
|
|
3183
|
-
|
|
3776
|
+
const clauses = buildClauseTable(
|
|
3777
|
+
files.filter(file => file.path.endsWith('.prompt.md'))
|
|
3778
|
+
.map(file => ({ path: file.path, text: promptTextsForClauses.get(file.path) ?? bytes(file).toString('utf8') })),
|
|
3779
|
+
);
|
|
3780
|
+
return { appMap, tar, sha256: sha256(tar), files: files.map(({ path, size, target }) => ({ path, size, ...(target ? { target } : {}) })), clauses, bytes: total,
|
|
3184
3781
|
references:[...provenance.keys()].filter(path=>payload.has(path)).sort().flatMap(path=>provenance.get(path)), stories:footprints,
|
|
3185
3782
|
warnings:footprints.flatMap(story=>(story.unavailable ?? []).map(item=>`Warning: ${story.story_path}: footprint unavailable: ${item.cause}`)),
|
|
3186
3783
|
raw_file_hashes:rawFileHashes,
|
|
@@ -3199,6 +3796,435 @@ export function captureSource(root, { attempts = 3, ...selection } = {}, ports =
|
|
|
3199
3796
|
return captureWithPolicy(root, { attempts, ...selection }, false, ports);
|
|
3200
3797
|
}
|
|
3201
3798
|
|
|
3799
|
+
// Fast single-snapshot dependency closure planner for buildCheckPlan.
|
|
3800
|
+
// Shares Git discovery, snapshotReader, file reads, markdown parsing, and
|
|
3801
|
+
// interface parsing across all Stories while isolating any broken Story to
|
|
3802
|
+
// unavailable without re-capturing healthy Stories individually.
|
|
3803
|
+
function captureStoryClosuresOnce(root, { groups = [], workspace = loadRuntimeWorkspace({ root }), excludeFixtureProjects = false, allowMissingInterfaces = true }, ports = {}) {
|
|
3804
|
+
const { isStoryPath, matchTests } = requireSelectionPorts(ports);
|
|
3805
|
+
const headBefore = gitHead(root);
|
|
3806
|
+
const policyBefore = JSON.stringify(loadRuntimeWorkspace({ root }));
|
|
3807
|
+
workspace = boundedWorkspace(root, workspace);
|
|
3808
|
+
const names = gitFiles(root), visible = new Set(names);
|
|
3809
|
+
const reader = snapshotReader(root, new Set(names), () => {}, false, workspace);
|
|
3810
|
+
const { inspectRaw, bytes } = reader;
|
|
3811
|
+
const inspect = (path, from) => {
|
|
3812
|
+
const file = inspectRaw(path, from);
|
|
3813
|
+
if (!file.stat) throw sourceProblem(from, path, 'is missing. Restore it or correct the declared dependency.');
|
|
3814
|
+
return file;
|
|
3815
|
+
};
|
|
3816
|
+
const excluded = excludeFixtureProjects ? fixtureProjectRoots(root, names) : [];
|
|
3817
|
+
const discoveryNames = outsideFixtureProjects(names, excluded);
|
|
3818
|
+
const onDisk = discoverStories(root, discoveryNames, false, workspace, null, ports);
|
|
3819
|
+
const allNamed = matchTests(onDisk.storyFiles, discoveryNames).tests.flatMap(test => (test.files ?? [test.path]).map(path => ({ ...test, path })));
|
|
3820
|
+
const siblingsByStory = new Map();
|
|
3821
|
+
for (const test of allNamed) {
|
|
3822
|
+
if (!test.storyPath) continue;
|
|
3823
|
+
let list = siblingsByStory.get(test.storyPath);
|
|
3824
|
+
if (!list) { list = []; siblingsByStory.set(test.storyPath, list); }
|
|
3825
|
+
list.push(test);
|
|
3826
|
+
}
|
|
3827
|
+
const expectedByTest = new Map(matchTests(names.filter(isStoryPath), names).tests.map(test => [test.path, test]));
|
|
3828
|
+
const shared = [];
|
|
3829
|
+
let sharedFailed = false;
|
|
3830
|
+
if (visible.has(SOURCE_CONFIG)) {
|
|
3831
|
+
try {
|
|
3832
|
+
const config = inspectRaw(SOURCE_CONFIG, SOURCE_CONFIG, false, false, true);
|
|
3833
|
+
const doc = JSON.parse(bytes(config).toString('utf8'));
|
|
3834
|
+
if (!isObject(doc) || Object.keys(doc).length !== 1 || !Array.isArray(doc.include)) {
|
|
3835
|
+
throw sourceProblem(SOURCE_CONFIG, '', 'must contain only an include array of file paths.');
|
|
3836
|
+
}
|
|
3837
|
+
for (const raw of doc.include) {
|
|
3838
|
+
const path = sourcePath(raw, SOURCE_CONFIG);
|
|
3839
|
+
requireRuntimePath(workspace, { path, from: SOURCE_CONFIG, chain: [] });
|
|
3840
|
+
inspect(path, SOURCE_CONFIG);
|
|
3841
|
+
shared.push(path);
|
|
3842
|
+
}
|
|
3843
|
+
} catch (error) {
|
|
3844
|
+
if (reader.unstable || error === unstableSource) return null;
|
|
3845
|
+
sharedFailed = true;
|
|
3846
|
+
}
|
|
3847
|
+
}
|
|
3848
|
+
|
|
3849
|
+
const referenceFiles = {
|
|
3850
|
+
stat({ path }) {
|
|
3851
|
+
const file = inspectRaw(path, 'Reference', true);
|
|
3852
|
+
return { exists: !!file.stat, is_symlink: false, size: file.size };
|
|
3853
|
+
},
|
|
3854
|
+
read({ path }) { return { content: bytes(inspect(path, 'Reference')).toString('utf8') }; },
|
|
3855
|
+
};
|
|
3856
|
+
const preparedCache = new Map();
|
|
3857
|
+
const textCache = new WeakMap();
|
|
3858
|
+
const textOf = file => {
|
|
3859
|
+
let text = textCache.get(file);
|
|
3860
|
+
if (text === undefined) {
|
|
3861
|
+
text = bytes(file).toString('utf8');
|
|
3862
|
+
textCache.set(file, text);
|
|
3863
|
+
}
|
|
3864
|
+
return text;
|
|
3865
|
+
};
|
|
3866
|
+
const markdownCache = new Map();
|
|
3867
|
+
const boundaryCache = new Map();
|
|
3868
|
+
const promptInterfaceCache = new Map();
|
|
3869
|
+
const appMapCache = new Map();
|
|
3870
|
+
const resolvedContextCache = new Map();
|
|
3871
|
+
|
|
3872
|
+
const resolvedMarkdownTargetsFor = (path, file) => {
|
|
3873
|
+
let cached = resolvedContextCache.get(path);
|
|
3874
|
+
if (cached) {
|
|
3875
|
+
if (!cached.ok) throw cached.error;
|
|
3876
|
+
return cached.targets;
|
|
3877
|
+
}
|
|
3878
|
+
try {
|
|
3879
|
+
const text = textOf(file);
|
|
3880
|
+
const rawTargets = markdownCache.get(path) ?? (() => {
|
|
3881
|
+
const list = markdownContext(text);
|
|
3882
|
+
markdownCache.set(path, list);
|
|
3883
|
+
return list;
|
|
3884
|
+
})();
|
|
3885
|
+
const resolved = [];
|
|
3886
|
+
for (const raw of rawTargets) {
|
|
3887
|
+
const ctx = contextPath(raw, path, visible);
|
|
3888
|
+
if (ctx) resolved.push(ctx);
|
|
3889
|
+
}
|
|
3890
|
+
resolvedContextCache.set(path, { ok: true, targets: resolved });
|
|
3891
|
+
return resolved;
|
|
3892
|
+
} catch (error) {
|
|
3893
|
+
resolvedContextCache.set(path, { ok: false, error });
|
|
3894
|
+
throw error;
|
|
3895
|
+
}
|
|
3896
|
+
};
|
|
3897
|
+
|
|
3898
|
+
const prepareCached = (file, format) => {
|
|
3899
|
+
const cacheKey = `${file.path}\0${format}`;
|
|
3900
|
+
if (preparedCache.has(cacheKey)) {
|
|
3901
|
+
const cached = preparedCache.get(cacheKey);
|
|
3902
|
+
if (!cached.ok) throw cached.error;
|
|
3903
|
+
return cached.value;
|
|
3904
|
+
}
|
|
3905
|
+
try {
|
|
3906
|
+
let expanded;
|
|
3907
|
+
try { expanded = expandSource({ path: file.path, text: bytes(file).toString('utf8'), format }, referenceFiles); }
|
|
3908
|
+
catch (error) {
|
|
3909
|
+
if (reader.unstable || error === unstableSource) throw unstableSource;
|
|
3910
|
+
if (error.code) throw new PreflightError(4, `${error.code}: ${error.message}`);
|
|
3911
|
+
throw error;
|
|
3912
|
+
}
|
|
3913
|
+
let content = expanded.references.length ? Buffer.from(expanded.text, 'utf8') : bytes(file);
|
|
3914
|
+
let extraStoryPath = null;
|
|
3915
|
+
if (format === 'scenario') {
|
|
3916
|
+
let doc; try { doc = parseScenarioJson(content.toString('utf8')); } catch { /* Keep invalid-source handling. */ }
|
|
3917
|
+
const expected = expectedByTest.get(file.path);
|
|
3918
|
+
const authority = doc?.schema_version !== TEST_SCHEMA ? null : isObject(doc) && (typeof doc.story_path !== 'string' || !doc.story_path)
|
|
3919
|
+
? refusal('pdd-no-story', 'story_path', 'The test has no story_path. Name its Story.')
|
|
3920
|
+
: discoveryRefusal({ path: file.path, storyPath: expected?.storyPath, doc });
|
|
3921
|
+
if (authority) {
|
|
3922
|
+
throw Object.assign(new PreflightError(4, `${file.path}: ${authority.message}`), authority,
|
|
3923
|
+
{ message: `${file.path}: ${authority.message}`, hint: 'Restore the Story path selected by the test name, then run the selection again.' });
|
|
3924
|
+
}
|
|
3925
|
+
if (typeof doc?.story_path === 'string' && !documentRefusal(doc, file.path, { allowOmittedCriteria: true })) {
|
|
3926
|
+
extraStoryPath = doc.story_path;
|
|
3927
|
+
const storySource = bytes(inspect(doc.story_path, file.path)).toString('utf8');
|
|
3928
|
+
const partial = partialTestRefusal(doc);
|
|
3929
|
+
const resolved = partial ? { doc, changed: false, refusal: null } : resolveScenarioCriteria(doc, storySource);
|
|
3930
|
+
if (resolved.refusal && needsCriteriaResolution(doc)) {
|
|
3931
|
+
throw Object.assign(new PreflightError(4, `${file.path}: ${resolved.refusal.message}`), resolved.refusal,
|
|
3932
|
+
{ message: `${file.path}: ${resolved.refusal.message}`, hint: 'Fix the scenario criteria or Story acceptance list, then run the selection again.' });
|
|
3933
|
+
}
|
|
3934
|
+
if (resolved.changed && !resolved.refusal) content = Buffer.from(stringifyScenarioJson(resolved.doc), 'utf8');
|
|
3935
|
+
if (!resolved.refusal && !scenarioShapeRefusal(resolved.doc, file.path)) {
|
|
3936
|
+
const plan = capturedCriterionPlan(resolved.doc, storyCriteria(storySource), file.path);
|
|
3937
|
+
if (resolved.changed || (plan?.not_checked.length && plan.checked)) {
|
|
3938
|
+
content = Buffer.from(stringifyScenarioJson({ ...resolved.doc, criteria: plan.criteria,
|
|
3939
|
+
...(plan?.not_checked.length ? { check_exemptions: plan.not_checked.map(item => ({ criterion_id: item.criterion_id, reason: 'out-of-scope', detail: item.reason })) } : {}) }), 'utf8');
|
|
3940
|
+
}
|
|
3941
|
+
}
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
const value = { file: { ...file, bytes: content, size: content.length }, extraStoryPath };
|
|
3945
|
+
preparedCache.set(cacheKey, { ok: true, value });
|
|
3946
|
+
return value;
|
|
3947
|
+
} catch (error) {
|
|
3948
|
+
if (reader.unstable || error === unstableSource) throw unstableSource;
|
|
3949
|
+
preparedCache.set(cacheKey, { ok: false, error });
|
|
3950
|
+
throw error;
|
|
3951
|
+
}
|
|
3952
|
+
};
|
|
3953
|
+
|
|
3954
|
+
const promptInfoFor = (path, file) => {
|
|
3955
|
+
let cached = promptInterfaceCache.get(path);
|
|
3956
|
+
if (!cached) {
|
|
3957
|
+
const text = textOf(file);
|
|
3958
|
+
const blocks = interfaceBlocks(text);
|
|
3959
|
+
const frontmatter = parsePromptFrontmatter(text);
|
|
3960
|
+
const calls = [];
|
|
3961
|
+
for (const block of blocks) {
|
|
3962
|
+
let doc;
|
|
3963
|
+
try { doc = JSON.parse(block[1]); } catch { continue; }
|
|
3964
|
+
for (const call of Array.isArray(doc?.calls) ? doc.calls : []) {
|
|
3965
|
+
if (typeof call?.target === 'string') calls.push(call.target);
|
|
3966
|
+
}
|
|
3967
|
+
}
|
|
3968
|
+
let bindingIface = null;
|
|
3969
|
+
if (!blocks.length && frontmatter.hasFrontmatter && !frontmatter.error && frontmatter.kind === 'native-only') {
|
|
3970
|
+
bindingIface = { kind: 'native-only', reason: frontmatter.reason };
|
|
3971
|
+
} else if (!blocks.length && !frontmatter.hasFrontmatter && allowMissingInterfaces) {
|
|
3972
|
+
bindingIface = { entries: [], calls: [], resources: [] };
|
|
3973
|
+
} else if (blocks.length) {
|
|
3974
|
+
try { bindingIface = JSON.parse(blocks[0][1]); } catch { /* malformed */ }
|
|
3975
|
+
}
|
|
3976
|
+
cached = { calls, bindingIface };
|
|
3977
|
+
promptInterfaceCache.set(path, cached);
|
|
3978
|
+
}
|
|
3979
|
+
return cached;
|
|
3980
|
+
};
|
|
3981
|
+
|
|
3982
|
+
const boundaryFor = (path, text, chain) => {
|
|
3983
|
+
if (boundaryCache.has(path)) return boundaryCache.get(path);
|
|
3984
|
+
const notes = [];
|
|
3985
|
+
let boundary = runtimeBoundary(path, text, { notes });
|
|
3986
|
+
if (boundary) {
|
|
3987
|
+
try {
|
|
3988
|
+
for (const member of boundary) {
|
|
3989
|
+
requireRuntimePath(workspace, { path: member, from: path, chain });
|
|
3990
|
+
bytes(inspect(member, path));
|
|
3991
|
+
}
|
|
3992
|
+
} catch (error) {
|
|
3993
|
+
if (reader.unstable || error === unstableSource) throw unstableSource;
|
|
3994
|
+
boundary = null;
|
|
3995
|
+
}
|
|
3996
|
+
}
|
|
3997
|
+
boundaryCache.set(path, boundary);
|
|
3998
|
+
return boundary;
|
|
3999
|
+
};
|
|
4000
|
+
|
|
4001
|
+
const appMapTargetsFor = (path, text) => {
|
|
4002
|
+
if (appMapCache.has(path)) {
|
|
4003
|
+
const cached = appMapCache.get(path);
|
|
4004
|
+
if (!cached.ok) throw cached.error;
|
|
4005
|
+
return cached.targets;
|
|
4006
|
+
}
|
|
4007
|
+
let map;
|
|
4008
|
+
try { map = JSON.parse(text); } catch {
|
|
4009
|
+
const err = sourceProblem(path, '', 'must be valid app-map JSON.');
|
|
4010
|
+
appMapCache.set(path, { ok: false, error: err });
|
|
4011
|
+
throw err;
|
|
4012
|
+
}
|
|
4013
|
+
const targets = [];
|
|
4014
|
+
const walk = value => {
|
|
4015
|
+
if (Array.isArray(value)) { for (const item of value) walk(item); return; }
|
|
4016
|
+
if (!isObject(value)) return;
|
|
4017
|
+
if (typeof value.prompt_path === 'string') targets.push(value.prompt_path);
|
|
4018
|
+
if (typeof value.owner_prompt === 'string') targets.push(value.owner_prompt);
|
|
4019
|
+
if (Array.isArray(value.stylesheets)) for (const s of value.stylesheets) if (typeof s === 'string') targets.push(s);
|
|
4020
|
+
for (const key of ['screens', 'router', 'routes', 'handlers', 'handler', 'after', 'timers', 'host_regions', 'helpers']) walk(value[key]);
|
|
4021
|
+
};
|
|
4022
|
+
walk(map);
|
|
4023
|
+
appMapCache.set(path, { ok: true, targets });
|
|
4024
|
+
return targets;
|
|
4025
|
+
};
|
|
4026
|
+
|
|
4027
|
+
const closures = new Map();
|
|
4028
|
+
const targets = new Map();
|
|
4029
|
+
|
|
4030
|
+
for (const group of groups) {
|
|
4031
|
+
const storyPath = group.story_path;
|
|
4032
|
+
const selected = group.tests ?? [];
|
|
4033
|
+
if (sharedFailed) {
|
|
4034
|
+
closures.set(storyPath, { closure: [], unavailable: true });
|
|
4035
|
+
continue;
|
|
4036
|
+
}
|
|
4037
|
+
const payload = new Map(), payloadAncestors = new Set(), footprintPayload = new Map(), visited = new Set(), queue = [], chains = new Map();
|
|
4038
|
+
const storyTests = new Map(), storyBoundaries = new Map(), selectedDocs = [];
|
|
4039
|
+
const storyTargets = new Map();
|
|
4040
|
+
let payloadBytes = 0, selecting = true, storyUnavailable = false;
|
|
4041
|
+
|
|
4042
|
+
const setPayload = (p, file) => {
|
|
4043
|
+
const prev = payload.get(p);
|
|
4044
|
+
if (prev) payloadBytes -= prev.size;
|
|
4045
|
+
else addPathPrefixTracking(payloadAncestors, p);
|
|
4046
|
+
payload.set(p, file);
|
|
4047
|
+
payloadBytes += file.size;
|
|
4048
|
+
};
|
|
4049
|
+
const add = (raw, from, role = 'context') => {
|
|
4050
|
+
const path = (typeof raw === 'string' && visible.has(raw) && !raw.includes('\\') && !raw.startsWith('/') && !raw.includes('..') && !raw.includes('//') && !raw.startsWith('./'))
|
|
4051
|
+
? raw
|
|
4052
|
+
: sourcePath(raw, from);
|
|
4053
|
+
const qKey = `${path}\0${role}\0${selecting}`;
|
|
4054
|
+
if (visited.has(qKey)) return;
|
|
4055
|
+
if (!selecting && footprintPayload.has(path)) {
|
|
4056
|
+
queue.push({ path, role, upload: false });
|
|
4057
|
+
return;
|
|
4058
|
+
}
|
|
4059
|
+
if (selecting && payload.has(path)) {
|
|
4060
|
+
queue.push({ path, role, upload: true });
|
|
4061
|
+
return;
|
|
4062
|
+
}
|
|
4063
|
+
const chain = chains.get(from) ?? [];
|
|
4064
|
+
requireRuntimePath(workspace, { path, from, chain });
|
|
4065
|
+
if (!chains.has(path)) chains.set(path, [...chain, from]);
|
|
4066
|
+
const file = inspect(path, from);
|
|
4067
|
+
if (!payload.has(path) && hasPathPrefixConflict(payload, payloadAncestors, path)) {
|
|
4068
|
+
for (const existing of payload.keys()) if (existing.startsWith(`${path}/`) || path.startsWith(`${existing}/`)) {
|
|
4069
|
+
throw sourceProblem(from, path, `conflicts with selected file ${existing}.`);
|
|
4070
|
+
}
|
|
4071
|
+
}
|
|
4072
|
+
if (!footprintPayload.has(path)) footprintPayload.set(path, file);
|
|
4073
|
+
if (selecting && !payload.has(path)) setPayload(path, file);
|
|
4074
|
+
if (file.target) storyTargets.set(path, file.target);
|
|
4075
|
+
queue.push({ path, role, upload: selecting });
|
|
4076
|
+
};
|
|
4077
|
+
const addStrings = (values, from, role) => {
|
|
4078
|
+
if (Array.isArray(values)) for (const p of values) if (typeof p === 'string') add(p, from, role);
|
|
4079
|
+
};
|
|
4080
|
+
|
|
4081
|
+
try {
|
|
4082
|
+
for (const path of shared) add(path, SOURCE_CONFIG);
|
|
4083
|
+
for (const path of selected) add(path, 'Selected test', path.endsWith('.prompt.md') ? 'context' : isStoryPath(path) ? 'story' : 'test');
|
|
4084
|
+
let siblingsAdded = false;
|
|
4085
|
+
for (let index = 0; index < queue.length || !siblingsAdded; index++) {
|
|
4086
|
+
if (index === queue.length && !siblingsAdded) {
|
|
4087
|
+
siblingsAdded = true; selecting = false;
|
|
4088
|
+
for (const s of storyTests.keys()) {
|
|
4089
|
+
for (const test of siblingsByStory.get(s) ?? []) {
|
|
4090
|
+
if (!storyTests.get(s).includes(test.path)) storyTests.get(s).push(test.path);
|
|
4091
|
+
try {
|
|
4092
|
+
if (test.problem) storyUnavailable = true;
|
|
4093
|
+
add(test.path, 'Story footprint', 'test');
|
|
4094
|
+
} catch (error) {
|
|
4095
|
+
if (reader.unstable || error === unstableSource) throw unstableSource;
|
|
4096
|
+
storyUnavailable = true;
|
|
4097
|
+
}
|
|
4098
|
+
}
|
|
4099
|
+
}
|
|
4100
|
+
if (index === queue.length) break;
|
|
4101
|
+
}
|
|
4102
|
+
const { path, role, upload } = queue[index], key = `${path}\0${role}\0${upload}`;
|
|
4103
|
+
selecting = upload;
|
|
4104
|
+
if (visited.has(key)) continue;
|
|
4105
|
+
visited.add(key);
|
|
4106
|
+
try {
|
|
4107
|
+
let file = footprintPayload.get(path);
|
|
4108
|
+
if (selecting) setPayload(path, file);
|
|
4109
|
+
if (path.endsWith('.prompt.md')) {
|
|
4110
|
+
const prepared = prepareCached(file, 'prompt');
|
|
4111
|
+
file = prepared.file;
|
|
4112
|
+
footprintPayload.set(path, file);
|
|
4113
|
+
if (selecting) setPayload(path, file);
|
|
4114
|
+
} else if (role === 'test') {
|
|
4115
|
+
const prepared = prepareCached(file, 'scenario');
|
|
4116
|
+
file = prepared.file;
|
|
4117
|
+
footprintPayload.set(path, file);
|
|
4118
|
+
if (selecting) setPayload(path, file);
|
|
4119
|
+
if (prepared.extraStoryPath) add(prepared.extraStoryPath, path, 'story');
|
|
4120
|
+
}
|
|
4121
|
+
if (payload.size > LIMITS.files || payloadBytes > LIMITS.bytes) sourceLimit([...payload.values()]);
|
|
4122
|
+
if (role === 'test' || role === 'app-map' || path.endsWith('.prompt.md') || path.endsWith('.md')) {
|
|
4123
|
+
if (role === 'test') {
|
|
4124
|
+
const text = textOf(file);
|
|
4125
|
+
let doc;
|
|
4126
|
+
try { doc = JSON.parse(text); } catch { continue; }
|
|
4127
|
+
if (!isObject(doc)) continue;
|
|
4128
|
+
const mapRefusal = appMapsRefusal(doc);
|
|
4129
|
+
if (mapRefusal) throw Object.assign(new PreflightError(4, path + ': ' + mapRefusal.section + ': ' + mapRefusal.message), { code: mapRefusal.code, section: mapRefusal.section });
|
|
4130
|
+
const effectiveStoryPath = typeof doc.story_path === 'string' && doc.story_path
|
|
4131
|
+
? doc.story_path
|
|
4132
|
+
: (path.endsWith('.json') && visible.has(`user_stories/${basename(path, '.json')}.md`)
|
|
4133
|
+
? `user_stories/${basename(path, '.json')}.md` : null);
|
|
4134
|
+
if (typeof effectiveStoryPath === 'string') {
|
|
4135
|
+
if (selecting) {
|
|
4136
|
+
if (!storyTests.has(effectiveStoryPath)) storyTests.set(effectiveStoryPath, []);
|
|
4137
|
+
if (!storyTests.get(effectiveStoryPath).includes(path)) storyTests.get(effectiveStoryPath).push(path);
|
|
4138
|
+
if (Array.isArray(doc.steps)) selectedDocs.push({ storyPath: effectiveStoryPath, doc });
|
|
4139
|
+
}
|
|
4140
|
+
add(effectiveStoryPath, path, 'story');
|
|
4141
|
+
}
|
|
4142
|
+
if (typeof doc.entry_path === 'string' && doc.entry_path) add(doc.entry_path, path);
|
|
4143
|
+
addStrings(doc.entry_paths, path);
|
|
4144
|
+
addStrings(doc.app_maps, path, 'app-map');
|
|
4145
|
+
for (const step of Array.isArray(doc.steps) ? doc.steps : []) if (typeof step?.entry_path === 'string') add(step.entry_path, path);
|
|
4146
|
+
for (const item of Array.isArray(doc.context) ? doc.context : []) {
|
|
4147
|
+
if (typeof item?.prompt_path === 'string') add(item.prompt_path, path);
|
|
4148
|
+
addStrings(item?.paths, path);
|
|
4149
|
+
}
|
|
4150
|
+
} else if (role === 'app-map') {
|
|
4151
|
+
for (const target of appMapTargetsFor(path, textOf(file))) add(target, path);
|
|
4152
|
+
} else {
|
|
4153
|
+
if (role === 'story') {
|
|
4154
|
+
const boundary = boundaryFor(path, textOf(file), chains.get(path) ?? []);
|
|
4155
|
+
storyBoundaries.set(path, boundary);
|
|
4156
|
+
for (const member of boundary ?? []) add(member, path);
|
|
4157
|
+
}
|
|
4158
|
+
for (const context of resolvedMarkdownTargetsFor(path, file)) add(context, path);
|
|
4159
|
+
if (path.endsWith('.prompt.md')) {
|
|
4160
|
+
const info = promptInfoFor(path, file);
|
|
4161
|
+
for (const target of info.calls) add(target, path);
|
|
4162
|
+
}
|
|
4163
|
+
}
|
|
4164
|
+
} else if (!selecting) {
|
|
4165
|
+
bytes(file);
|
|
4166
|
+
}
|
|
4167
|
+
} catch (error) {
|
|
4168
|
+
if (reader.unstable || error === unstableSource) throw unstableSource;
|
|
4169
|
+
if (selecting) throw error;
|
|
4170
|
+
storyUnavailable = true;
|
|
4171
|
+
}
|
|
4172
|
+
}
|
|
4173
|
+
// Validate per-story boundary reachability only when a Story declares a valid pdd-boundary.
|
|
4174
|
+
for (const item of selectedDocs) {
|
|
4175
|
+
const boundary = storyBoundaries.get(item.storyPath);
|
|
4176
|
+
if (!boundary) continue;
|
|
4177
|
+
const allowedSet = new Set(boundary);
|
|
4178
|
+
for (const p of boundary) inspect(p, item.storyPath);
|
|
4179
|
+
for (const step of item.doc.steps) {
|
|
4180
|
+
if (!step || typeof step.entry_path !== 'string') continue;
|
|
4181
|
+
const seen = new Set(), pending = [step.entry_path, ...boundary];
|
|
4182
|
+
for (let i = 0; i < pending.length; i++) {
|
|
4183
|
+
const p = pending[i];
|
|
4184
|
+
if (seen.has(p)) continue;
|
|
4185
|
+
seen.add(p);
|
|
4186
|
+
if (!allowedSet.has(p)) throw Object.assign(new PreflightError(4, `${item.storyPath}: ${step.step_id}: ${p}: out-of-boundary.`), { code: 'binding-boundary-invalid' });
|
|
4187
|
+
const f = footprintPayload.get(p);
|
|
4188
|
+
const info = f ? promptInfoFor(p, f) : null;
|
|
4189
|
+
if (!info?.bindingIface) throw Object.assign(new PreflightError(4, `${item.storyPath}: ${step.step_id}: ${p}: interface-unavailable.`), { code: 'binding-boundary-invalid' });
|
|
4190
|
+
for (const call of Array.isArray(info.bindingIface.calls) ? info.bindingIface.calls : []) {
|
|
4191
|
+
if (typeof call?.target === 'string') pending.push(call.target);
|
|
4192
|
+
}
|
|
4193
|
+
}
|
|
4194
|
+
}
|
|
4195
|
+
}
|
|
4196
|
+
// Enforce per-story upload size limit (only materialize tar if close to 10MB).
|
|
4197
|
+
const payloadFiles = [...payload.values()];
|
|
4198
|
+
sourceLimit(payloadFiles);
|
|
4199
|
+
if (payloadBytes + payloadFiles.length * 1024 + 1024 > LIMITS.bytes) {
|
|
4200
|
+
const tar = tarFiles(payloadFiles.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map(file => ({ path: file.path, bytes: bytes(file) })));
|
|
4201
|
+
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 });
|
|
4202
|
+
}
|
|
4203
|
+
if (storyUnavailable) {
|
|
4204
|
+
closures.set(storyPath, { closure: [], unavailable: true });
|
|
4205
|
+
} else {
|
|
4206
|
+
for (const [k, v] of storyTargets) targets.set(k, v);
|
|
4207
|
+
closures.set(storyPath, { closure: [...footprintPayload.keys()].sort(), unavailable: false });
|
|
4208
|
+
}
|
|
4209
|
+
} catch (error) {
|
|
4210
|
+
if (reader.unstable || error === unstableSource) return null;
|
|
4211
|
+
closures.set(storyPath, { closure: [], unavailable: true });
|
|
4212
|
+
}
|
|
4213
|
+
}
|
|
4214
|
+
|
|
4215
|
+
const same = !reader.unstable && gitHead(root) === headBefore && isDeepStrictEqual(gitFiles(root), names) && reader.stable() && JSON.stringify(loadRuntimeWorkspace({ root })) === policyBefore;
|
|
4216
|
+
if (!same) return null;
|
|
4217
|
+
return { closures, targets };
|
|
4218
|
+
}
|
|
4219
|
+
|
|
4220
|
+
export function captureStoryClosures(root, { attempts = 3, ...selection } = {}, ports = {}) {
|
|
4221
|
+
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
|
4222
|
+
const result = captureStoryClosuresOnce(root, selection, ports);
|
|
4223
|
+
if (result) return result;
|
|
4224
|
+
}
|
|
4225
|
+
throw new PreflightError(5, `The files changed while pdd read them (${attempts} times). Stop other edits, then run pdd test again.`);
|
|
4226
|
+
}
|
|
4227
|
+
|
|
3202
4228
|
// Resolve a scoped hash request before mutation. Capture remains the one owner
|
|
3203
4229
|
// of source closure, availability, workspace and reference validation.
|
|
3204
4230
|
captureSource.isDefaultCapture = true;
|
|
@@ -3585,6 +4611,8 @@ const PROMPT_PROSE_LINE_LIMIT = 500;
|
|
|
3585
4611
|
const PROMPT_PROSE_ELEVATED_LIMIT = 1000;
|
|
3586
4612
|
const STORY_STEP_LIMIT = 15;
|
|
3587
4613
|
const STORY_LINE_LIMIT = 1000;
|
|
4614
|
+
const STORY_CLOSURE_PROMPT_LIMIT = 6;
|
|
4615
|
+
const STORY_CLOSURE_CONTRACT_BYTES_LIMIT = 48 * 1024;
|
|
3588
4616
|
|
|
3589
4617
|
function promptProseLineCount(text) {
|
|
3590
4618
|
const prose = text.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '').replace(INTERFACE, '').trimEnd();
|
|
@@ -3618,7 +4646,114 @@ function storyComplexityWarningLine({ path, storyPath, doc }, rawText) {
|
|
|
3618
4646
|
if (lines > STORY_LINE_LIMIT) reasons.push(`${lines} lines (limit: ${STORY_LINE_LIMIT})`);
|
|
3619
4647
|
if (!reasons.length) return null;
|
|
3620
4648
|
const storyLabel = storyPath ?? (typeof doc.story_path === 'string' && doc.story_path.trim() ? doc.story_path.trim() : null) ?? path;
|
|
3621
|
-
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 (
|
|
4649
|
+
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 (see the pdd skill references stories.md and verification.md, or run pdd help prompting).`;
|
|
4650
|
+
}
|
|
4651
|
+
|
|
4652
|
+
function contractRefsFromText(text, fromPath, visible) {
|
|
4653
|
+
if (typeof text !== 'string' || !text) return [];
|
|
4654
|
+
const targets = new Set();
|
|
4655
|
+
const tryAdd = (raw, requireContractDir = false) => {
|
|
4656
|
+
if (typeof raw !== 'string' || !raw.trim()) return;
|
|
4657
|
+
let resolved;
|
|
4658
|
+
try { resolved = contextPath(raw, fromPath, visible); } catch { return; }
|
|
4659
|
+
if (!resolved || !visible.has(resolved) || resolved.endsWith('.prompt.md')) return;
|
|
4660
|
+
if (resolved.startsWith('user_stories/') || resolved.startsWith('tests/') || resolved.startsWith('test/')) return;
|
|
4661
|
+
if (!/\.(?:md|json)$/i.test(resolved)) return;
|
|
4662
|
+
if (requireContractDir && !/(?:^|\/)contracts\//.test(resolved)) return;
|
|
4663
|
+
targets.add(resolved);
|
|
4664
|
+
};
|
|
4665
|
+
for (const match of text.matchAll(/"\$contract"\s*:\s*"([^"#\r\n]+)(?:#[^"\r\n]*)?"/g)) {
|
|
4666
|
+
tryAdd(match[1], false);
|
|
4667
|
+
}
|
|
4668
|
+
const prose = text.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '').replace(INTERFACE, '');
|
|
4669
|
+
const masked = markdownSectionText(prose);
|
|
4670
|
+
const definitions = markdownDefinitions(masked);
|
|
4671
|
+
for (const raw of markdownContext(text)) tryAdd(raw, false);
|
|
4672
|
+
for (const raw of markdownLinks(masked, definitions)) tryAdd(raw, true);
|
|
4673
|
+
return [...targets];
|
|
4674
|
+
}
|
|
4675
|
+
|
|
4676
|
+
function storyClosureWarningLine({ path, storyPath, doc }, { readText, visible }) {
|
|
4677
|
+
if (!isObject(doc) || (Object.hasOwn(doc, 'schema_version') && doc.schema_version !== TEST_SCHEMA)) return null;
|
|
4678
|
+
const steps = Array.isArray(doc.steps) ? doc.steps : [];
|
|
4679
|
+
if (!steps.length || typeof readText !== 'function' || !(visible instanceof Set)) return null;
|
|
4680
|
+
const effectiveStoryPath = storyPath ?? (typeof doc.story_path === 'string' && doc.story_path.trim() ? doc.story_path.trim() : null);
|
|
4681
|
+
const storyText = effectiveStoryPath ? readText(effectiveStoryPath) : null;
|
|
4682
|
+
const boundary = typeof storyText === 'string' ? runtimeBoundary(effectiveStoryPath, storyText) : null;
|
|
4683
|
+
const promptTexts = new Map();
|
|
4684
|
+
const getPromptText = target => {
|
|
4685
|
+
if (!promptTexts.has(target)) promptTexts.set(target, readText(target));
|
|
4686
|
+
return promptTexts.get(target);
|
|
4687
|
+
};
|
|
4688
|
+
const storyPrompts = new Set();
|
|
4689
|
+
for (const step of steps) {
|
|
4690
|
+
if (!isObject(step) || typeof step.entry_path !== 'string' || !step.entry_path) continue;
|
|
4691
|
+
const sim = simulationGraph(stepSimulation(doc.simulation, step.simulation_overrides));
|
|
4692
|
+
const stepSeen = new Set();
|
|
4693
|
+
const pending = boundary !== null ? [step.entry_path, ...boundary] : [step.entry_path, ...sim.promptTargets];
|
|
4694
|
+
for (let index = 0; index < pending.length; index++) {
|
|
4695
|
+
const current = pending[index];
|
|
4696
|
+
if (typeof current !== 'string' || !current || stepSeen.has(current)) continue;
|
|
4697
|
+
stepSeen.add(current);
|
|
4698
|
+
storyPrompts.add(current);
|
|
4699
|
+
if (boundary !== null && !boundary.includes(current)) continue;
|
|
4700
|
+
const text = getPromptText(current);
|
|
4701
|
+
if (typeof text !== 'string') continue;
|
|
4702
|
+
const blocks = interfaceBlocks(text);
|
|
4703
|
+
let calls = [];
|
|
4704
|
+
if (blocks.length) {
|
|
4705
|
+
try {
|
|
4706
|
+
const parsed = JSON.parse(blocks[0][1]);
|
|
4707
|
+
calls = Array.isArray(parsed?.calls) ? parsed.calls : [];
|
|
4708
|
+
} catch { calls = []; }
|
|
4709
|
+
} else {
|
|
4710
|
+
const frontmatter = parsePromptFrontmatter(text);
|
|
4711
|
+
if (!(frontmatter.hasFrontmatter && frontmatter.kind === 'native-only')) {
|
|
4712
|
+
calls = plainProseCalls(text, current, visible);
|
|
4713
|
+
}
|
|
4714
|
+
}
|
|
4715
|
+
for (const call of calls) {
|
|
4716
|
+
if (typeof call?.target !== 'string') continue;
|
|
4717
|
+
if (boundary === null && call.target !== step.entry_path && isMockedPortCall(call, sim)) continue;
|
|
4718
|
+
pending.push(call.target);
|
|
4719
|
+
}
|
|
4720
|
+
}
|
|
4721
|
+
}
|
|
4722
|
+
const seenContracts = new Set();
|
|
4723
|
+
const contractQueue = [];
|
|
4724
|
+
for (const promptPath of storyPrompts) {
|
|
4725
|
+
const text = getPromptText(promptPath);
|
|
4726
|
+
if (typeof text === 'string') {
|
|
4727
|
+
for (const ref of contractRefsFromText(text, promptPath, visible)) contractQueue.push(ref);
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4730
|
+
try {
|
|
4731
|
+
for (const ref of contractRefsFromText(JSON.stringify(doc), path, visible)) contractQueue.push(ref);
|
|
4732
|
+
} catch {}
|
|
4733
|
+
let contractBytes = 0;
|
|
4734
|
+
for (let index = 0; index < contractQueue.length; index++) {
|
|
4735
|
+
const contractPath = contractQueue[index];
|
|
4736
|
+
if (seenContracts.has(contractPath)) continue;
|
|
4737
|
+
seenContracts.add(contractPath);
|
|
4738
|
+
const content = readText(contractPath);
|
|
4739
|
+
if (typeof content !== 'string') continue;
|
|
4740
|
+
contractBytes += Buffer.byteLength(content, 'utf8');
|
|
4741
|
+
if (contractPath.endsWith('.md')) {
|
|
4742
|
+
for (const nested of contractRefsFromText(content, contractPath, visible)) contractQueue.push(nested);
|
|
4743
|
+
}
|
|
4744
|
+
}
|
|
4745
|
+
const promptCount = storyPrompts.size;
|
|
4746
|
+
if (promptCount <= STORY_CLOSURE_PROMPT_LIMIT && contractBytes <= STORY_CLOSURE_CONTRACT_BYTES_LIMIT) return null;
|
|
4747
|
+
const reasons = [];
|
|
4748
|
+
if (promptCount > STORY_CLOSURE_PROMPT_LIMIT) {
|
|
4749
|
+
reasons.push(`${promptCount} prompts in closure (limit: ${STORY_CLOSURE_PROMPT_LIMIT})`);
|
|
4750
|
+
}
|
|
4751
|
+
if (contractBytes > STORY_CLOSURE_CONTRACT_BYTES_LIMIT) {
|
|
4752
|
+
const kib = (contractBytes / 1024).toFixed(1).replace(/\.0$/, '');
|
|
4753
|
+
reasons.push(`${kib} KiB of referenced contracts (limit: 48 KiB)`);
|
|
4754
|
+
}
|
|
4755
|
+
const storyLabel = effectiveStoryPath ?? path;
|
|
4756
|
+
return `Warning: large Story closure: ${storyLabel} (${path}) reaches ${reasons.join(' and ')}. Narrow the Story with a \`\`\`pdd-boundary block, mock downstream ports in simulation, or split shared contracts to reduce prefill tokens and stay under the 64 KiB contract cap.`;
|
|
3622
4757
|
}
|
|
3623
4758
|
|
|
3624
4759
|
function promptOpeningSentence(text) {
|
|
@@ -4018,6 +5153,8 @@ export function lintLocalHygiene({ root, files = gitFiles(root), promptPaths, te
|
|
|
4018
5153
|
for (const testEntry of [...inspectedTests].sort((a, b) => String(a?.path ?? '').localeCompare(String(b?.path ?? '')))) {
|
|
4019
5154
|
const storyWarning = storyComplexityWarningLine(testEntry, testEntry?.raw);
|
|
4020
5155
|
if (storyWarning) warnings.push(storyWarning);
|
|
5156
|
+
const closureWarning = storyClosureWarningLine(testEntry, { readText: readStrictText, visible: visibleSet });
|
|
5157
|
+
if (closureWarning) warnings.push(closureWarning);
|
|
4021
5158
|
}
|
|
4022
5159
|
|
|
4023
5160
|
for (const filePath of [...codeRowMap.keys()].sort()) {
|