@promptdriven/runtime-client 1.1.0 → 1.1.2

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptdriven/runtime-client",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "PDD Runtime Client (@promptdriven/runtime-client)",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -0,0 +1,53 @@
1
+ // Adaptive multi-Story check concurrency pacing (AIMD).
2
+ // Bounds default batch concurrency (instead of unbounded Infinity bursts),
3
+ // backs off multiplicatively on HTTP 429 / capacity / provider contention,
4
+ // and ramps back up conservatively after consecutive clean completions.
5
+
6
+ export const DEFAULT_CHECK_CONCURRENCY = 4;
7
+ export const ADAPTIVE_RECOVERY_SUCCESSES = 2;
8
+
9
+ export function createAdaptiveConcurrency({ ceiling = DEFAULT_CHECK_CONCURRENCY, initial = ceiling } = {}) {
10
+ const maxWindow = Number.isSafeInteger(ceiling) && ceiling >= 1 ? ceiling : DEFAULT_CHECK_CONCURRENCY;
11
+ const startWindow = Math.max(1, Math.min(maxWindow, Number.isSafeInteger(initial) && initial >= 1 ? initial : maxWindow));
12
+ return {
13
+ ceiling: maxWindow,
14
+ window: startWindow,
15
+ cleanCompletions: 0,
16
+ contentionEvents: 0,
17
+ countedSignals: new Set(),
18
+ countedSuccesses: new Set(),
19
+ };
20
+ }
21
+
22
+ export function recordContention(state, signalKey = null, { reason = 'contention' } = {}) {
23
+ if (!state) return { changed: false, previous: 1, current: 1, reason };
24
+ if (signalKey != null) {
25
+ if (state.countedSignals.has(signalKey)) return { changed: false, previous: state.window, current: state.window, reason };
26
+ state.countedSignals.add(signalKey);
27
+ }
28
+ state.contentionEvents += 1;
29
+ state.cleanCompletions = 0;
30
+ const previous = state.window;
31
+ state.window = Math.max(1, Math.floor(state.window / 2));
32
+ return { changed: state.window !== previous, previous, current: state.window, reason };
33
+ }
34
+
35
+ export function recordCleanSuccess(state, successKey = null) {
36
+ if (!state) return { changed: false, previous: 1, current: 1 };
37
+ if (successKey != null) {
38
+ if (state.countedSuccesses.has(successKey)) return { changed: false, previous: state.window, current: state.window };
39
+ state.countedSuccesses.add(successKey);
40
+ }
41
+ if (state.window >= state.ceiling) {
42
+ state.cleanCompletions = 0;
43
+ return { changed: false, previous: state.window, current: state.window };
44
+ }
45
+ state.cleanCompletions += 1;
46
+ if (state.cleanCompletions >= ADAPTIVE_RECOVERY_SUCCESSES) {
47
+ const previous = state.window;
48
+ state.window = Math.min(state.ceiling, state.window + 1);
49
+ state.cleanCompletions = 0;
50
+ return { changed: state.window !== previous, previous, current: state.window };
51
+ }
52
+ return { changed: false, previous: state.window, current: state.window };
53
+ }
@@ -60,6 +60,9 @@ function observed(current){const last=current.last_answer;if(!object(last)||type
60
60
  const before=own(report,'input_world')?report.input_world:own(last,'world_before')?last.world_before:undefined;
61
61
  const after=own(report,'world')?report.world:own(last,'world_after')?last.world_after:undefined;
62
62
  if(before!==undefined)run.world_before=clone(before);if(after!==undefined)run.world_after=clone(after);
63
+ const calls=object(report.calls)?report.calls:object(last.calls)?last.calls:undefined;
64
+ const recordingAvailable=typeof report.recording_available==='boolean'?report.recording_available:typeof last.recording_available==='boolean'?last.recording_available:undefined;
65
+ if(calls!==undefined)run.calls=clone(calls);if(recordingAvailable!==undefined)run.recording_available=recordingAvailable;
63
66
  if(typeof last.screen==='string')run.screen=last.screen;if(Array.isArray(last.screens))run.screens=last.screens.filter(x=>typeof x==='string').slice(0,64);
64
67
  return run;
65
68
  }
@@ -1,11 +1,61 @@
1
- // Generated from prompts/cli/agent-judge.prompt.md (sha256: 7413bb037488fc165d9f2e799ca4b04017b326ee8acee87da119c68d7af175a5).
1
+ // Generated from prompts/cli/agent-judge.prompt.md (sha256: 2931d1ba2f74b5399eba9d5f39e72af05e00af3c469eb7bd1125e1cfd6a2b834).
2
2
  import {isDeepStrictEqual} from 'node:util';
3
3
  const clone=value=>JSON.parse(JSON.stringify(value));
4
4
  const own=(x,k)=>x!==null&&typeof x==='object'&&Object.hasOwn(x,k);
5
+ const isPlainObj=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
6
+ const isCountMap=x=>isPlainObj(x)&&Object.values(x).every(v=>Number.isSafeInteger(v)&&v>=0);
7
+ const PATH_HEX_COUNTER_RE=/^path-([0-9a-f]+)-(.+)$/;
8
+ const utf8Decoder=new TextDecoder('utf-8',{fatal:true});
5
9
  const references=x=>Array.isArray(x)?x.some(references):x!==null&&typeof x==='object'&&(own(x,'$step_result')||Object.values(x).some(references));
6
10
  const entry=s=>`${s.entry_path}#${s.operation}`;
7
11
  const validPointer=p=>typeof p==='string'&&(p===''||(p.startsWith('/')&&!/~(?:[^01]|$)/.test(p)));
8
12
  function at(value,path){if(!validPointer(path))return{invalid:true};if(value===undefined)return{missing:true};if(path==='')return{value};for(const key of path.slice(1).split('/').map(k=>k.replace(/~1/g,'/').replace(/~0/g,'~'))){if(!own(value,key))return{missing:true};value=value[key];}return{value};}
13
+ function hasRecordedCalls(run){
14
+ if(!isPlainObj(run)||run.recording_available===false)return false;
15
+ const c=run.calls;
16
+ if(!isPlainObj(c))return false;
17
+ const hasInternal=own(c,'internal'),hasResources=own(c,'resources');
18
+ if(!hasInternal&&!hasResources)return false;
19
+ if(hasInternal&&!isCountMap(c.internal))return false;
20
+ if(hasResources&&!isCountMap(c.resources))return false;
21
+ return true;
22
+ }
23
+ function promptStem(decodedPath){
24
+ const base=decodedPath.split('/').at(-1)??decodedPath;
25
+ return base.endsWith('.prompt.md')?base.slice(0,-'.prompt.md'.length):base;
26
+ }
27
+ function decodeHexUtf8(hex){
28
+ if(!hex||hex.length%2!==0||!/^[0-9a-f]+$/.test(hex))return null;
29
+ try{return utf8Decoder.decode(Buffer.from(hex,'hex'));}catch{return null;}
30
+ }
31
+ function resolveCallsPointer(calls,path){
32
+ const direct=at(calls,path);
33
+ if(!direct.missing&&!direct.invalid)return direct;
34
+ if(direct.invalid||!isPlainObj(calls))return direct;
35
+ let bucketName,rest;
36
+ if(path.startsWith('/resources/')){bucketName='resources';rest=path.slice('/resources/'.length);}
37
+ else if(path.startsWith('/internal/')){bucketName='internal';rest=path.slice('/internal/'.length);}
38
+ else return direct;
39
+ if(rest.includes('/'))return direct;
40
+ const reqKey=rest.replace(/~1/g,'/').replace(/~0/g,'~');
41
+ const bucket=own(calls,bucketName)?calls[bucketName]:null;
42
+ if(!isPlainObj(bucket))return direct;
43
+ const matches=[];
44
+ for(const [key,count] of Object.entries(bucket)){
45
+ if(bucketName==='internal'){
46
+ if(key.startsWith('path-')){
47
+ const decoded=decodeHexUtf8(key.slice('path-'.length));
48
+ if(decoded!==null&&promptStem(decoded)===reqKey)matches.push(count);
49
+ }
50
+ continue;
51
+ }
52
+ const m=PATH_HEX_COUNTER_RE.exec(key);
53
+ if(!m)continue;
54
+ const decoded=decodeHexUtf8(m[1]);
55
+ if(decoded!==null&&`${promptStem(decoded)}-${m[2]}`===reqKey)matches.push(count);
56
+ }
57
+ return matches.length===1?{value:matches[0]}:direct;
58
+ }
9
59
  function observedTarget(run,target,path){
10
60
  if(target==='world')return run.world_after===undefined?{unavailable:true}:at(run.world_after,path);
11
61
  const hasError=own(run,'error')&&run.error!==undefined&&run.error!==null,hasResult=!hasError&&own(run,'result')&&run.result!==undefined;
@@ -30,7 +80,28 @@ export function createRunJudge({scenario,checkPassed=[]}){
30
80
  for(const c of criteria){const checks=(s.checks??[]).filter(ch=>ch.criterion_id===c.id);if(!checks.length)continue;const item={id:c.id,state:'tried',compared:0,unchecked:[]};
31
81
  const skip=reason=>{if(!item.unchecked.includes(reason))item.unchecked.push(reason);};
32
82
  for(const ch of checks){
33
- if(ch.target==='calls'){skip('calls not checked here: pdd test covers them');continue;}
83
+ if(ch.target==='calls'){
84
+ if(!['equals','not_equals','one_of','count'].includes(ch.op)||!validPointer(ch.path)||!own(ch,'value')||(ch.op==='one_of'&&(!Array.isArray(ch.value)||!ch.value.length))||(ch.op==='count'&&(!Number.isSafeInteger(ch.value)||ch.value<0))){skip('unsupported check not checked here');continue;}
85
+ if(references(ch.value)){skip('step-result reference not checked here');continue;}
86
+ if(run.recording_available===false){skip('calls not checked: dispatch recording unavailable');continue;}
87
+ if(!hasRecordedCalls(run)){skip('calls not checked: dispatch recording data unavailable');continue;}
88
+ const actual=resolveCallsPointer(run.calls,ch.path);
89
+ item.compared++;
90
+ let passed=false,got=actual.missing||actual.value===undefined?null:clone(actual.value);
91
+ if(ch.op==='equals'){passed=!actual.missing&&isDeepStrictEqual(actual.value,ch.value);}
92
+ else if(ch.op==='not_equals'){passed=!actual.missing&&!isDeepStrictEqual(actual.value,ch.value);}
93
+ else if(ch.op==='one_of'){passed=!actual.missing&&ch.value.some(v=>isDeepStrictEqual(actual.value,v));}
94
+ else{
95
+ let counted;
96
+ if(!actual.missing&&isPlainObj(actual.value)&&Object.values(actual.value).every(v=>Number.isSafeInteger(v))){counted=Object.values(actual.value).filter(v=>v>0).length;}
97
+ else if(!actual.missing&&(Array.isArray(actual.value)||typeof actual.value==='string')){counted=actual.value.length;}
98
+ else if(!actual.missing&&isPlainObj(actual.value)){counted=Object.keys(actual.value).length;}
99
+ got=counted!==undefined?counted:null;
100
+ passed=counted!==undefined&&counted===ch.value;
101
+ }
102
+ if(!passed){const difference={target:ch.target,path:ch.path,...(ch.op!=='equals'?{op:ch.op}:{}),expected:clone(ch.value),got,...(actual.missing?{missing:true}:{})};item.first_difference??=difference;firstDifference??=difference;}
103
+ continue;
104
+ }
34
105
  if(ch.op!=='equals'||!['result','error','world'].includes(ch.target)||!validPointer(ch.path)||!own(ch,'value')){skip('unsupported check not checked here');continue;}
35
106
  if(references(ch.value)){skip('step-result reference not checked here');continue;}
36
107
  if(ch.target==='world'&&!same){skip('world not checked: different or unknown starting data');continue;}
@@ -564,6 +564,25 @@ export async function observeTryCall(input, ports) {
564
564
  return observe(input, ports);
565
565
  }
566
566
 
567
+ let checkReconcileModule;
568
+ function checkReconcileSlice() { return checkReconcileModule ??= req('./runtime-check-reconcile.mjs'); }
569
+ export function projectCheckReconciliation(input) { return checkReconcileSlice().projectCheckReconciliation(input); }
570
+
571
+ export async function reconcileCheckReceipt(input, ports) {
572
+ const { reconcileCheckReceipt: reconcile } = await import('./runtime-client.mjs');
573
+ return reconcile(input, ports);
574
+ }
575
+
576
+ export async function reconcileCheckBatch(input, ports) {
577
+ const { reconcileCheckBatch: reconcile } = await import('./runtime-client.mjs');
578
+ return reconcile(input, ports);
579
+ }
580
+
581
+ export async function reconcileStaleReservations(input, ports) {
582
+ const { reconcileStaleReservations: reconcile } = await import('./runtime-client.mjs');
583
+ return reconcile(input, ports);
584
+ }
585
+
567
586
  export async function askAgent(input, ports) {
568
587
  const { askAgent: ask } = await import('./agent-ask.mjs');
569
588
  return ask(input, ports);
@@ -63,16 +63,18 @@ function scopedHandlers(handlers, screen, encode) {
63
63
  return output;
64
64
  }
65
65
 
66
+ const APP_MAP_VERSIONS = new Set(['prompt-runtime.app-map.v1', 'prompt-runtime.app-map.v2']);
67
+
66
68
  function validateMap(map, part) {
67
69
  const invalid = field => badMap(`app/maps/${part}.json has a missing or malformed ${field} field.`);
68
70
  const required = (value, fields, parent) => {
69
71
  if (!plain(value)) invalid(parent);
70
72
  for (const field of fields) if (!Object.hasOwn(value, field)) invalid(`${parent}.${field}`);
71
73
  };
72
- required(map, ['schema_version', 'name', 'initial_screen', 'initial_route', 'initial_state', 'state_schema', 'synthetic', 'screens', 'router', 'routes', 'handlers', 'stylesheets'], 'map');
74
+ required(map, ['name', 'initial_screen', 'initial_route', 'initial_state', 'state_schema', 'synthetic', 'screens', 'router', 'routes', 'handlers', 'stylesheets'], 'map');
73
75
  const supported=new Set(['schema_version','name','initial_screen','initial_route','initial_state','state_schema','synthetic','screens','router','routes','handlers','stylesheets']);
74
76
  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');
77
+ if (Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) invalid('schema_version');
76
78
  for (const field of ['name', 'initial_screen']) if (typeof map[field] !== 'string' || !map[field]) invalid(field);
77
79
  if (map.initial_route !== null && typeof map.initial_route !== 'string') invalid('initial_route');
78
80
  if (typeof map.synthetic !== 'boolean') invalid('synthetic');
@@ -129,8 +131,8 @@ function joinMaps(product, parts, maps, chain, encode, selectedParts) {
129
131
  let tapOperations = 0;
130
132
  for (const [index, map] of maps.entries()) {
131
133
  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
+ if ((Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) || !Array.isArray(map.screens) || !Array.isArray(map.handlers)
135
+ || !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/v2 map.`);
134
136
  const ids = new Set();
135
137
  for (const screen of map.screens) {
136
138
  if (!plain(screen) || Object.keys(screen).sort().join(',') !== 'format,id,input,operation,prompt_path,result_pointer,source'
@@ -427,7 +427,7 @@ export async function runProgram({ file, argv = [], options = {}, cwd = process.
427
427
  const pending = structuredClone(session);
428
428
  lastId = session.id;
429
429
  let reopened = await context.runtime.reopen(session.id);
430
- const deadline = Date.now() + 300_000;
430
+ const reopenStarted = Date.now(), deadline = reopenStarted + 300_000;
431
431
  for (;;) {
432
432
  const job = reopened.json;
433
433
  if ([200, 202].includes(reopened.status)) {
@@ -436,7 +436,8 @@ export async function runProgram({ file, argv = [], options = {}, cwd = process.
436
436
  if (reopened.status === 200 && job.state === 'passed') break;
437
437
  }
438
438
  if (programSignal.aborted || Date.now() >= deadline || reopened.status && ![200, 202].includes(reopened.status)) throw failure(`Reopening the program was not confirmed. Read: ${recovery(session.id)}`, 125);
439
- await context.ports.sleep(context.ports.pollMs, programSignal);
439
+ const delay = typeof context.ports.pollDelay === 'function' ? context.ports.pollDelay(Date.now() - reopenStarted) : context.ports.pollMs;
440
+ await context.ports.sleep(delay, programSignal);
440
441
  reopened = await context.runtime.get(session.id);
441
442
  }
442
443
  locked(() => { const latest = readPrivate(sessionPath); if (!isDeepStrictEqual(latest, pending) || latest?.state !== 'unknown' || latest.stop_id) throw failure('This session was superseded.', 125); session = { ...previous, state: 'running' }; writePrivate(sessionPath, session); });
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-bindings.prompt.md (sha256: d852225e7cabfb564f74e7cdd977f73a1fbf92e50346a72c31bcf566cc1a1e98).
1
+ // Generated from prompts/cli/runtime-bindings.prompt.md (sha256: 5431647b69a555975055800dd36c374050ac0f8cfc84419fd72f3248e48038e9).
2
2
  import {loadRuntimeWorkspace,allowsRuntimePath} from './runtime-workspace.mjs';
3
3
  import { lstatSync } from 'node:fs';
4
4
  import { join } from 'node:path';
@@ -10,20 +10,21 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
10
10
  const runtime = includeRuntime ? {runtime:runtimeCoverage({root,allowMissingInterfaces})} : {};
11
11
  const unavailable = { available: false, bound: null, total: null, modules: [], ...runtime };
12
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');
13
+ const regular = (path, control = false) => {
14
+ if (typeof path !== 'string' || !path || path.includes('\\') || path.startsWith('/') || path.split('/').some(p => !p || p === '.' || p === '..' || p.toLowerCase() === '.git')) fail(String(path), 'use an existing repository-relative regular Git-visible path');
15
15
  if (isSecretPath(path)) fail(path, 'secret-looking paths are not allowed');
16
+ if (!control && !allowsRuntimePath(workspace, path)) fail(path, 'outside pdd-workspace.json allowed_paths');
16
17
  let full = root;
17
18
  for (const part of path.split('/')) {
18
19
  full = join(full, part);
19
20
  let stat; try { stat = lstatSync(full); } catch { fail(path, 'file does not exist'); }
20
21
  if (stat.isSymbolicLink()) fail(path, 'symlinks are not allowed');
21
22
  }
22
- if (!lstatSync(full).isFile() || !(path==='pdd-bindings.json'?controlVisible:found.visible).has(path)) fail(path, 'must be a regular Git-visible file');
23
+ if (!lstatSync(full).isFile() || !(control ? controlVisible : found.visible).has(path)) fail(path, 'must be a regular Git-visible file');
23
24
  return path;
24
25
  };
25
26
  try { lstatSync(join(root, 'pdd-bindings.json')); } catch (error) { if (error.code === 'ENOENT') return unavailable; throw error; }
26
- regular('pdd-bindings.json');
27
+ regular('pdd-bindings.json', true);
27
28
  const files = sourceFilePort(root);
28
29
  if (files.stat({path:'pdd-bindings.json'}).size > 65536) fail('inventory', 'exceeds 64 KiB');
29
30
  let inventory; try { inventory = JSON.parse(files.read({path:'pdd-bindings.json'}).content); } catch { fail('inventory', 'invalid JSON'); }
@@ -49,8 +50,7 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
49
50
  const bound = Object.hasOwn(item, 'prompt');
50
51
  const hasStories = Object.hasOwn(item, 'stories');
51
52
  if (!keys(item, bound ? (hasStories ? ['module', 'stories', 'prompt'] : ['module', 'prompt']) : ['module', 'stories', 'reason', 'port_attempt'])) fail(path, 'declare prompt or both reason and port_attempt, with no extra fields');
52
- if(!allowsRuntimePath(workspace,item.module))continue;
53
- regular(item.module); if (seen.has(item.module)) fail(path, 'duplicate module'); seen.add(item.module);
53
+ regular(item.module, true); if (seen.has(item.module)) fail(path, 'duplicate module'); seen.add(item.module);
54
54
  const itemStories = bound && !hasStories ? [] : item.stories;
55
55
  if (!Array.isArray(itemStories) || (!bound && !itemStories.length) || new Set(itemStories).size !== itemStories.length) fail(path, bound ? 'stories must be an array of unique Story paths' : 'stories must be nonempty and unique');
56
56
  for (const story of itemStories) { regular(story); if (!stories.has(story)) fail(path, `unknown Story ${story}`); }
@@ -66,11 +66,10 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
66
66
  continue;
67
67
  }
68
68
  const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
69
- if ((lazyMissing && reached.has(item.prompt)) || (!reached.has(item.prompt) && context.has(item.prompt) && prompt.error === 'interface-missing')) {
70
- const pending = reached.has(item.prompt);
69
+ if (!reached.has(item.prompt) && context.has(item.prompt) && prompt.error === 'interface-missing') {
71
70
  modules.push({path:item.module,state:'unbound',prompt:item.prompt,
72
- reason:pending ? 'Runtime interface pending' : 'Context-only module contract',
73
- port_attempt:pending ? 'lazy interface synthesis pending' : 'no executable Runtime call'});
71
+ reason:'Context-only module contract',
72
+ port_attempt:'no executable Runtime call'});
74
73
  continue;
75
74
  }
76
75
  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`);
@@ -1,7 +1,7 @@
1
- // Generated from prompts/cli/runtime-check-plan.prompt.md (sha256: 764a2cdf6815a01f951ddd339d70b7aa44f7caac0ab93cb021d9164ab2b5d2c2).
1
+ // Generated from prompts/cli/runtime-check-plan.prompt.md (sha256: 081b45f925041a79c1e7ecf6b9b36ff3c4b10166ae0faecccfc138c2c0904780).
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { isAbsolute, posix } from 'node:path';
4
- import { captureSource, readPrompt, sourceFilePort, promptMarkdownTargets } from './runtime-preflight.mjs';
4
+ import { captureSource, readPrompt, sourceFilePort, analyzeStepCallCost, hasSimulationBindings, LAZY_INTERFACE_SYNTHESIS_CALLS } from './runtime-preflight.mjs';
5
5
  import { resultOutcome } from './runtime-outcome.mjs';
6
6
  import { allowsRuntimePath, loadRuntimeWorkspace } from './runtime-workspace.mjs';
7
7
 
@@ -118,37 +118,23 @@ export function buildCheckPlan({ root, found, selected, rows = [], full, base =
118
118
  const key = `${code}\0${path}\0${field}`;
119
119
  if (!seenProblems.has(key)) { seenProblems.add(key); prerequisites.push({code,path,field}); }
120
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; }
121
+ const getPrompt = path => {
123
122
  let prompt = prompts.get(path);
124
123
  if (!prompt) {
125
124
  try { prompt = readPrompt(root, found.visible, path, found.workspace); }
126
125
  catch { prompt = {error:'interface-unavailable'}; }
127
126
  prompts.set(path, prompt);
128
127
  }
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;
128
+ return prompt;
151
129
  };
130
+ const cost = (path, { hasSimulationPorts = false, missingInterfaces = null } = {}) => analyzeStepCallCost(path, {
131
+ getPrompt,
132
+ visible: found.visible,
133
+ allowMissingInterfaces,
134
+ hasSimulationPorts,
135
+ onProblem: problem,
136
+ missingInterfaces,
137
+ });
152
138
  const groups = new Map();
153
139
  for (const test of selected) {
154
140
  const key = test.storyPath ?? test.path;
@@ -254,9 +240,15 @@ export function buildCheckPlan({ root, found, selected, rows = [], full, base =
254
240
  }
255
241
  let estimated = 0;
256
242
  const dispatched = new Set(selectCheckTests({stories},{affected}).tests), budgetRows = [];
243
+ const docsByTest = new Map(selected.map(test => [test.path, test.doc]));
257
244
  for (const row of rows.filter(row=>!affected || dispatched.has(row.test))) {
258
245
  // 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);
246
+ const doc = docsByTest.get(row.test), missingInterfaces = new Set();
247
+ const stepSum = (row.steps ?? []).reduce((sum, step) => sum + cost(step?.entry_path, {
248
+ hasSimulationPorts: hasSimulationBindings(doc, step),
249
+ missingInterfaces,
250
+ }), 0);
251
+ const count = stepSum + missingInterfaces.size * LAZY_INTERFACE_SYNTHESIS_CALLS;
260
252
  if (row.state !== 'ready') continue;
261
253
  const validBound = Number.isSafeInteger(row.max_calls) && row.max_calls >= 1;
262
254
  if (!validBound) problem('undefined-call-bound',row.test,'/max_calls');
@@ -388,14 +380,18 @@ export function checkPlanLines(plan) {
388
380
  const callsLine = disabled
389
381
  ? ` 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
382
  : ` 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 ? [(() => {
383
+ const policyLines = policy ? (() => {
392
384
  const caps = policy.per_request_max_calls?.length ? policy.per_request_max_calls.join(', ') : 'none';
393
385
  const ceiling = policy.max_total_calls != null ? `${policy.max_total_calls} (--max-total-calls)` : 'unbounded';
394
386
  const replacement = disabled ? 'disabled' : 'at most 1 per test on confirmed service-restarted';
395
387
  const prior = policy.unresolved_reservations;
396
388
  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
- })()] : [];
389
+ const lines = [` 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).`];
390
+ if (prior?.count && prior.batches?.length) {
391
+ lines.push(` To reconcile finished prior batches: pdd test --reconcile ${prior.batches[0]} (or pdd test --reconcile-stale).`);
392
+ }
393
+ return lines;
394
+ })() : [];
399
395
  return ['Check plan:', ...plan.stories.flatMap(story=>[
400
396
  ` ${story.role}: ${story.story_path} (${story.tests.join(', ')}); ${story.reason}`,
401
397
  ` dependency closure: ${story.dependency_closure.join(', ') || 'unavailable'}`]),