@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.
Files changed (35) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +105 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +943 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/product-composition.mjs +384 -0
  18. package/src/runtime/runtime-binding-plan.mjs +145 -0
  19. package/src/runtime/runtime-bindings.mjs +71 -0
  20. package/src/runtime/runtime-check-plan.mjs +411 -0
  21. package/src/runtime/runtime-client.mjs +6323 -0
  22. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  23. package/src/runtime/runtime-markdown.mjs +215 -0
  24. package/src/runtime/runtime-outcome.mjs +407 -0
  25. package/src/runtime/runtime-output.mjs +714 -0
  26. package/src/runtime/runtime-preflight.mjs +3118 -0
  27. package/src/runtime/runtime-slots.mjs +391 -0
  28. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  29. package/src/runtime/runtime-workspace.mjs +52 -0
  30. package/src/runtime/scenario-json.mjs +91 -0
  31. package/src/runtime/secret-redaction.mjs +53 -0
  32. package/src/runtime/try-doors.mjs +231 -0
  33. package/src/runtime/try-http.mjs +259 -0
  34. package/src/runtime/try-mcp.mjs +223 -0
  35. package/src/runtime/try-session.mjs +95 -0
@@ -0,0 +1,71 @@
1
+ // Generated from prompts/cli/runtime-bindings.prompt.md (sha256: 9e453e809fb48b26c99653c94a4b6b8d5d58967940b6ec40b0679aeb415baa85).
2
+ import {loadRuntimeWorkspace,allowsRuntimePath} from './runtime-workspace.mjs';
3
+ import { lstatSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { PreflightError, readPrompt, promptRefusal, isSecretPath, sourceFilePort, gitFiles, promptMarkdownTargets, runtimeCoverage } from './runtime-preflight.mjs';
6
+
7
+ export function bindingCoverage({ root, found, selected, includeRuntime = false, allowMissingInterfaces = true }) {
8
+ const workspace=loadRuntimeWorkspace({root});
9
+ const controlVisible=new Set(gitFiles(root));
10
+ const runtime = includeRuntime ? {runtime:runtimeCoverage({root,allowMissingInterfaces})} : {};
11
+ const unavailable = { available: false, bound: null, total: null, modules: [], ...runtime };
12
+ const fail = (path, why) => { throw Object.assign(new PreflightError(4, `pdd-bindings.json: ${path}: ${why}`), { bindingInventory: true }); };
13
+ const regular = path => {
14
+ if (typeof path !== 'string' || !path || path.includes('\\') || path.startsWith('/') || path.split('/').some(p => !p || p === '.' || p === '..')) fail(String(path), 'use an existing repository-relative regular Git-visible path');
15
+ if (isSecretPath(path)) fail(path, 'secret-looking paths are not allowed');
16
+ let full = root;
17
+ for (const part of path.split('/')) {
18
+ full = join(full, part);
19
+ let stat; try { stat = lstatSync(full); } catch { fail(path, 'file does not exist'); }
20
+ if (stat.isSymbolicLink()) fail(path, 'symlinks are not allowed');
21
+ }
22
+ if (!lstatSync(full).isFile() || !(path==='pdd-bindings.json'?controlVisible:found.visible).has(path)) fail(path, 'must be a regular Git-visible file');
23
+ return path;
24
+ };
25
+ try { lstatSync(join(root, 'pdd-bindings.json')); } catch (error) { if (error.code === 'ENOENT') return unavailable; throw error; }
26
+ regular('pdd-bindings.json');
27
+ const files = sourceFilePort(root);
28
+ if (files.stat({path:'pdd-bindings.json'}).size > 65536) fail('inventory', 'exceeds 64 KiB');
29
+ let inventory; try { inventory = JSON.parse(files.read({path:'pdd-bindings.json'}).content); } catch { fail('inventory', 'invalid JSON'); }
30
+ const object = v => v !== null && typeof v === 'object' && !Array.isArray(v);
31
+ const keys = (v, names) => object(v) && Object.keys(v).length === names.length && names.every(k => Object.hasOwn(v, k));
32
+ if (!keys(inventory, ['schema_version', 'modules']) || inventory.schema_version !== 'pdd.bindings.v1' || !Array.isArray(inventory.modules)) fail('inventory', 'expected schema_version pdd.bindings.v1 and modules array only');
33
+ if (inventory.modules.length > 1000) fail('inventory', 'exceeds 1000 module declarations');
34
+ const stories = new Set(found.stories.map(s => s.path)), chosen = new Set(selected.map(t => t.storyPath)), seen = new Set(), modules = [];
35
+ const reached = new Set(), queue = selected.flatMap(t => (Array.isArray(t.doc?.steps) ? t.doc.steps : []).map(s => s?.entry_path));
36
+ while (queue.length) {
37
+ const path = queue.shift(); if (typeof path !== 'string' || reached.has(path)) continue;
38
+ reached.add(path);
39
+ const prompt = readPrompt(root, found.visible, path, workspace);
40
+ for (const call of Array.isArray(prompt?.interface?.calls) ? prompt.interface.calls : []) if (typeof call?.target === 'string') queue.push(call.target);
41
+ if (allowMissingInterfaces && prompt?.error === 'interface-missing') {
42
+ for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) queue.push(target);
43
+ }
44
+ }
45
+ for (const item of inventory.modules) {
46
+ const path = item?.module ?? 'module';
47
+ if (!object(item)) fail(path, 'expected module declaration');
48
+ const bound = Object.hasOwn(item, 'prompt');
49
+ if (!keys(item, bound ? ['module', 'stories', 'prompt'] : ['module', 'stories', 'reason', 'port_attempt'])) fail(path, 'declare prompt or both reason and port_attempt, with no extra fields');
50
+ if(!allowsRuntimePath(workspace,item.module))continue;
51
+ regular(item.module); if (seen.has(item.module)) fail(path, 'duplicate module'); seen.add(item.module);
52
+ if (!Array.isArray(item.stories) || (!bound && !item.stories.length) || new Set(item.stories).size !== item.stories.length) fail(path, bound ? 'stories must be an array of unique Story paths' : 'stories must be nonempty and unique');
53
+ for (const story of item.stories) { regular(story); if (!stories.has(story)) fail(path, `unknown Story ${story}`); }
54
+ if (bound) { regular(item.prompt); if (!item.prompt.endsWith('.prompt.md')) fail(path, `${item.prompt} must be a *.prompt.md file`); }
55
+ else for (const key of ['reason', 'port_attempt']) if (typeof item[key] !== 'string' || !item[key].trim()) fail(path, `${key} must be nonblank`);
56
+ if (!item.stories.some(story => chosen.has(story))) continue;
57
+ if (bound) {
58
+ const prompt = readPrompt(root, found.visible, item.prompt, workspace);
59
+ const nativeProblem = (prompt.frontmatter || prompt?.interface?.kind === 'native-only') ? promptRefusal(prompt, 'interface') : null;
60
+ if (nativeProblem) fail(path, nativeProblem.message);
61
+ if (!prompt.error && prompt?.interface?.kind === 'native-only' && typeof prompt.interface.reason === 'string' && prompt.interface.reason.trim()) {
62
+ modules.push({ path: item.module, state: 'unbound', prompt: item.prompt, reason: prompt.interface.reason.trim(), port_attempt: 'native-only prompt' });
63
+ continue;
64
+ }
65
+ const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
66
+ if (!reached.has(item.prompt) || (!lazyMissing && (prompt.error || !Array.isArray(prompt?.interface?.entries) || !prompt.interface.entries.length || prompt.interface.entries.some(entry => !entry || typeof entry.operation !== 'string' || !entry.operation.trim() || !object(entry.input_schema) || !object(entry.result_schema))))) fail(path, `${item.prompt} must be reached and have an executable Runtime interface`);
67
+ }
68
+ modules.push({ path: item.module, state: bound ? 'bound' : 'unbound', ...(bound ? {} : { reason: item.reason, port_attempt: item.port_attempt }) });
69
+ }
70
+ return { ...runtime, available: true, bound: modules.filter(m => m.state === 'bound').length, total: modules.length, modules };
71
+ }
@@ -0,0 +1,411 @@
1
+ // Generated from prompts/cli/runtime-check-plan.prompt.md (sha256: f54741480b042e2c817ad85411dab3a37a054316eb61a18b00fa4526a0c6af59).
2
+ import { spawnSync } from 'node:child_process';
3
+ import { isAbsolute, posix } from 'node:path';
4
+ import { captureSource, readPrompt, sourceFilePort, promptMarkdownTargets } from './runtime-preflight.mjs';
5
+ import { resultOutcome } from './runtime-outcome.mjs';
6
+ import { allowsRuntimePath, loadRuntimeWorkspace } from './runtime-workspace.mjs';
7
+
8
+ const HEAD = 4096, LINE = 1100;
9
+ const HEADER = /^\s*(?:\/\/+|#+|--|;+|\/\*+|\*+|<!--|"""|''')?\s*Generated from (\S+\.prompt\.md)(?: \(sha256: ([a-f0-9]{64})\))?\.?\s*(?:\*\/|-->|"""|''')?\s*$/;
10
+ const bytesOf = content => typeof content === 'string' ? Buffer.from(content, 'utf8') : content;
11
+ const decode = (content, limit) => content ? new TextDecoder().decode(bytesOf(content).subarray(0, limit)) : '';
12
+ const canonicalHeaderPath = value => typeof value === 'string' && value.trim().length > 0 && value.length <= 1000 && !isAbsolute(value)
13
+ && !/[\\\x00-\x1f\x7f]/.test(value) && !value.split('/').some(part => !part || part === '.' || part === '..' || part.toLowerCase() === '.git');
14
+ export function defaultHeaderPrompts(content) {
15
+ if (!content) return [];
16
+ const bytes = bytesOf(content), lines = decode(bytes, HEAD).split(/\r?\n/), seen = new Set();
17
+ if (bytes.length > HEAD) lines.pop();
18
+ for (const line of lines.filter(line => line.length <= LINE)) {
19
+ const match = HEADER.exec(line);
20
+ if (match && canonicalHeaderPath(match[1])) seen.add(match[1]);
21
+ }
22
+ return [...seen];
23
+ }
24
+
25
+ const sorted = values => [...new Set(values)].sort();
26
+ const unique = values => [...new Set(values)];
27
+ const gitRead = (root, args) => {
28
+ const reply = spawnSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
29
+ if (reply.status !== 0) throw Error('change scope unavailable');
30
+ return reply.stdout;
31
+ };
32
+
33
+ export function estimateCheckCalls({ prompts = [], rows = [] } = {}) {
34
+ const byPath = new Map(prompts.map(prompt => [prompt.path, prompt]));
35
+ const prerequisites = [], seenProblems = new Set();
36
+ const problem = (code, path, field) => {
37
+ const key = `${code}\0${path}\0${field}`;
38
+ if (!seenProblems.has(key)) { seenProblems.add(key); prerequisites.push({ code, path, field }); }
39
+ };
40
+ let hasExternalResources = false;
41
+ const cost = (path, stack = new Set()) => {
42
+ if (stack.has(path)) { problem('recursive-call-bound', path, '/calls'); return 0; }
43
+ const prompt = byPath.get(path);
44
+ if (!prompt || prompt.error) { problem(prompt?.error ?? 'interface-missing', path, '/interface'); return 0; }
45
+ if ((prompt.kind ?? 'full') === 'native-only') return 0;
46
+ if (!Number.isSafeInteger(prompt.max_model_calls) || prompt.max_model_calls < 1)
47
+ problem('undefined-call-bound', path, '/limits/max_model_calls');
48
+ const ops = Number.isSafeInteger(prompt.resource_operations) && prompt.resource_operations > 0 ? prompt.resource_operations : 0;
49
+ if (ops > 0) hasExternalResources = true;
50
+ const next = new Set([...stack, path]);
51
+ let count = 1 + ops;
52
+ for (const [index, call] of (Array.isArray(prompt.calls) ? prompt.calls : []).entries()) {
53
+ if (!Number.isSafeInteger(call?.max_calls) || call.max_calls < 1) problem('undefined-call-bound', path, `/calls/${index}/max_calls`);
54
+ const nested = cost(call?.target, next);
55
+ if (Number.isSafeInteger(call?.max_calls) && call.max_calls >= 1 && nested > 0) count += call.max_calls * (nested + 1);
56
+ }
57
+ return count;
58
+ };
59
+ let estimated = 0, maximum = 0, requests = 0;
60
+ for (const row of rows) {
61
+ const count = (row.steps ?? []).reduce((sum, step) => sum + cost(step?.entry_path), 0);
62
+ if (row.state !== 'ready') continue;
63
+ if (!Number.isSafeInteger(row.max_calls) || row.max_calls < 1) problem('undefined-call-bound', row.test, '/max_calls');
64
+ else {
65
+ estimated += Math.min(row.max_calls, count);
66
+ maximum += row.max_calls * 2;
67
+ }
68
+ requests += 2;
69
+ }
70
+ return {
71
+ calls: { estimated: prerequisites.length ? null : estimated, maximum: prerequisites.length ? null : maximum, check_requests: requests, lint_model_calls: 0 },
72
+ has_external_resources: hasExternalResources,
73
+ prerequisites,
74
+ };
75
+ }
76
+
77
+ export function buildCheckPlan({ root, found, selected, rows = [], full, base = 'HEAD', affected = false, allowMissingInterfaces = false, maxCalls = null, maxTotalCalls = null, singleAttempt = false, unresolvedReservations = null }, ports = {}) {
78
+ const git = args => (ports.git ?? gitRead)(root, args);
79
+ const readHeaders = ports.headerPrompts ?? defaultHeaderPrompts;
80
+ let changed = null;
81
+ try {
82
+ changed = sorted([...git(['diff', '--name-only', '-z', '--no-renames', base, '--']).split('\0'),
83
+ ...git(['ls-files', '--others', '--exclude-standard', '-z']).split('\0')].filter(Boolean));
84
+ } catch { /* Unknown changes require conservative target coverage. */ }
85
+ const workspace = found.workspace ?? loadRuntimeWorkspace({root});
86
+ const source = sourceFilePort(root, found.visible, workspace);
87
+ const permitted = path => allowsRuntimePath(workspace,path) && !(full && (found.excludedFixtureProjects ?? []).some(prefix=>path === prefix || path.startsWith(`${prefix}/`)));
88
+ const owners = new Map(), unknownOwners = new Set();
89
+ let deleted = new Set(), deletionsUnavailable = false;
90
+ if (changed?.some(permitted)) {
91
+ try { deleted = new Set(git(['diff', '--name-only', '-z', '--no-renames', '--diff-filter=D', base, '--']).split('\0').filter(Boolean)); }
92
+ catch { deletionsUnavailable = true; }
93
+ }
94
+ const own = (prompt, path) => {
95
+ if (!found.visible.has(prompt)) return;
96
+ owners.set(prompt, [...(owners.get(prompt) ?? []), path]);
97
+ unknownOwners.delete(path);
98
+ };
99
+ for (const path of changed ?? []) {
100
+ if (!permitted(path)) continue;
101
+ if (deleted.has(path)) unknownOwners.add(path);
102
+ else if (!found.visible.has(path)) continue;
103
+ try {
104
+ // Validate the permitted source path even when its working file is absent.
105
+ if (deleted.has(path)) source.stat({path});
106
+ const content = deleted.has(path) ? git(['show', `${base}:${path}`]) : source.read({path}).content;
107
+ for (const prompt of readHeaders(content)) own(prompt, path);
108
+ } catch { /* Unproved deleted ownership keeps target coverage conservative. */ }
109
+ }
110
+ if (changed?.length && found.visible.has('pdd-bindings.json')) {
111
+ try {
112
+ const inventory = JSON.parse(source.read({path:'pdd-bindings.json'}).content);
113
+ for (const item of inventory.modules ?? []) if (changed.includes(item.module) && permitted(item.module) && typeof item.prompt === 'string') own(item.prompt, item.module);
114
+ } catch { /* The binding owner retains inventory validation. */ }
115
+ }
116
+ const prerequisites = [], seenProblems = new Set(), prompts = new Map();
117
+ const problem = (code, path, field) => {
118
+ const key = `${code}\0${path}\0${field}`;
119
+ if (!seenProblems.has(key)) { seenProblems.add(key); prerequisites.push({code,path,field}); }
120
+ };
121
+ const cost = (path, stack = new Set(), proseOnly = false) => {
122
+ if (stack.has(path)) { if (!proseOnly) problem('recursive-call-bound', path, '/calls'); return 0; }
123
+ let prompt = prompts.get(path);
124
+ if (!prompt) {
125
+ try { prompt = readPrompt(root, found.visible, path, found.workspace); }
126
+ catch { prompt = {error:'interface-unavailable'}; }
127
+ prompts.set(path, prompt);
128
+ }
129
+ const iface = prompt.interface;
130
+ if (!iface) {
131
+ if (allowMissingInterfaces && prompt.error === 'interface-missing') {
132
+ const next = new Set([...stack, path]);
133
+ let count = 1;
134
+ for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) count += cost(target, next, true);
135
+ return count;
136
+ }
137
+ problem(prompt.error ?? 'interface-missing', path, '/interface');
138
+ return 0;
139
+ }
140
+ if (iface.kind === 'native-only') return 0;
141
+ if (!Number.isSafeInteger(iface.limits?.max_model_calls) || iface.limits.max_model_calls < 1)
142
+ problem('undefined-call-bound', path, '/limits/max_model_calls');
143
+ const next = new Set([...stack, path]);
144
+ let count = 1 + (Array.isArray(iface.resources) ? iface.resources : []).reduce((sum, resource) => sum + (Array.isArray(resource.operations) ? resource.operations.length : 0), 0);
145
+ for (const [index, call] of (Array.isArray(iface.calls) ? iface.calls : []).entries()) {
146
+ if (!Number.isSafeInteger(call?.max_calls) || call.max_calls < 1) problem('undefined-call-bound', path, `/calls/${index}/max_calls`);
147
+ const nested = cost(call?.target, next);
148
+ if (Number.isSafeInteger(call?.max_calls) && call.max_calls >= 1 && nested > 0) count += call.max_calls * (nested + 1);
149
+ }
150
+ return count;
151
+ };
152
+ const groups = new Map();
153
+ for (const test of selected) {
154
+ const key = test.storyPath ?? test.path;
155
+ if (!groups.has(key)) groups.set(key, []);
156
+ groups.get(key).push(test);
157
+ }
158
+ const capture = ports.capture ?? ((r, opts) => captureSource(r, opts, ports));
159
+ let footprints = new Map();
160
+ const targets = new Map();
161
+ const rememberTargets = captured => {
162
+ for (const file of captured.files ?? []) if (file.target) targets.set(file.path,file.target);
163
+ return captured;
164
+ };
165
+ const captureExtra = allowMissingInterfaces ? { allowMissingInterfaces: true } : {};
166
+ try {
167
+ const captured = rememberTargets(capture(root,{tests:selected.map(test=>test.path),appMap:null,excludeFixtureProjects:full,...captureExtra}));
168
+ footprints = new Map((captured.stories ?? []).map(story=>[story.story_path,story]));
169
+ } catch (error) { if (error?.unboundPort) throw error; /* Keep a broken Story from hiding other Stories' closures. */ }
170
+ const classified = [...groups].map(([story_path, tests]) => {
171
+ let closure = [], unavailable = false;
172
+ const footprint = footprints.get(story_path);
173
+ try {
174
+ if (footprint?.unavailable) unavailable = true;
175
+ else closure = sorted((footprint?.files ?? rememberTargets(capture(root, {tests:tests.map(test=>test.path),appMap:null,excludeFixtureProjects:full,...captureExtra})).files).map(file=>file.path));
176
+ }
177
+ catch (error) { if (error?.unboundPort) throw error; unavailable = true; }
178
+ return {story_path,tests,closure,unavailable};
179
+ });
180
+ let conservative = '';
181
+ if (affected && changed?.length) {
182
+ if (changed.some(path=>['pdd-source.json','pdd-workspace.json','pdd-bindings.json'].includes(path)))
183
+ conservative = 'global source, workspace or binding inventory changed; conservative selection';
184
+ if (classified.some(story=>story.unavailable)) conservative ||= 'dependency closure unavailable; conservative selection';
185
+
186
+ // Query only permitted names. The tree establishes whether a working path is
187
+ // new, and identifies old link aliases without following their targets.
188
+ const paths = sorted([...changed.filter(permitted), ...classified.flatMap(story=>story.closure).filter(permitted)]);
189
+ const old = new Map();
190
+ try {
191
+ if (paths.length) for (const record of git(['ls-tree','-z',base,'--',...paths]).split('\0').filter(Boolean)) {
192
+ const match = /^(\d+) (?:blob|tree|commit) [a-f0-9]+\t([\s\S]+)$/.exec(record);
193
+ if (!match) throw Error('invalid tree metadata');
194
+ if (permitted(match[2])) old.set(match[2],match[1]);
195
+ }
196
+ } catch { conservative ||= 'old ownership or safe-link metadata unavailable; conservative selection'; }
197
+ const implementation = path => /(?:^|\/)(?:src|lib|bin|app)\//.test(path)
198
+ || !/\.(?:md|txt|rst|csv|svg|png|jpe?g|gif|webp|ico|woff2?|ttf|json)$/i.test(path)
199
+ || [...owners.values()].some(paths=>paths.includes(path));
200
+ let bindings = [];
201
+ if (found.visible.has('pdd-bindings.json')) {
202
+ try {
203
+ const inventory = JSON.parse(source.read({path:'pdd-bindings.json'}).content);
204
+ if (inventory.schema_version !== 'pdd.bindings.v1' || !Array.isArray(inventory.modules)) throw Error('invalid binding inventory');
205
+ bindings = inventory.modules;
206
+ } catch { conservative ||= 'binding ownership unavailable; conservative selection'; }
207
+ }
208
+ for (const path of changed.filter(permitted)) {
209
+ const bound = bindings.filter(item=>item?.module === path && typeof item.prompt === 'string').map(item=>item.prompt);
210
+ const inspectOwners = content => {
211
+ const named = unique([...bound,...readHeaders(content)]);
212
+ if (!named.length || named.some(prompt=>!permitted(prompt) || !found.visible.has(prompt)))
213
+ conservative ||= `${deleted.has(path)?'deleted':'implementation'} ownership unavailable: ${path}; conservative selection`;
214
+ for (const prompt of named) if (permitted(prompt)) own(prompt,path);
215
+ };
216
+ try {
217
+ // Headers in either revision establish ownership, including assets whose
218
+ // current header was removed. Apply permission before either read.
219
+ const current = deleted.has(path) ? null : source.read({path}).content;
220
+ const previous = old.has(path) ? git(['show',`${base}:${path}`]) : null;
221
+ if (!implementation(path) && !bound.length && !readHeaders(previous).length && !readHeaders(current).length) continue;
222
+ if (current !== null) inspectOwners(current);
223
+ if (previous !== null) inspectOwners(previous);
224
+ else if (deleted.has(path)) conservative ||= `deleted ownership unavailable: ${path}; conservative selection`;
225
+ } catch { conservative ||= `${deleted.has(path)?'deleted':'old/new implementation'} ownership unavailable: ${path}; conservative selection`; }
226
+ }
227
+ // Capture records the final safe target while retaining the authored alias.
228
+ // Old aliases must also be known: a changed target may otherwise disappear
229
+ // from the current closure after a link is redirected or removed.
230
+ for (const [path,mode] of old) if (mode === '120000') {
231
+ try {
232
+ const raw = git(['show',`${base}:${path}`]);
233
+ const target = raw.startsWith('/') ? null : posix.normalize(posix.join(posix.dirname(path),raw));
234
+ if (!target || target.startsWith('../') || target.includes('\\') || !permitted(target)) throw Error('unavailable target');
235
+ if (!targets.has(path) || targets.get(path) !== target) throw Error('unproved old/new relationship');
236
+ } catch { conservative ||= 'old/new safe-link target relationship unavailable; conservative selection'; }
237
+ }
238
+ for (const [path,target] of targets) if (!permitted(path) || !permitted(target) || !old.has(path)
239
+ || changed.some(change=>path.startsWith(`${change}/`)))
240
+ conservative ||= 'safe-link target relationship unavailable; conservative selection';
241
+ }
242
+ const stories = classified.map(({story_path,tests,closure,unavailable}) => {
243
+ const affectedPaths = sorted((changed ?? []).filter(path => allowsRuntimePath(workspace,path) && (closure.includes(path) || tests.some(test=>test.path === path || test.storyPath === path)
244
+ || (affected && closure.some(alias=>targets.get(alias) === path))))
245
+ .concat(closure.flatMap(path=>owners.get(path) ?? [])));
246
+ const uncertainOwner = deletionsUnavailable || unknownOwners.size > 0;
247
+ const target = !full || changed === null || !changed.length || unavailable || uncertainOwner || !!conservative || affectedPaths.length > 0 || changed.includes('pdd-bindings.json');
248
+ return {story_path,tests:tests.map(test=>test.path),role:target?'target':'baseline',
249
+ reason:!full?'explicit selection':unavailable?'dependency closure unavailable; conservative selection':changed === null?'change scope unavailable; conservative selection':!changed.length?'no changed paths; conservative selection':uncertainOwner?'deleted ownership unavailable; conservative selection':conservative || (affectedPaths.length?`changed paths: ${affectedPaths.join(', ')}`:target?'binding inventory changed':'unrelated to known changes; required by full batch; pre-change result unknown'),
250
+ affected_paths:affectedPaths,dependency_closure:closure};
251
+ });
252
+ if (!stories.some(story=>story.role === 'target')) for (const story of stories) {
253
+ story.role = 'target'; story.reason = 'no affected Story established; conservative selection';
254
+ }
255
+ let estimated = 0;
256
+ const dispatched = new Set(selectCheckTests({stories},{affected}).tests), budgetRows = [];
257
+ for (const row of rows.filter(row=>!affected || dispatched.has(row.test))) {
258
+ // Inspect interfaces even when a different local rule won preflight precedence.
259
+ const count = (row.steps ?? []).reduce((sum, step) => sum + cost(step?.entry_path), 0);
260
+ if (row.state !== 'ready') continue;
261
+ const validBound = Number.isSafeInteger(row.max_calls) && row.max_calls >= 1;
262
+ if (!validBound) problem('undefined-call-bound',row.test,'/max_calls');
263
+ else estimated += Math.min(row.max_calls, count);
264
+ budgetRows.push({ test: row.test, max_calls: validBound ? row.max_calls : 0, restart_used: false, attempts: [] });
265
+ }
266
+ const prior = {
267
+ count: Number.isSafeInteger(unresolvedReservations?.count) && unresolvedReservations.count >= 0 ? unresolvedReservations.count : 0,
268
+ reserved_calls: Number.isSafeInteger(unresolvedReservations?.reserved_calls) && unresolvedReservations.reserved_calls >= 0 ? unresolvedReservations.reserved_calls : 0,
269
+ batches: Array.isArray(unresolvedReservations?.batches) ? [...unresolvedReservations.batches] : []
270
+ };
271
+ const evaluated = evaluateCheckBudget({ max_total_calls: maxTotalCalls, single_attempt: singleAttempt,
272
+ unresolved_prior_reservations: { count: prior.count, reserved_calls: prior.reserved_calls }, rows: budgetRows, candidate: null });
273
+ const call_policy = {
274
+ max_calls_override: maxCalls ?? null,
275
+ per_request_max_calls: evaluated.plan.per_request_caps,
276
+ max_total_calls: maxTotalCalls ?? null,
277
+ restart_replacement: evaluated.plan.restart_replacement,
278
+ unbounded_maximum: prerequisites.length ? null : evaluated.plan.unbounded_maximum,
279
+ planned_maximum: prerequisites.length ? null : evaluated.plan.planned_maximum,
280
+ unresolved_reservations: prior,
281
+ accounting_scope: evaluated.plan.accounting_scope
282
+ };
283
+ return {schema_version:'pdd.check-plan.v1',full,base,changed_paths:changed,stories,
284
+ calls:{estimated:prerequisites.length?null:estimated,maximum:prerequisites.length?null:evaluated.plan.planned_maximum,check_requests:evaluated.plan.planned_check_requests,lint_model_calls:0},
285
+ call_policy,prerequisites};
286
+ }
287
+
288
+ export function evaluateCheckBudget({ max_total_calls = null, single_attempt = false, unresolved_prior_reservations = { count: 0, reserved_calls: 0 }, rows = [], candidate = null } = {}) {
289
+ const multiplier = single_attempt ? 1 : 2;
290
+ const per_request_caps = [...new Set(rows.map(row => row.max_calls).filter(value => Number.isSafeInteger(value) && value >= 1))].sort((a, b) => a - b);
291
+ const unbounded_maximum = rows.reduce((sum, row) => sum + (Number.isSafeInteger(row.max_calls) && row.max_calls >= 1 ? row.max_calls * multiplier : 0), 0);
292
+ const planned_maximum = max_total_calls === null ? unbounded_maximum : Math.min(unbounded_maximum, max_total_calls);
293
+ const plan = {
294
+ per_request_caps,
295
+ max_total_calls,
296
+ restart_replacement: single_attempt ? 'disabled' : 'at-most-one',
297
+ unbounded_maximum,
298
+ planned_maximum,
299
+ planned_check_requests: rows.length * multiplier,
300
+ unresolved_prior_reservations: {
301
+ count: unresolved_prior_reservations?.count ?? 0,
302
+ reserved_calls: unresolved_prior_reservations?.reserved_calls ?? 0
303
+ },
304
+ accounting_scope: 'logical-interpreter-calls'
305
+ };
306
+ let consumed_known = 0, unresolved_reserved = 0, in_flight_reserved = 0;
307
+ for (const row of rows) {
308
+ for (const attempt of row.attempts ?? []) {
309
+ const floor = Math.max(attempt.requested_max_calls, (attempt.known_calls ?? 0) + (attempt.unknown_calls ?? 0));
310
+ if (attempt.status === 'capacity_refused_zero') continue;
311
+ if (attempt.status === 'settled') consumed_known += attempt.known_calls;
312
+ else if (attempt.status === 'in_flight') in_flight_reserved += floor;
313
+ else unresolved_reserved += floor;
314
+ }
315
+ }
316
+ const committed_calls = consumed_known + unresolved_reserved + in_flight_reserved;
317
+ const remaining_calls = max_total_calls === null ? null : Math.max(0, max_total_calls - committed_calls);
318
+ const accounting = { consumed_known, unresolved_reserved, in_flight_reserved, committed_calls, remaining_calls };
319
+ let decision = null;
320
+ if (candidate !== null && candidate !== undefined) {
321
+ if (candidate.kind === 'restart-replacement' && candidate.prior_reason_code !== 'service-restarted') {
322
+ decision = { action: 'refuse-replacement', reason_code: 'not-service-restarted', effective_max_calls: 0, retain_prior_uncertainty: true };
323
+ } else if (candidate.kind === 'restart-replacement' && candidate.restart_used) {
324
+ decision = { action: 'refuse-replacement', reason_code: 'restart-limit-reached', effective_max_calls: 0, retain_prior_uncertainty: true };
325
+ } else if (candidate.kind === 'restart-replacement' && single_attempt) {
326
+ decision = { action: 'refuse-replacement', reason_code: 'restart-replacement-disabled', effective_max_calls: 0, retain_prior_uncertainty: true };
327
+ } else {
328
+ const retain_prior_uncertainty = candidate.kind === 'restart-replacement';
329
+ if (max_total_calls === null || remaining_calls >= candidate.requested_max_calls) {
330
+ decision = { action: 'send', reason_code: 'within-budget', effective_max_calls: candidate.requested_max_calls, retain_prior_uncertainty };
331
+ } else if (in_flight_reserved > 0 && Math.max(0, max_total_calls - (consumed_known + unresolved_reserved)) > remaining_calls) {
332
+ decision = { action: 'wait', reason_code: 'awaiting-in-flight-settlement', effective_max_calls: 0, retain_prior_uncertainty };
333
+ } else if (remaining_calls >= 1) {
334
+ decision = { action: 'send', reason_code: 'clamped-to-remaining-budget', effective_max_calls: remaining_calls, retain_prior_uncertainty };
335
+ } else {
336
+ decision = { action: 'block', reason_code: 'call-budget-exhausted', effective_max_calls: 0, retain_prior_uncertainty };
337
+ }
338
+ }
339
+ }
340
+ return { plan, accounting, decision };
341
+ }
342
+
343
+ export function selectCheckTests(plan, {affected = false} = {}) {
344
+ const all = unique(plan.stories.flatMap(story=>story.tests));
345
+ if (!affected) return {mode:'full',tests:all,baseline_tests:[]};
346
+ const tests = unique(plan.stories.filter(story=>story.role === 'target').flatMap(story=>story.tests));
347
+ if (!tests.length) return {mode:'affected',tests:all,baseline_tests:[]};
348
+ return {mode:'affected',tests,baseline_tests:unique(plan.stories.filter(story=>story.role === 'baseline').flatMap(story=>story.tests))};
349
+ }
350
+
351
+ export function baselineReport({plan,observations,availability,warnings}) {
352
+ const tests = unique(plan.stories.filter(story=>story.role === 'baseline').flatMap(story=>story.tests));
353
+ const admitted = observations.filter(observation=>tests.includes(observation.test));
354
+ const observed = new Set(admitted.map(observation=>observation.test));
355
+ return {schema_version:'pdd.baseline-report.v1',availability,tests,observations:admitted,
356
+ missing_tests:tests.filter(test=>!observed.has(test)),warnings:[...warnings]};
357
+ }
358
+
359
+ export function checkPlanResults(plan, rows) {
360
+ if (plan?.schema_version !== 'pdd.check-plan.v1' || !Array.isArray(plan.stories)
361
+ || plan.stories.some(story=>!story || !['target','baseline'].includes(story.role) || !Array.isArray(story.tests)
362
+ || story.tests.some(path=>typeof path !== 'string'))) return null;
363
+ const group = role => {
364
+ const tests = sorted(plan.stories.filter(story=>story.role === role).flatMap(story=>story.tests));
365
+ const state = test => {
366
+ const matches = rows.filter(row=>row.test === test).map(row=>resultOutcome(row).state);
367
+ return matches.length && matches.every(value=>value === 'passed') ? 'passed' : matches.includes('failed') ? 'failed' : 'not_run';
368
+ };
369
+ const passed = tests.filter(test=>state(test) === 'passed'), failures = tests.filter(test=>state(test) === 'failed'), unresolved = tests.filter(test=>state(test) === 'not_run');
370
+ return {tests,passed,failures,unresolved,state:!tests.length?'none':failures.length?'failed':unresolved.length?'not_run':'passed'};
371
+ };
372
+ const target = group('target'), baseline = group('baseline');
373
+ const allTargetRefused = target.unresolved.length > 0 && target.unresolved.every(test => {
374
+ const matches = rows.filter(row => row.test === test).map(row => resultOutcome(row).state);
375
+ return matches.length > 0 && matches.every(value => value === 'refused');
376
+ });
377
+ const guidance = plan.full && plan.prerequisites?.length ? `Repair local check-plan prerequisites: ${plan.prerequisites.map(item=>`${item.code}: ${item.path} ${item.field}`).join('; ')}. Repair the named interface or call bound, then run a fresh pdd test check. No checks were sent; saved reads and retries cannot repair these local prerequisites.`
378
+ : target.failures.length ? `Repair target failures: ${target.failures.join(', ')}. Keep baseline results separate.`
379
+ : target.unresolved.length ? (allTargetRefused ? `Inspect refused target checks: ${target.unresolved.join(', ')}. Follow each refusal Fix or Next step, then run a fresh pdd test check.` : 'Read the saved batch for unresolved target checks; do not resend uncertain work.')
380
+ : baseline.failures.length || baseline.unresolved.length ? `Target checks passed. Hand off baseline obligations: ${[...baseline.failures,...baseline.unresolved].join(', ')}. Keep the failed or incomplete full batch and required full-pass gates. Do not rerun unchanged target checks or change their expectations to repair baseline work. Read the saved batch for unresolved checks; baseline age and ownership are not proved.`
381
+ : 'Selected checks passed; required repository gates still apply.';
382
+ return {target,baseline,guidance};
383
+ }
384
+
385
+ export function checkPlanLines(plan) {
386
+ const policy = plan.call_policy, disabled = policy?.restart_replacement === 'disabled';
387
+ const capNote = policy?.max_total_calls != null ? `${disabled ? ', ' : ' ('}capped by --max-total-calls ${policy.max_total_calls}${disabled ? '' : ')'}` : '';
388
+ const callsLine = disabled
389
+ ? ` Interpreter calls: about ${plan.calls.estimated ?? 'unknown'}; at most ${plan.calls.maximum ?? 'unknown'} (restart replacement disabled${capNote}); at most ${plan.calls.check_requests} Check requests; lint: 0 model calls.`
390
+ : ` Interpreter calls: about ${plan.calls.estimated ?? 'unknown'}; at most ${plan.calls.maximum ?? 'unknown'} including one restart replacement per test${capNote}; at most ${plan.calls.check_requests} Check requests; lint: 0 model calls.`;
391
+ const policyLines = policy ? [(() => {
392
+ const caps = policy.per_request_max_calls?.length ? policy.per_request_max_calls.join(', ') : 'none';
393
+ const ceiling = policy.max_total_calls != null ? `${policy.max_total_calls} (--max-total-calls)` : 'unbounded';
394
+ const replacement = disabled ? 'disabled' : 'at most 1 per test on confirmed service-restarted';
395
+ const prior = policy.unresolved_reservations;
396
+ const priorText = prior?.count ? `${prior.count} (${prior.reserved_calls} calls reserved${prior.batches?.length ? ` in ${prior.batches.join(', ')}` : ''})` : '0';
397
+ return ` Call policy: per-request cap ${caps}; invocation ceiling ${ceiling}; restart replacement ${replacement}; unresolved prior reservations ${priorText} (logical interpreter call limits; not dollar, token or provider-attempt guarantees).`;
398
+ })()] : [];
399
+ return ['Check plan:', ...plan.stories.flatMap(story=>[
400
+ ` ${story.role}: ${story.story_path} (${story.tests.join(', ')}); ${story.reason}`,
401
+ ` dependency closure: ${story.dependency_closure.join(', ') || 'unavailable'}`]),
402
+ callsLine, ...policyLines,
403
+ ...plan.prerequisites.map(item=>` prerequisite: ${item.code}: ${item.path} ${item.field}`)];
404
+ }
405
+
406
+ export function checkPlanResultLines(result) {
407
+ const counts = group => [`${group.passed.length} passed`,...(group.failures.length?[`${group.failures.length} failed`]:[]),
408
+ ...(group.unresolved.length?[`${group.unresolved.length} unresolved`]:[])].join(', ');
409
+ return result ? [`Target checks: ${result.target.state}; ${counts(result.target)}.`,
410
+ `Baseline obligations: ${result.baseline.state}; ${counts(result.baseline)}.`, result.guidance] : [];
411
+ }