@promptdriven/runtime-client 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +42 -2
- package/package.json +28 -4
- package/src/index.mjs +1 -0
- package/src/runtime/agent-ask.mjs +187 -0
- package/src/runtime/agent-chat.mjs +105 -0
- package/src/runtime/agent-coverage.mjs +97 -0
- package/src/runtime/agent-guide.mjs +152 -0
- package/src/runtime/agent-judge.mjs +71 -0
- package/src/runtime/agent-packet.mjs +62 -0
- package/src/runtime/agent-project.mjs +93 -0
- package/src/runtime/contract-refs.mjs +519 -0
- package/src/runtime/contracts.mjs +138 -0
- package/src/runtime/index.mjs +943 -0
- package/src/runtime/lint-call-preflight.mjs +19 -0
- package/src/runtime/lint-compatibility-display.mjs +62 -0
- package/src/runtime/product-composition.mjs +384 -0
- package/src/runtime/runtime-binding-plan.mjs +145 -0
- package/src/runtime/runtime-bindings.mjs +71 -0
- package/src/runtime/runtime-check-plan.mjs +411 -0
- package/src/runtime/runtime-client.mjs +6323 -0
- package/src/runtime/runtime-lint-receipt.mjs +25 -0
- package/src/runtime/runtime-markdown.mjs +215 -0
- package/src/runtime/runtime-outcome.mjs +407 -0
- package/src/runtime/runtime-output.mjs +714 -0
- package/src/runtime/runtime-preflight.mjs +3118 -0
- package/src/runtime/runtime-slots.mjs +391 -0
- package/src/runtime/runtime-workspace-migration.mjs +70 -0
- package/src/runtime/runtime-workspace.mjs +52 -0
- package/src/runtime/scenario-json.mjs +91 -0
- package/src/runtime/secret-redaction.mjs +53 -0
- package/src/runtime/try-doors.mjs +231 -0
- package/src/runtime/try-http.mjs +259 -0
- package/src/runtime/try-mcp.mjs +223 -0
- package/src/runtime/try-session.mjs +95 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Generated from prompts/cli/lint-call-preflight.prompt.md.
|
|
2
|
+
// The Runtime supplies all costs. Association gates display only, never paid admission.
|
|
3
|
+
export function describeCallPreflight({ test, preflight, context, sourceSha256, requestedCap }) {
|
|
4
|
+
const trusted = preflight && context && context.source_sha256 === sourceSha256
|
|
5
|
+
&& /^[a-f0-9]{40}$/.test(context.engine_build ?? '')
|
|
6
|
+
&& context.selected_cap === requestedCap && preflight.selected_cap === requestedCap;
|
|
7
|
+
const quantity = value => value ?? 'unknown';
|
|
8
|
+
const lines = [trusted
|
|
9
|
+
? `Call preflight (${test}): ${preflight.status}; structural catalog estimate ${quantity(preflight.estimated_calls)} calls; selected cap ${preflight.selected_cap ?? 'not selected'}; complete ${preflight.complete}.`
|
|
10
|
+
: `Call preflight (${test}): unavailable; no estimate or cap-fit claim.`];
|
|
11
|
+
if (trusted) for (const step of preflight.steps ?? []) lines.push(
|
|
12
|
+
` Step ${step.step_id} (${step.entry_path} :: ${step.operation}): catalog ${quantity(step.catalog_calls)}; cumulative ${quantity(step.cumulative_catalog_calls)}; external resources ${step.has_external_resources}.`);
|
|
13
|
+
lines.push(context
|
|
14
|
+
? ` Source ${context.source_sha256}; engine ${context.engine_build}; configured maximum ${context.max_cap}.`
|
|
15
|
+
: ' Source and engine identity unavailable.');
|
|
16
|
+
if (trusted && preflight.status === 'warning') lines.push(' Warning: the structural estimate exceeds the selected cap; the cap is unchanged.');
|
|
17
|
+
lines.push(' Advisory only: no guarantee of actual calls or completion; resource continuations are not included. Lint uses 0 AI calls.');
|
|
18
|
+
return { text: lines.join('\n') };
|
|
19
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// Generated from prompts/cli/lint-compatibility-display.prompt.md (sha256: 73f366ec3d5c86902ce432f5037b2af34a29d67e30ae388bff28d361707d2cb8).
|
|
2
|
+
|
|
3
|
+
const countText = (count, singular) => count === 1 ? `1 ${singular}` : `${count} ${singular}s`;
|
|
4
|
+
const nonblank = value => typeof value === 'string' && value.trim().length > 0;
|
|
5
|
+
const distinct = values => [...new Set(values)];
|
|
6
|
+
|
|
7
|
+
export function describeCompatibility({ label, compatibility, clientAdvice = null, details = false }) {
|
|
8
|
+
if (details) {
|
|
9
|
+
const lines = [`Compatibility (${label}): ${JSON.stringify(compatibility, null, 2)}`];
|
|
10
|
+
if (clientAdvice !== null && clientAdvice !== undefined) lines.push(` Client advice: ${JSON.stringify(clientAdvice)}`);
|
|
11
|
+
return { text: lines.join('\n') };
|
|
12
|
+
}
|
|
13
|
+
const reported = compatibility?.reported;
|
|
14
|
+
const structured = reported !== null && typeof reported === 'object' && !Array.isArray(reported)
|
|
15
|
+
&& Array.isArray(reported.operations) && Array.isArray(reported.edges);
|
|
16
|
+
let summary;
|
|
17
|
+
if (structured) {
|
|
18
|
+
const items = [...reported.operations, ...reported.edges];
|
|
19
|
+
const stepCount = countText(distinct(items.map(item => item.selection.step_id)).length, 'step');
|
|
20
|
+
const opCount = countText(reported.operations.length, 'operation');
|
|
21
|
+
const edgeCount = countText(reported.edges.length, 'edge');
|
|
22
|
+
const execModes = items.length ? distinct(items.map(item => item.execution_mode)).join(', ') : 'none';
|
|
23
|
+
const resModes = items.length ? distinct(items.map(item => item.resource_mode)).join(', ') : 'none';
|
|
24
|
+
const engine = reported.engine_build === 'unknown' ? 'unknown' : String(reported.engine_build ?? '').slice(0, 12);
|
|
25
|
+
summary = `Compatibility (${label}): ${compatibility.state} (association ${compatibility.association}); ${stepCount} (${opCount}, ${edgeCount}); execution ${execModes}; resources ${resModes}; complete ${reported.complete}; engine ${engine}`;
|
|
26
|
+
if (nonblank(compatibility.issue)) summary += `; issue ${compatibility.issue}`;
|
|
27
|
+
const nonSupported = distinct(items.filter(item => item.verdict !== 'supported').map(item => item.reason_code));
|
|
28
|
+
if (nonSupported.length > 0) summary += `; non-supported: ${nonSupported.join(', ')}`;
|
|
29
|
+
summary += '.';
|
|
30
|
+
} else {
|
|
31
|
+
summary = `Compatibility (${label}): ${compatibility.state} (association ${compatibility.association})`;
|
|
32
|
+
if (typeof reported?.complete === 'boolean') summary += `; complete ${reported.complete}`;
|
|
33
|
+
if (typeof reported?.engine_build === 'string' && reported.engine_build.length > 0) {
|
|
34
|
+
summary += `; engine ${reported.engine_build === 'unknown' ? 'unknown' : reported.engine_build.slice(0, 12)}`;
|
|
35
|
+
}
|
|
36
|
+
if (nonblank(compatibility.issue)) summary += `; issue ${compatibility.issue}`;
|
|
37
|
+
summary += '.';
|
|
38
|
+
}
|
|
39
|
+
const lines = [summary];
|
|
40
|
+
if (clientAdvice !== null && clientAdvice !== undefined) {
|
|
41
|
+
lines.push(` Client advice (${clientAdvice.owner}): ${clientAdvice.next_step}`);
|
|
42
|
+
}
|
|
43
|
+
return { text: lines.join('\n') };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function describeLintDiagnostics({ problems, localOnly = false }) {
|
|
47
|
+
if (!problems.length) return { text: '' };
|
|
48
|
+
const blocking = problems.filter(item => item.severity !== 'warning');
|
|
49
|
+
const advisories = problems.filter(item => item.severity === 'warning');
|
|
50
|
+
const lines = [];
|
|
51
|
+
const emitGroup = (heading, items) => {
|
|
52
|
+
if (!items.length) return;
|
|
53
|
+
lines.push(heading);
|
|
54
|
+
for (const item of items) {
|
|
55
|
+
lines.push(` ${[item.code, item.path, item.section, item.message].filter(Boolean).join(' ')}`);
|
|
56
|
+
if (nonblank(item.hint)) lines.push(` ${item.hint}`);
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
emitGroup(localOnly ? 'Local lint problems:' : 'Lint problems (from the PDD interpreter):', blocking);
|
|
60
|
+
emitGroup(localOnly ? 'Local lint advisories:' : 'Lint advisories (from the PDD interpreter):', advisories);
|
|
61
|
+
return { text: lines.join('\n') };
|
|
62
|
+
}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// Generated from prompts/cli/product-composition.prompt.md (sha256: 5cce422befd0b81cf14251b2c7bed26572b988dc55a8dd5535ff6e684564cded).
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { checkInput, interfaceBlocks, parsePromptFrontmatter, PreflightError, promptMarkdownTargets } from './runtime-preflight.mjs';
|
|
4
|
+
import { expandSource, isJsonNumber, jsonNumberIdentity, parseJsonValue, stringifyJsonValue } from './contract-refs.mjs';
|
|
5
|
+
|
|
6
|
+
const fail = (code, message) => { throw Object.assign(Error(message), { code }); };
|
|
7
|
+
const badMap = message => fail('invalid-product-map', message);
|
|
8
|
+
const escape = value => value.replace(/~/g, '~0').replace(/\//g, '~1');
|
|
9
|
+
const plain = value => value !== null && typeof value === 'object' && !Array.isArray(value) && !isJsonNumber(value);
|
|
10
|
+
const ref = path => ({ $ref: path });
|
|
11
|
+
|
|
12
|
+
function matcherEqual(a, b) {
|
|
13
|
+
if (a === b) return true;
|
|
14
|
+
const numeric = value => isJsonNumber(value) || typeof value === 'number' || typeof value === 'boolean';
|
|
15
|
+
if (numeric(a) && numeric(b)) return jsonNumberIdentity(typeof a === 'boolean' ? Number(a) : a) === jsonNumberIdentity(typeof b === 'boolean' ? Number(b) : b);
|
|
16
|
+
if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((value, index) => matcherEqual(value, b[index]));
|
|
17
|
+
return plain(a) && plain(b) && Object.keys(a).length === Object.keys(b).length
|
|
18
|
+
&& Object.entries(a).every(([key, value]) => Object.hasOwn(b, key) && matcherEqual(value, b[key]));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function scopeTemplate(value, part) {
|
|
22
|
+
if (Array.isArray(value)) return value.map(item => scopeTemplate(item, part));
|
|
23
|
+
if (!plain(value)) return value;
|
|
24
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key,
|
|
25
|
+
key === '$ref' && typeof item === 'string' && /^\/state(?:\/|$)/.test(item)
|
|
26
|
+
? `/state/${escape(part)}${item.slice(6)}` : scopeTemplate(item, part)]));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function scopedHandlers(handlers, screen, encode) {
|
|
30
|
+
const applicable = handlers.filter(rule => rule.screen === '*' || rule.screen === screen);
|
|
31
|
+
const output = [];
|
|
32
|
+
for (const kind of new Set(applicable.map(rule => rule.kind))) {
|
|
33
|
+
const rules = applicable.filter(rule => rule.kind === kind);
|
|
34
|
+
if (!rules.some(rule => rule.screen === '*') || !rules.some(rule => rule.screen === screen)) { output.push(...rules); continue; }
|
|
35
|
+
const entries = value => Object.entries(value);
|
|
36
|
+
const compatible = (a, b) => entries(a).every(([key, value]) => !Object.hasOwn(b, key) || matcherEqual(value, b[key]));
|
|
37
|
+
const covers = (a, b) => entries(a).every(([key, value]) => Object.hasOwn(b, key) && matcherEqual(value, b[key]));
|
|
38
|
+
const behavior = rule => encode(Object.fromEntries(entries(rule).filter(([key]) => !['screen', 'match'].includes(key))));
|
|
39
|
+
const conditions = [], queue = [];
|
|
40
|
+
const addCondition = match => { if (!conditions.some(prior => matcherEqual(prior, match))) { conditions.push(match); queue.push(match); } };
|
|
41
|
+
for (const rule of rules) addCondition(rule.match);
|
|
42
|
+
for (let index = 0; index < queue.length; index++) for (const rule of rules) {
|
|
43
|
+
const match = queue[index];
|
|
44
|
+
if (!compatible(match, rule.match)) continue;
|
|
45
|
+
addCondition({ ...match, ...rule.match });
|
|
46
|
+
}
|
|
47
|
+
const compiled = conditions.map(match => {
|
|
48
|
+
const eligible = rules.filter(rule => covers(rule.match, match));
|
|
49
|
+
eligible.sort((a, b) => Number(a.screen === screen) - Number(b.screen === screen) || Object.keys(a.match).length - Object.keys(b.match).length);
|
|
50
|
+
return { ...eligible.at(-1), match };
|
|
51
|
+
});
|
|
52
|
+
const minimal = compiled.filter(rule => !compiled.some(other => other !== rule && Object.keys(other.match).length < Object.keys(rule.match).length
|
|
53
|
+
&& covers(other.match, rule.match) && behavior(other) === behavior(rule)
|
|
54
|
+
&& !compiled.some(competitor => behavior(competitor) !== behavior(rule) && compatible(competitor.match, rule.match)
|
|
55
|
+
&& Object.keys(competitor.match).length >= Object.keys(other.match).length)));
|
|
56
|
+
for (let index = 0; index < minimal.length; index++) for (const other of minimal.slice(index + 1)) {
|
|
57
|
+
if (Object.keys(minimal[index].match).length === Object.keys(other.match).length && compatible(minimal[index].match, other.match)) {
|
|
58
|
+
badMap(`Unsupported wildcard priority on ${screen}: overlapping ${kind} rules cannot retain their original priority after scoping.`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
output.push(...minimal);
|
|
62
|
+
}
|
|
63
|
+
return output;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function validateMap(map, part) {
|
|
67
|
+
const invalid = field => badMap(`app/maps/${part}.json has a missing or malformed ${field} field.`);
|
|
68
|
+
const required = (value, fields, parent) => {
|
|
69
|
+
if (!plain(value)) invalid(parent);
|
|
70
|
+
for (const field of fields) if (!Object.hasOwn(value, field)) invalid(`${parent}.${field}`);
|
|
71
|
+
};
|
|
72
|
+
required(map, ['schema_version', 'name', 'initial_screen', 'initial_route', 'initial_state', 'state_schema', 'synthetic', 'screens', 'router', 'routes', 'handlers', 'stylesheets'], 'map');
|
|
73
|
+
const supported=new Set(['schema_version','name','initial_screen','initial_route','initial_state','state_schema','synthetic','screens','router','routes','handlers','stylesheets']);
|
|
74
|
+
for(const key of Object.keys(map))if(!supported.has(key))badMap(`app/maps/${part}.json: unsupported composition field ${key}; preserve it in a standalone Simulator.`);
|
|
75
|
+
if (map.schema_version !== 'prompt-runtime.app-map.v1') invalid('schema_version');
|
|
76
|
+
for (const field of ['name', 'initial_screen']) if (typeof map[field] !== 'string' || !map[field]) invalid(field);
|
|
77
|
+
if (map.initial_route !== null && typeof map.initial_route !== 'string') invalid('initial_route');
|
|
78
|
+
if (typeof map.synthetic !== 'boolean') invalid('synthetic');
|
|
79
|
+
for (const field of ['initial_state', 'state_schema']) if (!plain(map[field])) invalid(field);
|
|
80
|
+
for (const field of ['screens', 'routes', 'handlers', 'stylesheets']) if (!Array.isArray(map[field])) invalid(field);
|
|
81
|
+
for (const screen of map.screens) {
|
|
82
|
+
required(screen, ['id', 'prompt_path', 'operation', 'source', 'format', 'input', 'result_pointer'], 'screen');
|
|
83
|
+
if (typeof screen.prompt_path !== 'string' || !screen.prompt_path) invalid('screen.prompt_path');
|
|
84
|
+
if (!['operation', 'mockup'].includes(screen.source)) invalid('screen.source');
|
|
85
|
+
if (screen.source === 'mockup') {
|
|
86
|
+
if (screen.operation !== null) invalid('screen.operation');
|
|
87
|
+
if (screen.format !== 'svg') invalid('screen.format');
|
|
88
|
+
if (screen.result_pointer !== null) invalid('screen.result_pointer');
|
|
89
|
+
} else {
|
|
90
|
+
if (typeof screen.operation !== 'string' || !screen.operation) invalid('screen.operation');
|
|
91
|
+
if (!['html', 'text', 'grid'].includes(screen.format)) invalid('screen.format');
|
|
92
|
+
if (typeof screen.result_pointer !== 'string' || !/^(?:\/(?:[^~]|~[01])*)?$/.test(screen.result_pointer)) invalid('screen.result_pointer');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
if (map.router !== null) required(map.router, ['handler', 'input', 'result_pointer'], 'router');
|
|
96
|
+
for (const route of map.routes) required(route, ['name', 'screen', 'input'], 'route');
|
|
97
|
+
for (const handler of map.handlers) {
|
|
98
|
+
required(handler, ['screen', 'kind', 'match', 'handler', 'input', 'next', 'state'], 'handler');
|
|
99
|
+
required(handler.next, ['kind', 'screen', 'route_pointer'], 'handler.next');
|
|
100
|
+
if (!plain(handler.match)) invalid('handler.match');
|
|
101
|
+
if (Object.hasOwn(handler, 'after') && !Array.isArray(handler.after)) invalid('handler.after');
|
|
102
|
+
for (const after of handler.after ?? []) required(after, ['handler', 'input', 'bind'], 'handler.after');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function joinMaps(product, parts, maps, chain, encode, selectedParts) {
|
|
107
|
+
maps.forEach((map, index) => validateMap(map, parts[index]));
|
|
108
|
+
let scratch = 'product_after';
|
|
109
|
+
while (selectedParts.includes(scratch)) scratch += '_';
|
|
110
|
+
const slots = Object.fromEntries(chain.map((operation, index) => [String(index), operation.resultSchema === null
|
|
111
|
+
? {}
|
|
112
|
+
: checkInput(null, operation.resultSchema, 0).refusals.length
|
|
113
|
+
? { oneOf: [{ type: 'null' }, operation.resultSchema] } : operation.resultSchema]));
|
|
114
|
+
const initial = Object.fromEntries(parts.map((part, index) => [part, maps[index].initial_state]));
|
|
115
|
+
const properties = Object.fromEntries(parts.map((part, index) => [part, maps[index].state_schema]));
|
|
116
|
+
if (chain.length) {
|
|
117
|
+
initial[scratch] = Object.fromEntries(chain.map((_operation, index) => [String(index), null]));
|
|
118
|
+
properties[scratch] = { type: 'object', properties: slots, required: Object.keys(slots), additionalProperties: false };
|
|
119
|
+
}
|
|
120
|
+
const stateKeys = Object.keys(initial);
|
|
121
|
+
const allScreens = maps.flatMap((map, index) => (Array.isArray(map.screens) ? map.screens : []).map(screen => `${parts[index]}/${screen.id}`));
|
|
122
|
+
const globalIds = new Set(allScreens);
|
|
123
|
+
if (globalIds.size !== allScreens.length) badMap('Selected parts produce duplicate qualified screen IDs.');
|
|
124
|
+
const joined = { schema_version: 'prompt-runtime.app-map.v1', name: product.name,
|
|
125
|
+
initial_screen: `${parts[0]}/${maps[0].initial_screen}`, initial_route: maps[0].initial_route,
|
|
126
|
+
initial_state: initial, state_schema: { type: 'object', properties, required: stateKeys, additionalProperties: false },
|
|
127
|
+
synthetic: maps.some(map => map.synthetic === true), screens: [], router: null, routes: [], handlers: [], stylesheets: [] };
|
|
128
|
+
const labels = [], routers = [], routes = new Map();
|
|
129
|
+
let tapOperations = 0;
|
|
130
|
+
for (const [index, map] of maps.entries()) {
|
|
131
|
+
const part = parts[index], screenId = id => `${part}/${id}`;
|
|
132
|
+
if (map.schema_version !== joined.schema_version || !Array.isArray(map.screens) || !Array.isArray(map.handlers)
|
|
133
|
+
|| !Array.isArray(map.stylesheets) || !Array.isArray(map.routes) || !Object.hasOwn(map, 'initial_state') || !plain(map.state_schema)) badMap(`app/maps/${part}.json is not a complete v1 map.`);
|
|
134
|
+
const ids = new Set();
|
|
135
|
+
for (const screen of map.screens) {
|
|
136
|
+
if (!plain(screen) || Object.keys(screen).sort().join(',') !== 'format,id,input,operation,prompt_path,result_pointer,source'
|
|
137
|
+
|| typeof screen.id !== 'string' || !screen.id || ids.has(screen.id)) badMap(`app/maps/${part}.json has an invalid or duplicate screen ID.`);
|
|
138
|
+
ids.add(screen.id);
|
|
139
|
+
joined.screens.push({ ...screen, id: screenId(screen.id), input: scopeTemplate(screen.input, part) });
|
|
140
|
+
labels.push({ id: screenId(screen.id), title: `${part} · ${screen.id}` });
|
|
141
|
+
}
|
|
142
|
+
if (!ids.has(map.initial_screen)) badMap(`app/maps/${part}.json has an unknown initial screen.`);
|
|
143
|
+
routers.push(map.router === null ? null : scopeTemplate(map.router, part));
|
|
144
|
+
for (const route of map.routes) {
|
|
145
|
+
const scoped = { ...route, screen: screenId(route.screen), input: scopeTemplate(route.input, part) };
|
|
146
|
+
if (!ids.has(route.screen)) badMap(`app/maps/${part}.json has an unknown route screen.`);
|
|
147
|
+
if (routes.has(route.name) && encode(routes.get(route.name)) !== encode(scoped)) fail('unsupported-product-router', `Route ${route.name} selects different part screens.`);
|
|
148
|
+
routes.set(route.name, scoped);
|
|
149
|
+
}
|
|
150
|
+
for (const handler of map.handlers) if (handler.screen !== '*' && !ids.has(handler.screen)) badMap(`app/maps/${part}.json has an unknown handler screen.`);
|
|
151
|
+
for (const target of ids) {
|
|
152
|
+
for (const handler of scopedHandlers(map.handlers, target, encode)) {
|
|
153
|
+
const next = { ...handler.next };
|
|
154
|
+
if (next.screen !== null && next.screen !== undefined) {
|
|
155
|
+
if (ids.has(next.screen)) next.screen = screenId(next.screen);
|
|
156
|
+
else if (!globalIds.has(next.screen)) badMap(`app/maps/${part}.json: next screen ${next.screen} is neither local nor a screen in the selected product parts.`);
|
|
157
|
+
}
|
|
158
|
+
const after = (handler.after ?? []).map(operation => {
|
|
159
|
+
if (typeof operation.bind !== 'string' || !operation.bind.startsWith('/')) badMap(`app/maps/${part}.json has an invalid after binding.`);
|
|
160
|
+
return { ...operation, input: scopeTemplate(operation.input, part), bind: `/${escape(part)}${operation.bind}` };
|
|
161
|
+
});
|
|
162
|
+
if (handler.handler !== null && handler.handler !== undefined) {
|
|
163
|
+
for (const [offset, operation] of chain.entries()) after.push({ handler: operation.handler, input: {}, bind: `/${escape(scratch)}/${offset}` });
|
|
164
|
+
if (after.length > 8) badMap(`app/maps/${part}.json needs ${after.length} after operations; the PDD interpreter limit is 8 (40 total calls per tap).`);
|
|
165
|
+
tapOperations = Math.max(tapOperations, 1 + after.length);
|
|
166
|
+
}
|
|
167
|
+
const state = handler.state === null || handler.state === undefined ? null : Object.fromEntries(stateKeys.map(key => [key,
|
|
168
|
+
key === part ? scopeTemplate(handler.state, part) : ref(`/state/${escape(key)}`)]));
|
|
169
|
+
joined.handlers.push({ ...handler, screen: screenId(target), input: scopeTemplate(handler.input, part), next, state, ...(Object.hasOwn(handler, 'after') || after.length ? { after } : {}) });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
for (const stylesheet of map.stylesheets) if (!joined.stylesheets.includes(stylesheet)) joined.stylesheets.push(stylesheet);
|
|
173
|
+
}
|
|
174
|
+
if (routers.some(router => router !== null)) {
|
|
175
|
+
if (routers.some(router => router === null) || routers.some(router => encode(router) !== encode(routers[0]))) fail('unsupported-product-router', 'Selected maps require incompatible routers; the PDD interpreter has one router slot.');
|
|
176
|
+
joined.router = routers[0];
|
|
177
|
+
}
|
|
178
|
+
joined.routes = [...routes.values()];
|
|
179
|
+
return { map: joined, labels, tapOperations };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function selectJourneys(tests, selector, ports = {}) {
|
|
183
|
+
if (typeof ports?.selectTests !== 'function') {
|
|
184
|
+
throw Object.assign(new Error('Product composition port (selectTests) is not bound.'), { unboundPort: true });
|
|
185
|
+
}
|
|
186
|
+
const candidates = tests.filter(test => /^user_stories\/journeys\/[^/]+\.md$/.test(test.storyPath));
|
|
187
|
+
if (selector === undefined) return candidates.map(test => test.testPath);
|
|
188
|
+
const records = candidates.map(test => ({ ...test, path: test.testPath }));
|
|
189
|
+
const exactPaths = records.filter(test => test.testPath === selector || test.storyPath === selector).map(test => test.testPath);
|
|
190
|
+
const exact = exactPaths.length ? ports.selectTests({ tests: records }, exactPaths).selected : [];
|
|
191
|
+
const matches = exact.length ? exact : records.filter(test => {
|
|
192
|
+
const name = basename(test.storyPath, '.md');
|
|
193
|
+
return name === selector || name.startsWith(`${selector}-`) || name.startsWith(`${selector}.`);
|
|
194
|
+
});
|
|
195
|
+
if (new Set(matches.map(test => test.storyPath)).size !== 1) {
|
|
196
|
+
fail('invalid-journey', `${matches.length ? 'Ambiguous' : 'Unknown'} journey ${selector}. Candidates: ${[...new Set(candidates.map(test => test.storyPath))].join(', ') || 'none'}.`);
|
|
197
|
+
}
|
|
198
|
+
return matches.map(test => test.testPath);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function composeProductTry({ root, parts, journey, testPath }, ports) {
|
|
202
|
+
if (typeof ports?.parseProductDocuments !== 'function' || typeof ports?.parseProductWorldWriters !== 'function') {
|
|
203
|
+
throw Object.assign(new Error('Product composition ports (parseProductDocuments, parseProductWorldWriters) are not bound.'), { unboundPort: true });
|
|
204
|
+
}
|
|
205
|
+
const cached = new Map();
|
|
206
|
+
const read = (path, optional = false) => {
|
|
207
|
+
if (cached.has(path)) return cached.get(path);
|
|
208
|
+
const stat = ports.statFile(join(root, path));
|
|
209
|
+
if (stat?.is_symlink) throw new PreflightError(4, `${path}: symbolic links are not allowed.`);
|
|
210
|
+
if (!stat || typeof stat.exists !== 'boolean') throw new PreflightError(4, `${path}: source file could not be inspected.`);
|
|
211
|
+
if (!stat.exists) { if (optional) return null; badMap(`${path}: required source file is missing.`); }
|
|
212
|
+
const value = ports.readFile(join(root, path));
|
|
213
|
+
const text = typeof value === 'string' ? value : Buffer.isBuffer(value) ? value.toString('utf8') : null;
|
|
214
|
+
if (text === null) badMap(`${path}: the file reader did not return UTF-8 bytes.`);
|
|
215
|
+
cached.set(path, text); return text;
|
|
216
|
+
};
|
|
217
|
+
const files = {
|
|
218
|
+
stat({ path }) { return ports.statFile(join(root, path)); },
|
|
219
|
+
read({ path }) { return { content: read(path) }; },
|
|
220
|
+
};
|
|
221
|
+
try {
|
|
222
|
+
const mapText = read('product/map.md'), planText = read('product/plan.md', true) ?? '';
|
|
223
|
+
const { product } = ports.parseProductDocuments({ mapText, planText });
|
|
224
|
+
const selected = parts === undefined ? product.parts.map(part => part.part) : [...parts];
|
|
225
|
+
if (!selected.length || new Set(selected).size !== selected.length || selected.some(part => !product.parts.some(row => row.part === part))) {
|
|
226
|
+
fail('invalid-product', `Choose distinct product parts from: ${product.parts.map(part => part.part).join(', ')}.`);
|
|
227
|
+
}
|
|
228
|
+
const writers = new Map();
|
|
229
|
+
for (const { key, writer } of ports.parseProductWorldWriters({ worldText: read('contracts/world.md', true) ?? '' })) {
|
|
230
|
+
if (writers.has(key) && writers.get(key) !== writer) fail('world-writer-conflict', `${key} is written by ${writers.get(key)} and ${writer}.`);
|
|
231
|
+
writers.set(key, writer);
|
|
232
|
+
}
|
|
233
|
+
const parseWorld = path => {
|
|
234
|
+
const expanded = expandSource({ path, text: JSON.stringify({ initial_world: { $seed: path } }), format: 'scenario' }, files);
|
|
235
|
+
return parseJsonValue(expanded.text).initial_world;
|
|
236
|
+
};
|
|
237
|
+
let world = read('contracts/seed-world.json', true) === null ? {} : parseWorld('contracts/seed-world.json');
|
|
238
|
+
const contributions = new Map();
|
|
239
|
+
for (const part of selected) {
|
|
240
|
+
const path = `prompts/${part}/seed.json`;
|
|
241
|
+
if (read(path, true) === null) continue;
|
|
242
|
+
const value = parseWorld(path);
|
|
243
|
+
for (const key of Object.keys(value)) {
|
|
244
|
+
if (contributions.has(key) && contributions.get(key) !== part) fail('world-writer-conflict', `${key} is seeded by ${contributions.get(key)} and ${part}.`);
|
|
245
|
+
if (writers.has(key) && writers.get(key) !== part) fail('world-writer-conflict', `${key} is written by ${writers.get(key)}, not seed part ${part}.`);
|
|
246
|
+
contributions.set(key, part);
|
|
247
|
+
}
|
|
248
|
+
world = Object.fromEntries([...Object.entries(world), ...Object.entries(value)]);
|
|
249
|
+
}
|
|
250
|
+
let appMapPath, seedPath;
|
|
251
|
+
for (let suffix = 0; ; suffix++) {
|
|
252
|
+
const tag = suffix ? `_${suffix}` : '';
|
|
253
|
+
appMapPath = `app/maps/product${tag}.json`;
|
|
254
|
+
seedPath = `contracts/product-seed${tag}.json`;
|
|
255
|
+
const mapStat = ports.statFile(join(root, appMapPath), {presenceOnly:true}), seedStat = ports.statFile(join(root, seedPath), {presenceOnly:true});
|
|
256
|
+
if (mapStat?.is_symlink || seedStat?.is_symlink) throw new PreflightError(4, 'Generated product paths must not be symbolic links.');
|
|
257
|
+
if (!mapStat || !seedStat || typeof mapStat.exists !== 'boolean' || typeof seedStat.exists !== 'boolean') throw new PreflightError(4, 'Generated product paths could not be inspected.');
|
|
258
|
+
if (!mapStat.exists && !seedStat.exists) break;
|
|
259
|
+
}
|
|
260
|
+
if (journey !== undefined) {
|
|
261
|
+
if (typeof testPath !== 'string' || !testPath) fail('invalid-journey', 'Choose one journey test path for this Try.');
|
|
262
|
+
const raw = read(testPath), scenario = parseJsonValue(raw);
|
|
263
|
+
selectJourneys([{ testPath, storyPath: scenario.story_path }], journey, ports);
|
|
264
|
+
if (!plain(scenario.initial_world)) fail('invalid-journey', `${testPath}: initial_world must be an object.`);
|
|
265
|
+
// Validate its ordinary standalone seed/reference before using only its set.
|
|
266
|
+
expandSource({ path: testPath, text: raw, format: 'scenario' }, files);
|
|
267
|
+
if (Object.hasOwn(scenario.initial_world, '$seed')) {
|
|
268
|
+
const base = stringifyJsonValue(world), overlay = { ...files,
|
|
269
|
+
stat: input => input.path === seedPath ? { exists: true, is_symlink: false, size: Buffer.byteLength(base) } : files.stat(input),
|
|
270
|
+
read: input => input.path === seedPath ? { content: base } : files.read(input) };
|
|
271
|
+
const initial_world = { $seed: seedPath, ...(Object.hasOwn(scenario.initial_world, 'set') ? { set: scenario.initial_world.set } : {}) };
|
|
272
|
+
world = parseJsonValue(expandSource({ path: testPath, text: stringifyJsonValue({ initial_world }), format: 'scenario' }, overlay).text).initial_world;
|
|
273
|
+
} else world = Object.fromEntries([...Object.entries(world), ...Object.entries(scenario.initial_world)]);
|
|
274
|
+
}
|
|
275
|
+
const afterSection = planText.split(/^##\s+/m).find(section => section.split(/\r?\n/, 1)[0].trim() === 'After every tap');
|
|
276
|
+
const chain = [];
|
|
277
|
+
for (const line of afterSection?.split(/\r?\n/).slice(1) ?? []) {
|
|
278
|
+
const item = /^\s*\d+[.)]\s+`?(.+?\.prompt\.md)#([^\s`#]+)`?\s*$/.exec(line);
|
|
279
|
+
if (!item) { if (/^\s*\d+[.)]/.test(line)) badMap(`Invalid After every tap operation: ${line.trim()}`); continue; }
|
|
280
|
+
const handler = { prompt_path: item[1], operation: item[2] };
|
|
281
|
+
const expanded = expandSource({ path: handler.prompt_path, text: read(handler.prompt_path), format: 'prompt' }, files);
|
|
282
|
+
const blocks = interfaceBlocks(expanded.text);
|
|
283
|
+
if (blocks.length > 1) badMap(`${handler.prompt_path}: expected at most one Runtime interface for ${handler.operation}.`);
|
|
284
|
+
if (!blocks.length) {
|
|
285
|
+
const fm = parsePromptFrontmatter(expanded.text);
|
|
286
|
+
if (fm.error) badMap(`${handler.prompt_path}: invalid prompt frontmatter (${fm.error}).`);
|
|
287
|
+
if (fm.kind === 'native-only') badMap(`${handler.prompt_path}: native-only prompt cannot run After every tap.`);
|
|
288
|
+
chain.push({ handler, resultSchema: null });
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const entry = parseJsonValue(blocks[0][1]).entries?.find(operation => operation.operation === handler.operation);
|
|
292
|
+
if (!entry || !plain(entry.result_schema)) badMap(`${handler.prompt_path}: missing operation/result schema ${handler.operation}.`);
|
|
293
|
+
chain.push({ handler, resultSchema: entry.result_schema });
|
|
294
|
+
}
|
|
295
|
+
const mapped = selected.flatMap(part => {
|
|
296
|
+
const text = read(`app/maps/${part}.json`, true);
|
|
297
|
+
return text === null ? [] : [{ part, map: parseJsonValue(text) }];
|
|
298
|
+
});
|
|
299
|
+
if (!mapped.length) badMap('No screen is available: the selected product parts have no app map; Runtime v1 requires an initial screen.');
|
|
300
|
+
const joined = joinMaps(product, mapped.map(item => item.part), mapped.map(item => item.map), chain, stringifyJsonValue, selected);
|
|
301
|
+
const paths = [...new Set([
|
|
302
|
+
...joined.map.screens.map(screen=>screen.prompt_path),
|
|
303
|
+
...(joined.map.router ? [joined.map.router.handler.prompt_path] : []),
|
|
304
|
+
...joined.map.handlers.flatMap(rule=>[...(rule.handler ? [rule.handler.prompt_path] : []), ...(rule.after??[]).map(step=>step.handler.prompt_path)])
|
|
305
|
+
])];
|
|
306
|
+
const product_parts = selected.map(name=>({name,prompt_paths:[]}));
|
|
307
|
+
for (const path of paths) {
|
|
308
|
+
const owners = selected.filter(name=>{const folder=product.parts.find(part=>part.part===name).folder.replace(/\/$/,'');return path===folder || path.startsWith(folder+'/');});
|
|
309
|
+
if (owners.length > 1) badMap(`Ambiguous product owner for ${path}.`);
|
|
310
|
+
if (owners.length) product_parts.find(part=>part.name===owners[0]).prompt_paths.push(path);
|
|
311
|
+
}
|
|
312
|
+
return { appMapPath, seedPath, files: [{ path: appMapPath, content: stringifyJsonValue(joined.map) }, { path: seedPath, content: stringifyJsonValue(world) }],
|
|
313
|
+
product_parts, parts: selected, journey: journey ?? null, tapOperations: joined.tapOperations, labels: joined.labels };
|
|
314
|
+
} catch (error) {
|
|
315
|
+
if (error?.unboundPort) throw error;
|
|
316
|
+
if (error.exitCode || ['invalid-product', 'invalid-journey', 'world-writer-conflict', 'invalid-product-map', 'unsupported-product-router'].includes(error.code) || /^(?:contract-|seed-)/.test(error.code ?? '')) throw error;
|
|
317
|
+
badMap(`Cannot compose this product Try: ${error.message}`);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// Setup-only validation: pure assembly may inspect partial fixtures, but no upload
|
|
322
|
+
// is allowed until all executable source has supplied a bounded graph.
|
|
323
|
+
export function productTapCallBound(map, {root, readFile, statFile}) {
|
|
324
|
+
const read = path => {
|
|
325
|
+
const full=join(root,path), stat=statFile(full);
|
|
326
|
+
if(!stat?.exists || stat.is_symlink)badMap(`Cannot bound product operation: ${path} is unavailable.`);
|
|
327
|
+
return String(readFile(full));
|
|
328
|
+
};
|
|
329
|
+
const files={stat:({path})=>statFile(join(root,path)),read:({path})=>({content:read(path)})};
|
|
330
|
+
const visible={has:path=>{const st=statFile(join(root,path));return !!st?.exists && !st?.is_symlink;}};
|
|
331
|
+
// Same acyclic caller/child/resume recurrence as Runtime's declared graph bound.
|
|
332
|
+
const costs = new Map(), visiting = new Set();
|
|
333
|
+
const cost = reference => {
|
|
334
|
+
const key=reference.prompt_path+'#'+reference.operation;
|
|
335
|
+
if(costs.has(key))return costs.get(key);
|
|
336
|
+
if(visiting.has(key) || visiting.has(reference.prompt_path+'#*'))badMap(`Cannot bound recursive product operation ${key}.`);
|
|
337
|
+
const expanded=expandSource({path:reference.prompt_path,text:read(reference.prompt_path),format:'prompt'},files);
|
|
338
|
+
const blocks=interfaceBlocks(expanded.text);
|
|
339
|
+
if(blocks.length>1)badMap(`Cannot bound ${key}: at most one interface is allowed.`);
|
|
340
|
+
if(!blocks.length) {
|
|
341
|
+
const fm=parsePromptFrontmatter(expanded.text);
|
|
342
|
+
if(fm.error)badMap(`Cannot bound product operation ${key}: invalid prompt frontmatter (${fm.error}).`);
|
|
343
|
+
if(fm.kind==='native-only')badMap(`Cannot bound native-only product operation ${key}.`);
|
|
344
|
+
const plainKey=reference.prompt_path+'#*';
|
|
345
|
+
if(costs.has(plainKey))return costs.get(plainKey);
|
|
346
|
+
if(visiting.has(plainKey))badMap(`Cannot bound recursive product operation ${key}.`);
|
|
347
|
+
visiting.add(plainKey);
|
|
348
|
+
let bound=1;
|
|
349
|
+
for(const target of promptMarkdownTargets(expanded.text,reference.prompt_path,visible)) {
|
|
350
|
+
bound+=cost({prompt_path:target,operation:'*'})+1;
|
|
351
|
+
if(bound>40)break;
|
|
352
|
+
}
|
|
353
|
+
visiting.delete(plainKey);costs.set(plainKey,bound);costs.set(key,bound);return bound;
|
|
354
|
+
}
|
|
355
|
+
visiting.add(key);
|
|
356
|
+
const iface=parseJsonValue(blocks[0][1]);
|
|
357
|
+
if(reference.operation!=='*' && !iface.entries?.some(entry=>entry.operation===reference.operation))badMap(`Unknown product operation ${key}.`);
|
|
358
|
+
let bound=1;
|
|
359
|
+
for(const call of iface.calls??[]) {
|
|
360
|
+
const count=Number(isJsonNumber(call.max_calls)?call.max_calls.text:call.max_calls);
|
|
361
|
+
if(!Number.isSafeInteger(count)||count<1||typeof call.target!=='string'||typeof call.target_operation!=='string')badMap(`Cannot bound call in ${key}.`);
|
|
362
|
+
bound+=count*(cost({prompt_path:call.target,operation:call.target_operation})+1);
|
|
363
|
+
if(bound>40)break;
|
|
364
|
+
}
|
|
365
|
+
const declared=iface.limits?.max_model_calls;
|
|
366
|
+
if(declared!==undefined){const cap=Number(isJsonNumber(declared)?declared.text:declared);if(!Number.isSafeInteger(cap)||cap<1)badMap(`Cannot bound provider allowance for ${key}.`);bound=Math.max(bound,cap);}
|
|
367
|
+
else if((iface.resources??[]).length)badMap(`Cannot bound resource continuations for ${key} without a provider allowance.`);
|
|
368
|
+
visiting.delete(key);costs.set(key,bound);return bound;
|
|
369
|
+
};
|
|
370
|
+
let maxTapCalls=0;
|
|
371
|
+
for(const rule of map.handlers) {
|
|
372
|
+
let bound=(rule.handler?cost(rule.handler):0)+(rule.after??[]).reduce((sum,step)=>sum+cost(step.handler),0);
|
|
373
|
+
let destinations;
|
|
374
|
+
if(rule.next.kind==='screen')destinations=map.screens.filter(screen=>screen.id===rule.next.screen);
|
|
375
|
+
else if(rule.next.kind==='same')destinations=map.screens.filter(screen=>screen.id===rule.screen);
|
|
376
|
+
else destinations=map.screens;
|
|
377
|
+
bound+=Math.max(0,...destinations.map(screen=>screen.source==='mockup'?1:cost(screen)));
|
|
378
|
+
// A dynamic router also evaluates before destination drawing.
|
|
379
|
+
if(rule.next.kind==='route' && map.router)bound+=cost(map.router.handler);
|
|
380
|
+
if(bound>40)badMap(`One product tap may need ${bound} AI calls; the limit is 40. Shorten the background chain or declared calls.`);
|
|
381
|
+
maxTapCalls=Math.max(maxTapCalls,bound);
|
|
382
|
+
}
|
|
383
|
+
return maxTapCalls;
|
|
384
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Generated from prompts/cli/runtime-binding-plan.prompt.md (sha256: 667d9ad0ad59e95258aac6c32665398d28642416fc95d7132d7349eba65abd60).
|
|
2
|
+
|
|
3
|
+
const rows = value => Array.isArray(value) ? value : [];
|
|
4
|
+
const stepSimulation = (base, overrides) => {
|
|
5
|
+
const result = { ...(base ?? {}) };
|
|
6
|
+
if (Array.isArray(overrides)) {
|
|
7
|
+
for (const row of overrides) {
|
|
8
|
+
if (row && typeof row === 'object' && !Array.isArray(row) && typeof row.operation === 'string' && row.operation) {
|
|
9
|
+
result[row.operation] = row.binding;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
} else if (overrides && typeof overrides === 'object') {
|
|
13
|
+
Object.assign(result, overrides);
|
|
14
|
+
}
|
|
15
|
+
return result;
|
|
16
|
+
};
|
|
17
|
+
const selectedResources = (iface, operation) => {
|
|
18
|
+
const entries = rows(iface?.entries), selected = entries.filter(entry => entry?.operation === operation);
|
|
19
|
+
const declared = new Set(rows(iface?.resources).flatMap(resource => rows(resource?.operations)
|
|
20
|
+
.map(member => `${resource.name}.${member?.name}`)));
|
|
21
|
+
if (selected.length !== 1 || entries.some(entry => typeof entry?.operation !== 'string' || !entry.operation)
|
|
22
|
+
|| new Set(entries.map(entry => entry.operation)).size !== entries.length
|
|
23
|
+
|| !entries.every(entry => Array.isArray(entry?.resource_operations)
|
|
24
|
+
&& entry.resource_operations.every(name => typeof name === 'string' && declared.has(name))
|
|
25
|
+
&& new Set(entry.resource_operations).size === entry.resource_operations.length)) return null;
|
|
26
|
+
if (new Set(entries.flatMap(entry => entry.resource_operations)).size !== declared.size) return null;
|
|
27
|
+
return new Set(selected[0].resource_operations);
|
|
28
|
+
};
|
|
29
|
+
const boundaryNote = (notes, reason) => {
|
|
30
|
+
notes.push({code:'boundary-not-applied',reason,message:reason === 'legacy-syntax'
|
|
31
|
+
? 'boundary not applied: use the pdd-boundary block'
|
|
32
|
+
: `boundary not applied: ${reason === 'unsupported-line-ends' ? 'unsupported line ends' : reason}; full dependency closure is required`});
|
|
33
|
+
return null;
|
|
34
|
+
};
|
|
35
|
+
export function runtimeBoundary(storyPath, text, {notes=[]}={}) {
|
|
36
|
+
// Scope removal needs unambiguous line boundaries throughout the Story.
|
|
37
|
+
// Do not normalize unsupported separators into apparent top-level authority.
|
|
38
|
+
if (/\r(?!\n)|[\v\f\u001c-\u001e\u0085\u2028\u2029]/u.test(text)) {
|
|
39
|
+
return boundaryNote(notes,'unsupported-line-ends');
|
|
40
|
+
}
|
|
41
|
+
const lines = text.split(/\r?\n/);
|
|
42
|
+
// Admission is deliberately stricter than Markdown discovery. Count even
|
|
43
|
+
// unsupported/example markers so uncertain declarations never yield a subset.
|
|
44
|
+
const markers = lines.flatMap((line,index)=>/[`~]{3,}[ \t]*pdd-boundary\b/.test(line) ? [index] : []);
|
|
45
|
+
if (!markers.length) return boundaryNote(notes,/runtime boundary/i.test(text) ? 'legacy-syntax' : 'missing-block');
|
|
46
|
+
if (markers.length !== 1) return boundaryNote(notes,'duplicate-blocks');
|
|
47
|
+
const start = markers[0];
|
|
48
|
+
let fence = null, uncertain = false;
|
|
49
|
+
for (let index=0;index<start;index++) {
|
|
50
|
+
const line=lines[index], match=line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
|
|
51
|
+
if (fence) {
|
|
52
|
+
if (match && match[1][0] === fence.char && match[1].length >= fence.length && !match[2].trim()) fence=null;
|
|
53
|
+
} else if (match) fence={char:match[1][0],length:match[1].length};
|
|
54
|
+
else if (/<(?:[!?]|\/?[A-Za-z])/.test(line)) uncertain=true;
|
|
55
|
+
}
|
|
56
|
+
const end=lines.indexOf('```',start+1);
|
|
57
|
+
if (lines[start] !== '```pdd-boundary' || fence || uncertain || end < 0
|
|
58
|
+
|| start > 0 && lines[start-1].trim() || end+1 < lines.length && lines[end+1].trim()) {
|
|
59
|
+
return boundaryNote(notes,'unsupported-syntax');
|
|
60
|
+
}
|
|
61
|
+
// Reject HTML after the block too: an enclosing/raw example is not authority.
|
|
62
|
+
if (/<(?:[!?]|\/?[A-Za-z])/.test(lines.slice(end+1).join('\n'))) return boundaryNote(notes,'unsupported-syntax');
|
|
63
|
+
const paths=lines.slice(start+1,end);
|
|
64
|
+
if (!paths.length || paths.some(path=>!/^[A-Za-z0-9_./-]+\.prompt\.md$/.test(path)
|
|
65
|
+
|| path.split('/').some(part=>!part || part==='.' || part==='..'))) return boundaryNote(notes,'invalid-path');
|
|
66
|
+
if (/runtime boundary/i.test(text)) boundaryNote(notes,'legacy-syntax');
|
|
67
|
+
return [...new Set(paths)].sort();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function buildBindingPlan({test, storyText, prompts, dependencyPaths=[], boundaryState}) {
|
|
71
|
+
const notes=[];
|
|
72
|
+
const boundary = boundaryState ? boundaryState.boundary : runtimeBoundary(test.storyPath,storyText,{notes});
|
|
73
|
+
if (boundaryState) notes.push(...boundaryState.notes);
|
|
74
|
+
const steps = [], edges = [], problems = [];
|
|
75
|
+
const allowed = path => boundary === null || boundary.includes(path);
|
|
76
|
+
for (const step of rows(test.doc?.steps)) {
|
|
77
|
+
if (!step || typeof step.entry_path !== 'string') continue;
|
|
78
|
+
const closure = new Set(), pending = [step.entry_path, ...(boundary ?? dependencyPaths)];
|
|
79
|
+
for (let index = 0; index < pending.length; index++) {
|
|
80
|
+
const path = pending[index];
|
|
81
|
+
if (closure.has(path)) continue;
|
|
82
|
+
closure.add(path);
|
|
83
|
+
if (!allowed(path)) { problems.push({step_id:step.step_id,prompt_path:path,code:'out-of-boundary'}); continue; }
|
|
84
|
+
const iface = prompts.get(path);
|
|
85
|
+
if (!iface) { problems.push({step_id:step.step_id,prompt_path:path,code:'interface-unavailable'}); continue; }
|
|
86
|
+
for (const call of rows(iface.calls)) if (typeof call?.target==='string') pending.push(call.target);
|
|
87
|
+
}
|
|
88
|
+
steps.push({step_id:step.step_id,closure:[...closure].sort()});
|
|
89
|
+
const simulation = stepSimulation(test.doc.simulation, step.simulation_overrides);
|
|
90
|
+
const otherEntryCall = [...closure].some(path => rows(prompts.get(path)?.calls).some(call =>
|
|
91
|
+
call?.target === step.entry_path && call.target_operation !== step.operation));
|
|
92
|
+
const active = otherEntryCall ? null : selectedResources(prompts.get(step.entry_path), step.operation);
|
|
93
|
+
for (const path of [...closure].sort()) {
|
|
94
|
+
if (!allowed(path)) continue;
|
|
95
|
+
for (const resource of rows(prompts.get(path)?.resources)) for (const operation of rows(resource?.operations)) {
|
|
96
|
+
if (typeof resource?.name !== 'string' || typeof operation?.name !== 'string') continue;
|
|
97
|
+
const key = `${resource.name}.${operation.name}`, candidates = [];
|
|
98
|
+
if (path === step.entry_path && active !== null && !active.has(key)) continue;
|
|
99
|
+
for (const [name,binding] of Object.entries(simulation)) {
|
|
100
|
+
const split = name.lastIndexOf('.'), resourceName = name.slice(0,split), operationName = name.slice(split+1);
|
|
101
|
+
const cause = resourceName !== resource.name ? 'wrong-name' : operationName !== operation.name ? 'wrong-operation'
|
|
102
|
+
: !binding || typeof binding !== 'object' || binding.action === 'fixture.lookup' && (!Array.isArray(binding.cases) || !binding.cases.length) ? 'invalid-fixture' : 'selected';
|
|
103
|
+
candidates.push({kind:'simulation',name,cause});
|
|
104
|
+
}
|
|
105
|
+
for (const [candidate,iface] of prompts) for (const entry of rows(iface?.entries)) {
|
|
106
|
+
if (!entry) continue;
|
|
107
|
+
if (entry.operation !== operation.name) continue;
|
|
108
|
+
candidates.push({kind:'prompt',name:`${candidate}#${entry.operation}`,
|
|
109
|
+
cause:!allowed(candidate)?'out-of-boundary':!closure.has(candidate)?'not-in-dependency-closure':'wrong-name'});
|
|
110
|
+
}
|
|
111
|
+
const internal = ['key-value','collection','blob','sql','compute'].includes(resource.kind);
|
|
112
|
+
const state = candidates.some(candidate=>candidate.cause==='selected') ? 'bound' : internal ? 'internal' : 'missing';
|
|
113
|
+
const rename = candidates.some(candidate=>candidate.kind==='simulation' && ['wrong-name','wrong-operation'].includes(candidate.cause)
|
|
114
|
+
&& (candidate.name.startsWith(`${resource.name}.`) || candidate.name.endsWith(`.${operation.name}`)));
|
|
115
|
+
const repair = state !== 'missing' ? null : rename ? `Fix the fixture name or operation to ${key}.`
|
|
116
|
+
: `Add a binding for ${key}; if this module is context only, declare the Story pdd-boundary block.`;
|
|
117
|
+
edges.push({step_id:step.step_id,prompt_path:path,resource:resource.name,operation:operation.name,key,state,candidates,repair});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return {schema_version:'pdd.binding-plan.v1',test:test.path,story:test.storyPath,boundary,notes,steps,edges,problems};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function bindingPlanLines(plan) {
|
|
125
|
+
return [`Bindings: ${plan.test}; boundary: ${plan.boundary?.join(', ') ?? 'full dependency closure'}`,
|
|
126
|
+
...plan.edges.map(edge=>`${edge.step_id}: ${edge.prompt_path}: ${edge.key}: ${edge.state}; considered: ${edge.candidates.map(candidate=>`${candidate.kind} ${candidate.name} (${candidate.cause})`).join(', ') || 'none'}${edge.repair ? `; repair: ${edge.repair}` : ''}`),
|
|
127
|
+
...(plan.notes ?? []).map(note=>`${note.code}: ${note.message}`),
|
|
128
|
+
...plan.problems.map(problem=>`${problem.step_id}: ${problem.prompt_path}: ${problem.code}; repair: correct the declared boundary or Runtime call target.`)];
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function bindingRefusals(plan, compatibility) {
|
|
132
|
+
return (compatibility?.reported?.edges ?? []).filter(edge=>edge.reason_code==='binding-missing').map(edge=>{
|
|
133
|
+
const {step_id,prompt_path}=edge.selection, key=edge.selection.edge.resource_operation;
|
|
134
|
+
const local=plan.edges.find(row=>row.step_id===step_id && row.prompt_path===prompt_path && row.key===key);
|
|
135
|
+
const closure=plan.steps.find(row=>row.step_id===step_id)?.closure ?? [];
|
|
136
|
+
const cause=plan.boundary && !plan.boundary.includes(prompt_path) ? 'out-of-boundary'
|
|
137
|
+
: !closure.includes(prompt_path) ? 'not-in-dependency-closure'
|
|
138
|
+
: local?.state==='bound' ? 'server-binding-disagreement'
|
|
139
|
+
: local?.candidates.find(candidate=>candidate.kind==='simulation' && (candidate.name.startsWith(`${local.resource}.`) || candidate.name.endsWith(`.${local.operation}`)))?.cause ?? 'binding-missing';
|
|
140
|
+
const repair=cause==='server-binding-disagreement' ? `The exact fixture ${key} is selected locally. Ask the compatibility owner to diagnose fixture selection before retrying.`
|
|
141
|
+
: ['out-of-boundary','not-in-dependency-closure'].includes(cause) ? 'Check the declared Story Runtime boundary and compatibility closure before retrying.'
|
|
142
|
+
: local?.repair ?? `Add a binding for ${key}.`;
|
|
143
|
+
return {step_id,prompt_path,key,cause,candidates:local?.candidates ?? [],repair};
|
|
144
|
+
});
|
|
145
|
+
}
|