@promptdriven/runtime-client 1.1.4 → 1.2.1

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.4",
3
+ "version": "1.2.1",
4
4
  "description": "PDD Runtime Client (@promptdriven/runtime-client)",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -1,15 +1,10 @@
1
- // Generated from prompts/cli/lint-compatibility-display.prompt.md (sha256: 73f366ec3d5c86902ce432f5037b2af34a29d67e30ae388bff28d361707d2cb8).
1
+ // Generated from prompts/cli/lint-compatibility-display.prompt.md (sha256: 16b4a020aed753cb2ab66d02518a4fdae69d3a0f793da12587f3899eebfadd65).
2
2
 
3
3
  const countText = (count, singular) => count === 1 ? `1 ${singular}` : `${count} ${singular}s`;
4
4
  const nonblank = value => typeof value === 'string' && value.trim().length > 0;
5
5
  const distinct = values => [...new Set(values)];
6
6
 
7
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
8
  const reported = compatibility?.reported;
14
9
  const structured = reported !== null && typeof reported === 'object' && !Array.isArray(reported)
15
10
  && Array.isArray(reported.operations) && Array.isArray(reported.edges);
@@ -37,6 +32,25 @@ export function describeCompatibility({ label, compatibility, clientAdvice = nul
37
32
  summary += '.';
38
33
  }
39
34
  const lines = [summary];
35
+ if (details) {
36
+ if (structured) {
37
+ for (const item of reported.operations) {
38
+ if (item.verdict === 'supported') continue;
39
+ lines.push(` Non-supported operation (${item.selection.step_id}): ${item.selection.prompt_path}#${item.selection.operation} — ${item.verdict} (${item.reason_code})`);
40
+ }
41
+ for (const item of reported.edges) {
42
+ if (item.verdict === 'supported') continue;
43
+ const edge = item.selection.edge;
44
+ lines.push(` Non-supported edge (${item.selection.step_id}): ${edge.edge_id} (${edge.kind} ${edge.call_operation}) — ${item.verdict} (${item.reason_code})`);
45
+ }
46
+ }
47
+ if (Array.isArray(reported?.diagnostics)) {
48
+ for (const item of reported.diagnostics) {
49
+ const parts = [item?.code, item?.path, item?.section].filter(nonblank);
50
+ if (parts.length > 0) lines.push(` Diagnostic: ${parts.join(' ')}`);
51
+ }
52
+ }
53
+ }
40
54
  if (clientAdvice !== null && clientAdvice !== undefined) {
41
55
  lines.push(` Client advice (${clientAdvice.owner}): ${clientAdvice.next_step}`);
42
56
  }
@@ -9,6 +9,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
9
9
  import { captureSource, gitFiles, interfaceBlocks, sourceFilePort, findTests } from './runtime-preflight.mjs';
10
10
  import { createProgramContext, admitProgram, runDoorCall, withRepositoryRunLock, saveDoorCaseResult, acquireCaseWriteOwnership } from './runtime-client.mjs';
11
11
  import { openServe, parseServeOptions, SERVE_OPTION_KEYS } from './try-http.mjs';
12
+ import { withReceiptUsage } from './runtime-output.mjs';
12
13
  import { projectTryCall } from './try-session.mjs';
13
14
 
14
15
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -325,7 +326,7 @@ export async function runProgram({ file, argv = [], options = {}, cwd = process.
325
326
  if (latest?.id !== session.id || latest.state !== 'unknown' || latest.stop_id !== id) throw failure('This stop was superseded.', 125);
326
327
  const { stop_id, ...retained } = latest;
327
328
  session = { ...retained, state: stopped ? 'stopped' : 'running' };
328
- context.store.write(join(context.folder, `${id}.json`), job);
329
+ context.store.write(join(context.folder, `${id}.json`), withReceiptUsage(job));
329
330
  writePrivate(sessionPath, session);
330
331
  });
331
332
  if (!stopped) throw failure(`${job.result?.refusals?.[0]?.message ?? 'The interpreter did not confirm that the old program stopped.'} Run the program again when ready.`, 125);
@@ -453,7 +454,7 @@ export async function runProgram({ file, argv = [], options = {}, cwd = process.
453
454
  locked(() => { const latest = readPrivate(sessionPath); if (latest?.id !== previous?.id) throw failure('Another process changed this program session; run again.', 125); writePrivate(sessionPath, session); });
454
455
  const pending = structuredClone(session);
455
456
  let opened;
456
- try { opened = await admitProgram(context, capture, { requestId: id, entry, appMap, initial_world: JSON.parse(plan.initial_world_json), simulation: JSON.parse(plan.simulation_json), max_calls: options['--max-calls'] ?? 400, tab: invocation.door === 'screen' ? 'screen' : ['cli', 'shell'].includes(invocation.door) ? 'terminal' : 'call' }); }
457
+ try { opened = await admitProgram(context, capture, { requestId: id, entry, appMap, initial_world: JSON.parse(plan.initial_world_json), simulation: JSON.parse(plan.simulation_json), ...(options['--max-calls'] !== undefined ? { max_calls: options['--max-calls'] } : {}), tab: invocation.door === 'screen' ? 'screen' : ['cli', 'shell'].includes(invocation.door) ? 'terminal' : 'call' }); }
457
458
  catch (error) { if (!error.unknownOutcome) locked(() => { if (readPrivate(sessionPath)?.id === id) { if (previous) writePrivate(sessionPath, previous); else unlinkSync(sessionPath); } }); throw error; }
458
459
  locked(() => { const latest = readPrivate(sessionPath); if (!isDeepStrictEqual(latest, pending) || latest?.state !== 'unknown' || latest.stop_id) throw failure('Program session was superseded.', 125); session = { ...pending, id: opened.id, url: opened.url, state: 'running' }; writePrivate(sessionPath, session); writePrivate(dataPath, JSON.parse(plan.initial_world_json)); });
459
460
  }
@@ -33,21 +33,58 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
33
33
  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');
34
34
  if (inventory.modules.length > 1000) fail('inventory', 'exceeds 1000 module declarations');
35
35
  const stories = new Set(found.stories.map(s => s.path)), chosen = new Set(selected.map(t => t.storyPath)), seen = new Set(), modules = [];
36
- const reached = new Set(), context = new Set(), visited = new Set(), promptCache = new Map();
36
+ const promptCache = new Map();
37
37
  const getPrompt = path => {
38
38
  if (!promptCache.has(path)) promptCache.set(path, readPrompt(root, found.visible, path, workspace));
39
39
  return promptCache.get(path);
40
40
  };
41
- const queue = selected.flatMap(t => (Array.isArray(t.doc?.steps) ? t.doc.steps : []).map(s => ({path:s?.entry_path, executable:true})));
42
- while (queue.length) {
43
- const {path,executable} = queue.shift(), identity = `${executable ? 'call' : 'context'}:${path}`;
44
- if (typeof path !== 'string' || visited.has(identity)) continue;
45
- visited.add(identity);
46
- (executable ? reached : context).add(path);
47
- const prompt = getPrompt(path);
48
- for (const call of Array.isArray(prompt?.interface?.calls) ? prompt.interface.calls : []) if (typeof call?.target === 'string') queue.push({path:call.target,executable});
49
- for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) queue.push({path:target,executable:false});
41
+ const collectReach = tests => {
42
+ const reached = new Set(), context = new Set(), visited = new Set();
43
+ const queue = tests.flatMap(t => (Array.isArray(t.doc?.steps) ? t.doc.steps : []).map(s => ({ path: s?.entry_path, executable: true })));
44
+ while (queue.length) {
45
+ const { path, executable } = queue.shift(), identity = `${executable ? 'call' : 'context'}:${path}`;
46
+ if (typeof path !== 'string' || visited.has(identity)) continue;
47
+ visited.add(identity);
48
+ (executable ? reached : context).add(path);
49
+ const prompt = getPrompt(path);
50
+ for (const call of Array.isArray(prompt?.interface?.calls) ? prompt.interface.calls : []) if (typeof call?.target === 'string') queue.push({ path: call.target, executable });
51
+ for (const target of promptMarkdownTargets(prompt.text, path, found.visible)) queue.push({ path: target, executable: false });
52
+ }
53
+ return { reached, context };
54
+ };
55
+ const { reached, context } = collectReach(selected);
56
+ const selectedPathsByStory = new Map(), selectedSyntheticByStory = new Set();
57
+ for (const t of selected) {
58
+ if (!t?.storyPath) continue;
59
+ if (typeof t.path === 'string' && t.path) {
60
+ if (!selectedPathsByStory.has(t.storyPath)) selectedPathsByStory.set(t.storyPath, new Set());
61
+ selectedPathsByStory.get(t.storyPath).add(t.path);
62
+ } else selectedSyntheticByStory.add(t.storyPath);
63
+ }
64
+ const allExecutableByStory = new Map();
65
+ for (const t of Array.isArray(found.tests) ? found.tests : []) {
66
+ if (!t?.storyPath || t.error || !object(t.doc) || typeof t.path !== 'string' || !t.path) continue;
67
+ if (!allExecutableByStory.has(t.storyPath)) allExecutableByStory.set(t.storyPath, []);
68
+ allExecutableByStory.get(t.storyPath).push(t);
69
+ }
70
+ const partialStories = new Set();
71
+ for (const [storyPath, selectedPaths] of selectedPathsByStory) {
72
+ if (selectedSyntheticByStory.has(storyPath)) continue;
73
+ const allTests = allExecutableByStory.get(storyPath);
74
+ if (!allTests || allTests.length < 2) continue;
75
+ const allPaths = new Set(allTests.map(t => t.path));
76
+ if (selectedPaths.size < allPaths.size && [...selectedPaths].every(p => allPaths.has(p))) partialStories.add(storyPath);
50
77
  }
78
+ const siblingReachCache = new Map();
79
+ const siblingReach = storyPath => {
80
+ if (!siblingReachCache.has(storyPath)) {
81
+ const selectedPaths = selectedPathsByStory.get(storyPath);
82
+ const siblings = (allExecutableByStory.get(storyPath) ?? []).filter(t => !selectedPaths?.has(t.path));
83
+ siblingReachCache.set(storyPath, collectReach(siblings));
84
+ }
85
+ return siblingReachCache.get(storyPath);
86
+ };
87
+ const hasValidInterface = prompt => !prompt.error && Array.isArray(prompt?.interface?.entries) && prompt.interface.entries.length > 0 && !prompt.interface.entries.some(entry => !entry || typeof entry.operation !== 'string' || !entry.operation.trim() || !object(entry.input_schema) || !object(entry.result_schema));
51
88
  for (const item of inventory.modules) {
52
89
  const path = item?.module ?? 'module';
53
90
  if (!object(item)) fail(path, 'expected module declaration');
@@ -60,7 +97,8 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
60
97
  for (const story of itemStories) { regular(story); if (!stories.has(story)) fail(path, `unknown Story ${story}`); }
61
98
  if (bound) { regular(item.prompt); if (!item.prompt.endsWith('.prompt.md')) fail(path, `${item.prompt} must be a *.prompt.md file`); }
62
99
  else for (const key of ['reason', 'port_attempt']) if (typeof item[key] !== 'string' || !item[key].trim()) fail(path, `${key} must be nonblank`);
63
- const selectedByStories = itemStories.some(story => chosen.has(story));
100
+ const chosenItemStories = itemStories.filter(story => chosen.has(story));
101
+ const selectedByStories = chosenItemStories.length > 0;
64
102
  const selectedByReach = bound && !hasStories && (reached.has(item.prompt) || context.has(item.prompt));
65
103
  if (!selectedByStories && !selectedByReach) continue;
66
104
  if (bound) {
@@ -71,6 +109,13 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
71
109
  modules.push({ path: item.module, state: 'unbound', prompt: item.prompt, reason: prompt.interface.reason.trim(), port_attempt: 'native-only prompt' });
72
110
  continue;
73
111
  }
112
+ const partialOnly = selectedByStories && chosenItemStories.every(story => partialStories.has(story));
113
+ if (!reached.has(item.prompt) && partialOnly) {
114
+ const reachedBySibling = chosenItemStories.some(story => siblingReach(story).reached.has(item.prompt));
115
+ if (reachedBySibling && (hasValidInterface(prompt) || (prompt.error === 'interface-missing' && typeof prompt.text === 'string' && prompt.text.trim()))) continue;
116
+ const contextBySibling = !reachedBySibling && !context.has(item.prompt) && chosenItemStories.some(story => siblingReach(story).context.has(item.prompt));
117
+ if (contextBySibling && prompt.error === 'interface-missing' && typeof prompt.text === 'string' && prompt.text.trim()) continue;
118
+ }
74
119
  const lazyMissing = allowMissingInterfaces && prompt.error === 'interface-missing';
75
120
  if (!reached.has(item.prompt) && context.has(item.prompt) && (prompt.error === 'interface-missing' || (!hasStories && !prompt.error))) {
76
121
  modules.push({path:item.module,state:'unbound',prompt:item.prompt,
@@ -78,7 +123,7 @@ export function bindingCoverage({ root, found, selected, includeRuntime = false,
78
123
  port_attempt:'no executable Runtime call'});
79
124
  continue;
80
125
  }
81
- 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`);
126
+ if (!reached.has(item.prompt) || (!lazyMissing && !hasValidInterface(prompt))) fail(path, `${item.prompt} must be reached and have an executable Runtime interface`);
82
127
  }
83
128
  modules.push({ path: item.module, state: bound ? 'bound' : 'unbound', ...(bound ? {} : { reason: item.reason, port_attempt: item.port_attempt }) });
84
129
  }
@@ -60,10 +60,15 @@ export function estimateCheckCalls({ prompts = [], rows = [] } = {}) {
60
60
  for (const row of rows) {
61
61
  const count = (row.steps ?? []).reduce((sum, step) => sum + cost(step?.entry_path), 0);
62
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 {
63
+ const explicitBound = Number.isSafeInteger(row.max_calls) && row.max_calls >= 1;
64
+ const serverOwned = row.max_calls === null;
65
+ if (!explicitBound && !serverOwned) problem('undefined-call-bound', row.test, '/max_calls');
66
+ else if (explicitBound) {
65
67
  estimated += Math.min(row.max_calls, count);
66
- maximum += row.max_calls * 2;
68
+ if (maximum !== null) maximum += row.max_calls * 2;
69
+ } else {
70
+ estimated += count;
71
+ maximum = null;
67
72
  }
68
73
  requests += 2;
69
74
  }
@@ -276,10 +281,11 @@ export function buildCheckPlan({ root, found, selected, rows = [], full, base =
276
281
  }), 0);
277
282
  const count = stepSum + missingInterfaces.size * LAZY_INTERFACE_SYNTHESIS_CALLS;
278
283
  if (row.state !== 'ready') continue;
279
- const validBound = Number.isSafeInteger(row.max_calls) && row.max_calls >= 1;
280
- if (!validBound) problem('undefined-call-bound',row.test,'/max_calls');
281
- else estimated += Math.min(row.max_calls, count);
282
- budgetRows.push({ test: row.test, max_calls: validBound ? row.max_calls : 0, restart_used: false, attempts: [] });
284
+ const explicitBound = Number.isSafeInteger(row.max_calls) && row.max_calls >= 1;
285
+ const serverOwned = row.max_calls === null;
286
+ if (!explicitBound && !serverOwned) problem('undefined-call-bound',row.test,'/max_calls');
287
+ else estimated += explicitBound ? Math.min(row.max_calls, count) : count;
288
+ budgetRows.push({ test: row.test, max_calls: explicitBound ? row.max_calls : (serverOwned ? null : 0), restart_used: false, attempts: [] });
283
289
  }
284
290
  const prior = {
285
291
  count: Number.isSafeInteger(unresolvedReservations?.count) && unresolvedReservations.count >= 0 ? unresolvedReservations.count : 0,
@@ -306,8 +312,13 @@ export function buildCheckPlan({ root, found, selected, rows = [], full, base =
306
312
  export function evaluateCheckBudget({ max_total_calls = null, single_attempt = false, unresolved_prior_reservations = { count: 0, reserved_calls: 0 }, rows = [], candidate = null } = {}) {
307
313
  const multiplier = single_attempt ? 1 : 2;
308
314
  const per_request_caps = [...new Set(rows.map(row => row.max_calls).filter(value => Number.isSafeInteger(value) && value >= 1))].sort((a, b) => a - b);
309
- const unbounded_maximum = rows.reduce((sum, row) => sum + (Number.isSafeInteger(row.max_calls) && row.max_calls >= 1 ? row.max_calls * multiplier : 0), 0);
310
- const planned_maximum = max_total_calls === null ? unbounded_maximum : Math.min(unbounded_maximum, max_total_calls);
315
+ const hasServerOwnedCap = rows.some(row => row.max_calls === null);
316
+ const unbounded_maximum = hasServerOwnedCap
317
+ ? null
318
+ : rows.reduce((sum, row) => sum + (Number.isSafeInteger(row.max_calls) && row.max_calls >= 1 ? row.max_calls * multiplier : 0), 0);
319
+ const planned_maximum = max_total_calls === null
320
+ ? unbounded_maximum
321
+ : (unbounded_maximum === null ? max_total_calls : Math.min(unbounded_maximum, max_total_calls));
311
322
  const plan = {
312
323
  per_request_caps,
313
324
  max_total_calls,
@@ -324,7 +335,7 @@ export function evaluateCheckBudget({ max_total_calls = null, single_attempt = f
324
335
  let consumed_known = 0, unresolved_reserved = 0, in_flight_reserved = 0;
325
336
  for (const row of rows) {
326
337
  for (const attempt of row.attempts ?? []) {
327
- const floor = Math.max(attempt.requested_max_calls, (attempt.known_calls ?? 0) + (attempt.unknown_calls ?? 0));
338
+ const floor = Math.max(attempt.requested_max_calls ?? 0, (attempt.known_calls ?? 0) + (attempt.unknown_calls ?? 0));
328
339
  if (attempt.status === 'capacity_refused_zero') continue;
329
340
  if (attempt.status === 'settled') consumed_known += attempt.known_calls;
330
341
  else if (attempt.status === 'in_flight') in_flight_reserved += floor;
@@ -344,12 +355,17 @@ export function evaluateCheckBudget({ max_total_calls = null, single_attempt = f
344
355
  decision = { action: 'refuse-replacement', reason_code: 'restart-replacement-disabled', effective_max_calls: 0, retain_prior_uncertainty: true };
345
356
  } else {
346
357
  const retain_prior_uncertainty = candidate.kind === 'restart-replacement';
347
- if (max_total_calls === null || remaining_calls >= candidate.requested_max_calls) {
348
- decision = { action: 'send', reason_code: 'within-budget', effective_max_calls: candidate.requested_max_calls, retain_prior_uncertainty };
358
+ const requestedCap = Number.isSafeInteger(candidate.requested_max_calls) && candidate.requested_max_calls >= 1
359
+ ? candidate.requested_max_calls : null;
360
+ if (max_total_calls === null) {
361
+ decision = { action: 'send', reason_code: 'within-budget', effective_max_calls: requestedCap, retain_prior_uncertainty };
362
+ } else if (requestedCap !== null && remaining_calls >= requestedCap) {
363
+ decision = { action: 'send', reason_code: 'within-budget', effective_max_calls: requestedCap, retain_prior_uncertainty };
349
364
  } else if (in_flight_reserved > 0 && Math.max(0, max_total_calls - (consumed_known + unresolved_reserved)) > remaining_calls) {
350
365
  decision = { action: 'wait', reason_code: 'awaiting-in-flight-settlement', effective_max_calls: 0, retain_prior_uncertainty };
351
366
  } else if (remaining_calls >= 1) {
352
- decision = { action: 'send', reason_code: 'clamped-to-remaining-budget', effective_max_calls: remaining_calls, retain_prior_uncertainty };
367
+ const clampedCap = requestedCap === null ? Math.min(1000, remaining_calls) : remaining_calls;
368
+ decision = { action: 'send', reason_code: 'clamped-to-remaining-budget', effective_max_calls: clampedCap, retain_prior_uncertainty };
353
369
  } else {
354
370
  decision = { action: 'block', reason_code: 'call-budget-exhausted', effective_max_calls: 0, retain_prior_uncertainty };
355
371
  }
@@ -407,7 +423,7 @@ export function checkPlanLines(plan) {
407
423
  ? ` 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.`
408
424
  : ` 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.`;
409
425
  const policyLines = policy ? (() => {
410
- const caps = policy.per_request_max_calls?.length ? policy.per_request_max_calls.join(', ') : 'none';
426
+ const caps = policy.per_request_max_calls?.length ? policy.per_request_max_calls.join(', ') : 'server default';
411
427
  const ceiling = policy.max_total_calls != null ? `${policy.max_total_calls} (--max-total-calls)` : 'unbounded';
412
428
  const replacement = disabled ? 'disabled' : 'at most 1 per test on confirmed service-restarted';
413
429
  const prior = policy.unresolved_reservations;
@@ -207,7 +207,7 @@ export function projectCheckReconciliation({ request_id, status, body }) {
207
207
 
208
208
  if (acct.status === 'complete_zero') {
209
209
  const validZero =
210
- disp.state === 'refused' &&
210
+ (disp.state === 'refused' || (disp.state === 'passed' && retry.blocked === true)) &&
211
211
  disp.terminal === true &&
212
212
  disp.expired === false &&
213
213
  disp.purged === false &&
@@ -27,7 +27,7 @@ import { DRAFT_SERVER_TEXT, PreflightError, TEST_SCHEMA, LIMITS, captureSource,
27
27
  import { catalogRecords, compareCopies } from './contract-refs.mjs';
28
28
  import { jsonSafe, parseScenarioJson } from './scenario-json.mjs';
29
29
  import { scenarioDerivationRefusal } from './runtime-preflight.mjs';
30
- import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refusalView, renderJson, renderText, summaryLine, stepTimeLimit, tokenUsageOf, tryUsage, validLink, coverageText } from './runtime-output.mjs';
30
+ import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refusalView, renderJson, renderText, summaryLine, stepTimeLimit, tokenUsageOf, tryUsage, validLink, coverageText, withReceiptUsage } from './runtime-output.mjs';
31
31
  import { adaptivePollMs, isSseContentType, parseSseStream, preferWaitHeaders, SSE_IDLE_MS, WAIT_PREFER_CALL_SECONDS, WAIT_PREFER_RUN_SECONDS } from './runtime-stream.mjs';
32
32
  import { DEFAULT_CHECK_CONCURRENCY, createAdaptiveConcurrency, recordContention, recordCleanSuccess } from './adaptive-concurrency.mjs';
33
33
 
@@ -55,6 +55,28 @@ function isPlainProseUiPromptText(text) {
55
55
  const low = text.toLowerCase();
56
56
  return low.includes('render') || low.includes('<main') || low.includes('html') || low.includes('data-pdd-op');
57
57
  }
58
+ function isInterfaceHtmlScreenPrompt(prompt) {
59
+ const entries = Array.isArray(prompt?.interface?.entries) ? prompt.interface.entries : [];
60
+ if (!entries.length) return false;
61
+ const conventions = Array.isArray(prompt?.interface?.conventions) ? prompt.interface.conventions : [];
62
+ for (const entry of entries) {
63
+ const title = entry?.input_schema?.title;
64
+ if (typeof title !== 'string') continue;
65
+ const match = /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\/\S*)$/.exec(title);
66
+ if (!match) continue;
67
+ const [, method, path] = match;
68
+ if (((method === 'GET' || method === 'HEAD') && path === '/') || path.startsWith('/__pdd/screen/')) return false;
69
+ }
70
+ return entries.some((entry, index) => {
71
+ if (entry?.operation !== 'render') return false;
72
+ if (typeof entry?.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title)) return false;
73
+ if (['input_schema', 'result_schema'].every(key => conventions.some(c => c?.path === `/entries/${index}/${key}` && c.convention === 'cli'))) return false;
74
+ const res = entry.result_schema;
75
+ if (!isObject(res)) return false;
76
+ if (res.type === 'object' && Array.isArray(res.required) && res.required.includes('html') && res.properties?.html?.type === 'string') return true;
77
+ return res.type === 'string' && typeof prompt.text === 'string' && /html|<main|\.ui\.svg|kind\s*:\s*screen/i.test(prompt.text);
78
+ });
79
+ }
58
80
  function hasMissingPromptInterface(root, found, startPaths) {
59
81
  const seen = new Set(), queue = [...startPaths];
60
82
  while (queue.length) {
@@ -116,6 +138,11 @@ const POST_MS = 90_000, GET_MS = 30_000, TRY_MS = 300_000, MAX_READS = 8, PROGRE
116
138
  const AGENT_WAIT_MIN = 1.5;
117
139
  // Under load a POST can time out and its job appear 3 to 4 min later: read a lost answer's ID for 5 min.
118
140
  const LOST_READ_MS = 300_000;
141
+ // After a lost POST (or unconfirmed run), finalize on persistent HTTP 404 once at least 3 consecutive
142
+ // 404s have been observed across a 15s grace window so in-flight server admission commits can settle
143
+ // without polling dead 404 runs for the full LOST_READ_MS.
144
+ const MISSING_GRACE_MS = 15_000;
145
+ const MISSING_MIN_POLLS = 3;
119
146
  // Unresolved prior local batch reservations automatically expire after 24 hours (override via PDD_PRIOR_RESERVATION_TTL_HOURS).
120
147
  const PRIOR_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
121
148
  // Completed/reconciled local batch directories older than 14 days are eligible for automatic GC (override via PDD_BATCH_RETENTION_DAYS; 0 disables).
@@ -1456,6 +1483,9 @@ class Runtime {
1456
1483
  this.uploadedSources = new Set();
1457
1484
  this.uploadingSources = new Map();
1458
1485
  this.sourceUploadDisabled = false;
1486
+ this.syncedTrees = new Map();
1487
+ this.syncingTrees = new Map();
1488
+ this.blobSyncDisabled = false;
1459
1489
  }
1460
1490
  async sendOnce(path, init, ms) {
1461
1491
  const readSignal = init?.method === 'GET' ? init.signal : null;
@@ -1585,6 +1615,92 @@ class Runtime {
1585
1615
  else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
1586
1616
  return retry;
1587
1617
  }
1618
+ async syncTree(sha256Hex, sources, timeoutMs = this.ports.postMs) {
1619
+ if (this.blobSyncDisabled || !Array.isArray(sources) || typeof sha256Hex !== 'string' || !/^[a-f0-9]{64}$/.test(sha256Hex)) return null;
1620
+ if (this.syncedTrees.has(sha256Hex)) return this.syncedTrees.get(sha256Hex);
1621
+ if (this.syncingTrees.has(sha256Hex)) return this.syncingTrees.get(sha256Hex);
1622
+ const pending = (async () => {
1623
+ const files = {};
1624
+ const blobsBySha = new Map();
1625
+ const sorted = [...sources].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
1626
+ for (const file of sorted) {
1627
+ const buf = Buffer.isBuffer(file.bytes) ? file.bytes : Buffer.from(file.bytes);
1628
+ const digest = sha256(buf);
1629
+ files[file.path] = { sha256: digest, mode: '0600', bytes: buf.length };
1630
+ if (!blobsBySha.has(digest)) blobsBySha.set(digest, buf);
1631
+ }
1632
+ const treeReply = await this.send('/v1/trees', {
1633
+ method: 'POST',
1634
+ headers: { 'Content-Type': 'application/json' },
1635
+ body: () => JSON.stringify({ files, source_sha256: sha256Hex }),
1636
+ }, timeoutMs);
1637
+ if ([404, 405, 415, 501].includes(treeReply.status)) {
1638
+ this.blobSyncDisabled = true;
1639
+ return null;
1640
+ }
1641
+ const treeSha = treeReply.status === 200
1642
+ && typeof treeReply.json?.tree_sha256 === 'string'
1643
+ && /^[a-f0-9]{64}$/.test(treeReply.json.tree_sha256)
1644
+ ? treeReply.json.tree_sha256 : null;
1645
+ if (!treeSha) return null;
1646
+ const missing = Array.isArray(treeReply.json?.missing_blobs) ? treeReply.json.missing_blobs : [];
1647
+ if (missing.length === 1) {
1648
+ const digest = missing[0];
1649
+ const buf = blobsBySha.get(digest);
1650
+ if (!buf) return null;
1651
+ const blobReply = await this.send('/v1/blobs', {
1652
+ method: 'POST',
1653
+ headers: { 'Content-Type': 'application/octet-stream', 'X-Blob-Sha256': digest },
1654
+ body: () => new Blob([buf], { type: 'application/octet-stream' }),
1655
+ }, timeoutMs);
1656
+ if ([404, 405, 415, 501].includes(blobReply.status)) {
1657
+ this.blobSyncDisabled = true;
1658
+ return null;
1659
+ }
1660
+ if (blobReply.status !== 200 || blobReply.json?.sha256 !== digest) return null;
1661
+ } else if (missing.length > 1) {
1662
+ const MAX_BATCH_BYTES = 8 * 1024 * 1024;
1663
+ const MAX_BATCH_COUNT = 512;
1664
+ let batch = [];
1665
+ let batchBytes = 0;
1666
+ const flushBatch = async () => {
1667
+ if (!batch.length) return true;
1668
+ const items = batch;
1669
+ batch = [];
1670
+ batchBytes = 0;
1671
+ const makeBlobForm = () => {
1672
+ const form = new FormData();
1673
+ for (const { digest, buf } of items) {
1674
+ form.append(digest, new Blob([buf], { type: 'application/octet-stream' }), digest);
1675
+ }
1676
+ return form;
1677
+ };
1678
+ const blobReply = await this.send('/v1/blobs', { method: 'POST', body: makeBlobForm }, timeoutMs);
1679
+ if ([404, 405, 415, 501].includes(blobReply.status)) {
1680
+ this.blobSyncDisabled = true;
1681
+ return false;
1682
+ }
1683
+ return blobReply.status === 200 && blobReply.json?.count === items.length;
1684
+ };
1685
+ for (const digest of missing) {
1686
+ const buf = blobsBySha.get(digest);
1687
+ if (!buf) return null;
1688
+ if (batch.length && (batchBytes + buf.length > MAX_BATCH_BYTES || batch.length >= MAX_BATCH_COUNT)) {
1689
+ if (!await flushBatch()) return null;
1690
+ }
1691
+ batch.push({ digest, buf });
1692
+ batchBytes += buf.length;
1693
+ }
1694
+ if (!await flushBatch()) return null;
1695
+ }
1696
+ this.syncedTrees.set(sha256Hex, treeSha);
1697
+ return treeSha;
1698
+ })().finally(() => {
1699
+ if (this.syncingTrees.get(sha256Hex) === pending) this.syncingTrees.delete(sha256Hex);
1700
+ });
1701
+ this.syncingTrees.set(sha256Hex, pending);
1702
+ return pending;
1703
+ }
1588
1704
  async uploadSource(sha256Hex, tar, timeoutMs = this.ports.postMs) {
1589
1705
  if (this.sourceUploadDisabled || !tar || typeof sha256Hex !== 'string' || !/^[a-f0-9]{64}$/.test(sha256Hex)) return false;
1590
1706
  if (this.uploadedSources.has(sha256Hex)) return true;
@@ -1625,6 +1741,43 @@ class Runtime {
1625
1741
  if (sha && [200, 202].includes(reply.status)) this.uploadedSources.add(sha);
1626
1742
  return reply;
1627
1743
  };
1744
+ const useBlobSync = options?.blobSync === true && !this.blobSyncDisabled
1745
+ && Array.isArray(options?.sources) && typeof request?.source_sha256 === 'string' && /^[a-f0-9]{64}$/.test(request.source_sha256);
1746
+ if (useBlobSync) {
1747
+ const shaHex = request.source_sha256;
1748
+ const sendViaTree = async (treeSha) => this.send(path, {
1749
+ method: 'POST',
1750
+ headers: { 'Content-Type': 'application/json' },
1751
+ body: () => JSON.stringify({ ...request, tree_sha256: treeSha }),
1752
+ }, timeoutMs);
1753
+ let treeSha = await this.syncTree(shaHex, options.sources, timeoutMs);
1754
+ if (treeSha) {
1755
+ let reply = await sendViaTree(treeSha);
1756
+ let code = reply.json?.error?.code ?? reply.json?.code;
1757
+ if ([404, 409, 422].includes(reply.status) && code === 'source-not-found'
1758
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
1759
+ this.syncedTrees.delete(shaHex);
1760
+ treeSha = await this.syncTree(shaHex, options.sources, timeoutMs);
1761
+ if (treeSha) {
1762
+ reply = await sendViaTree(treeSha);
1763
+ code = reply.json?.error?.code ?? reply.json?.code;
1764
+ }
1765
+ if (!treeSha || ([404, 409, 422].includes(reply.status) && code === 'source-not-found'
1766
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown')) {
1767
+ this.syncedTrees.delete(shaHex);
1768
+ return postInline();
1769
+ }
1770
+ }
1771
+ if (((reply.status === 415 && code === 'unsupported-content-type')
1772
+ || (reply.status === 400 && code === 'invalid-request' && reply.json?.error?.details?.field === 'tree_sha256'))
1773
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
1774
+ this.blobSyncDisabled = true;
1775
+ this.syncedTrees.delete(shaHex);
1776
+ return postInline();
1777
+ }
1778
+ return reply;
1779
+ }
1780
+ }
1628
1781
  if (!sha) return postInline();
1629
1782
  if (options?.inlineFirst === true && !this.uploadedSources.has(sha)) return postInline();
1630
1783
  if (!this.uploadedSources.has(sha)) {
@@ -3558,7 +3711,7 @@ function budgetRowsForContext(context, excludePendingRow = null) {
3558
3711
  const terminalReceipt = latest && sameJob(latest, id, 'check') && accountingEnd(latest, id);
3559
3712
  const unknownWithoutExplicitProof = latest?.state === 'unknown'
3560
3713
  && ![latest, latest?.usage, latest?.result, latest?.report, latest?.result?.report].some(s => isObject(s) && s.accounting_complete === true);
3561
- if (isLatest && !terminalReceipt && (OPEN_STATES.has(row.state) || activeLost)) {
3714
+ if (isLatest && !terminalReceipt && (OPEN_STATES.has(row.state) || activeLost || row.admitting)) {
3562
3715
  attempts.push({ id, kind, requested_max_calls, status: 'in_flight', known_calls: part.known, unknown_calls: part.complete ? 0 : part.unknown, reason_code });
3563
3716
  } else if (!hasCapacityEvidence && !unknownWithoutExplicitProof && part.complete && Number.isSafeInteger(part.total)) {
3564
3717
  attempts.push({ id, kind, requested_max_calls, status: 'settled', known_calls: part.total, unknown_calls: 0, reason_code });
@@ -3570,7 +3723,7 @@ function budgetRowsForContext(context, excludePendingRow = null) {
3570
3723
  attempts.push({ id: 'incomplete-claim', kind: row.restart_used ? 'restart-replacement' : 'initial',
3571
3724
  requested_max_calls: row.max_calls, status: 'unresolved', known_calls: 0, unknown_calls: 1, reason_code: 'dispatch-incomplete' });
3572
3725
  }
3573
- if (row !== excludePendingRow && Number.isSafeInteger(row.budget_in_flight) && row.budget_in_flight >= 1) {
3726
+ if (row !== excludePendingRow && Number.isSafeInteger(row.budget_in_flight) && row.budget_in_flight >= 1 && !attempts.some(a => a.status === 'in_flight')) {
3574
3727
  attempts.push({ id: 'pending-dispatch', kind: row.restart_pending ? 'restart-replacement' : 'initial',
3575
3728
  requested_max_calls: row.budget_in_flight, status: 'in_flight', known_calls: 0, unknown_calls: 0, reason_code: null });
3576
3729
  }
@@ -3669,18 +3822,23 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
3669
3822
  if (row) delete row.prior_restart_snapshot; // Dispatch is now uncertain; never roll it back.
3670
3823
  if (row) { if (!row.request_ids.includes(id)) row.request_ids.push(id); row.sent_at ??= context.ports.now(); row.state = 'sending'; row.phase = 'server'; row.calls = 'unknown'; row.post_verdict = 'uncertain'; }
3671
3824
  saveBatch(context);
3825
+ const blobSync = Boolean(context.serverFeatures?.includes('blob-sync-v1') && Array.isArray(context.capture?.sources));
3672
3826
  const dedup = Boolean(context.serverFeatures?.includes('source-upload-v1'));
3673
3827
  const pendingChecks = command === 'check'
3674
3828
  ? (context.rows ?? []).filter(item => !item.unsent && ['ready', 'waiting', 'sending'].includes(item.state)).length
3675
3829
  : 0;
3676
- const inlineFirst = (command === 'lint' || (command === 'check' && pendingChecks <= 1))
3830
+ const inlineFirst = !blobSync
3831
+ && (command === 'lint' || (command === 'check' && pendingChecks <= 1))
3677
3832
  && (!dedup || Buffer.byteLength(JSON.stringify(request), 'utf8') <= 60_000);
3833
+ const postOptions = (blobSync || dedup)
3834
+ ? { ...(blobSync ? { blobSync: true, sources: context.capture.sources } : {}), ...(dedup ? { dedup: true, inlineFirst } : {}) }
3835
+ : undefined;
3678
3836
  const reply = await context.runtime.post(
3679
3837
  path,
3680
3838
  request,
3681
3839
  context.capture.tar,
3682
3840
  Math.max(1, Math.min(timeoutMs, deadline - context.ports.now())),
3683
- dedup ? { dedup: true, inlineFirst } : undefined,
3841
+ postOptions,
3684
3842
  );
3685
3843
  const verdict = judgePost(reply, id, command, context.secrets);
3686
3844
  verdict.observed_at = context.ports.now();
@@ -3711,7 +3869,7 @@ async function sendCheck(context, row) {
3711
3869
  }
3712
3870
  async function sendCheckAttempt(context, row, deadline = rowDeadline(context, row)) {
3713
3871
  if (context.interrupted || context.ports.now() >= deadline || !['ready', 'waiting'].includes(row.state)) return;
3714
- if (context.checkOptions && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
3872
+ if (context.checkOptions && Number.isSafeInteger(row.max_calls) && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
3715
3873
  // Recheck the saved raw cohort immediately before any capacity-driven new ID.
3716
3874
  // The one structured restart replacement has its own durable fuse and remains allowed.
3717
3875
  if (row.request_ids.length && (row.busy || row.capacity_uncertain) && !row.restart_pending && !capacityRetryAllowed(context, row)) {
@@ -3736,7 +3894,7 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3736
3894
  if (preDecision.action === 'wait') { row.awaiting_budget = true; return; }
3737
3895
  if (preDecision.action !== 'send') { applyBudgetDecisionStop(context, row, preDecision); return; }
3738
3896
  row.awaiting_budget = false;
3739
- row.budget_in_flight = preDecision.effective_max_calls;
3897
+ row.budget_in_flight = Number.isSafeInteger(preDecision.effective_max_calls) && preDecision.effective_max_calls >= 1 ? preDecision.effective_max_calls : 0;
3740
3898
  const attempt = row.request_ids.length, previousCalls = row.restart_used || row.restart_pending ? accumulatedCalls(context, row) : 0;
3741
3899
  if (!await admission(context, 'check', row, deadline)) {
3742
3900
  if (context.interrupted && interruptedAdmissions.has(row)) Object.assign(row, { state: 'not_run', calls: previousCalls, phase: 'local', note: { code: null, message: 'Stopped before sending.' } });
@@ -3774,12 +3932,12 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3774
3932
  return;
3775
3933
  }
3776
3934
  const effectiveMaxCalls = finalDecision.effective_max_calls;
3777
- if (context.checkOptions && context.checkOptions.samples > effectiveMaxCalls) {
3935
+ if (context.checkOptions && Number.isSafeInteger(effectiveMaxCalls) && context.checkOptions.samples > effectiveMaxCalls) {
3778
3936
  await finishReservation(context, row, { state: 'not_run' });
3779
3937
  Object.assign(row, {state:'not_run',note:{code:'call-budget',message:'Remaining total call allowance is smaller than samples.'}});
3780
3938
  return;
3781
3939
  }
3782
- row.budget_in_flight = effectiveMaxCalls;
3940
+ row.budget_in_flight = Number.isSafeInteger(effectiveMaxCalls) && effectiveMaxCalls >= 1 ? effectiveMaxCalls : 0;
3783
3941
  if (row.restart_pending) {
3784
3942
  const restartPath = claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json');
3785
3943
  let claim;
@@ -3812,8 +3970,9 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3812
3970
  return;
3813
3971
  }
3814
3972
  const id = context.ports.randomUUID();
3815
- (row.claim_max_calls ??= {})[id] = effectiveMaxCalls;
3816
- const dispatchClaim = { id, reservation: row.reservation, restart: !!row.restart_used, max_calls: effectiveMaxCalls };
3973
+ const hasEffectiveMaxCalls = Number.isSafeInteger(effectiveMaxCalls) && effectiveMaxCalls >= 1;
3974
+ if (hasEffectiveMaxCalls) (row.claim_max_calls ??= {})[id] = effectiveMaxCalls;
3975
+ const dispatchClaim = { id, reservation: row.reservation, restart: !!row.restart_used, ...(hasEffectiveMaxCalls ? { max_calls: effectiveMaxCalls } : {}) };
3817
3976
  try { writeSync(fd, JSON.stringify(dispatchClaim)); }
3818
3977
  finally { closeSync(fd); }
3819
3978
  (context.preparingDispatches ??= new WeakMap()).set(row, dispatchClaim);
@@ -3833,7 +3992,8 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3833
3992
  row.phase = 'server';
3834
3993
  const clauseTable = clauseTableForRow(context, row);
3835
3994
  if (clauseTable) row.clause_table = clauseTable;
3836
- const request = { requestId: id, source_sha256: context.capture.sha256, scenario: row.test, max_calls: effectiveMaxCalls,
3995
+ const request = { requestId: id, source_sha256: context.capture.sha256, scenario: row.test,
3996
+ ...(hasEffectiveMaxCalls ? { max_calls: effectiveMaxCalls } : {}),
3837
3997
  ...(context.freshChecks || context.checkOptions?.fresh ? { fresh: true } : {}),
3838
3998
  ...(context.checkOptions ? { samples: context.checkOptions.samples,
3839
3999
  ...(context.checkOptions.step_ids ? { step_ids: context.checkOptions.step_ids } : {}) } : {}),
@@ -3872,7 +4032,7 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3872
4032
  const readUntil = Number.isFinite(deadline) ? deadline : context.ports.now() + LOST_READ_MS;
3873
4033
  if (verdict.capacity_uncertain) markCapacityUnknown(context, row);
3874
4034
  else Object.assign(row, { state: 'unknown', why: verdict.why, lost: true, read_until: readUntil });
3875
- row.lost = true; row.read_until = readUntil;
4035
+ row.lost = true; row.read_until = readUntil; row.missing_id = id; row.missing_count = 0; row.missing_since = null;
3876
4036
  }
3877
4037
  }
3878
4038
 
@@ -3906,13 +4066,39 @@ async function readRow(context, row, deadline = Infinity) {
3906
4066
  const rowEnd = rowDeadline(context, row);
3907
4067
  const id = row.request_ids.at(-1), end = Math.min(rowEnd, deadline, row.lost ? row.read_until ?? rowEnd : rowEnd);
3908
4068
  if (!id || context.interrupted || context.ports.now() >= end) return;
4069
+ if (row.missing_id !== id) { row.missing_id = id; row.missing_count = 0; row.missing_since = null; }
3909
4070
  const verdict = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, (end ?? Infinity) - context.ports.now()))), id, 'check');
3910
4071
  verdict.observed_at = context.ports.now();
3911
4072
  if (verdict.kind === 'again' && verdict.contention) backoffCheckWindow(context, `get:${id}:${Math.floor(verdict.observed_at / 5000)}`, 'HTTP 429');
3912
4073
  // A network problem while reading says so once; pdd keeps reading the same IDs.
3913
4074
  if (verdict.kind === 'again' && verdict.why && !context.readTrouble) line(context.ports.stderr, `pdd cannot read the results right now (${verdict.why}). It keeps trying.`);
3914
4075
  if (verdict.kind !== 'again') context.readTrouble = false; else if (verdict.why) context.readTrouble = true;
4076
+ if (verdict.kind !== 'missing') { row.missing_count = 0; row.missing_since = null; }
3915
4077
  if (verdict.kind === 'state') { saveAnswer(context, id, verdict.answer); queueProgress(context, verdict.answer); await finishReservation(context, row, verdict.answer); applyAnswer(row, verdict.answer, context, verdict.wait, verdict.observed_at); row.lost = false; }
4078
+ else if (verdict.kind === 'missing') {
4079
+ row.missing_count = (row.missing_count ?? 0) + 1;
4080
+ row.missing_since ??= verdict.observed_at;
4081
+ if (row.missing_count >= MISSING_MIN_POLLS && verdict.observed_at - row.missing_since >= MISSING_GRACE_MS) {
4082
+ if (row.capacity_uncertain) markCapacityUnknown(context, row);
4083
+ else {
4084
+ const notFoundWhy = 'The run was not found on the interpreter (HTTP 404).';
4085
+ const why = row.why && !row.why.includes('HTTP 404')
4086
+ ? `${row.why.replace(/\.$/, '')}. ${notFoundWhy}`
4087
+ : notFoundWhy;
4088
+ Object.assign(row, {
4089
+ state: 'unknown',
4090
+ calls: row.calls ?? 'unknown',
4091
+ busy: false,
4092
+ can_retry: false,
4093
+ note: { code: 'not-found', message: why },
4094
+ why,
4095
+ lost: false,
4096
+ final: true,
4097
+ });
4098
+ }
4099
+ row.lost = false; row.final = true;
4100
+ }
4101
+ }
3916
4102
  else if (verdict.kind === 'unknown') {
3917
4103
  if (row.capacity_uncertain) markCapacityUnknown(context, row);
3918
4104
  else Object.assign(row, { state: 'unknown', why: verdict.why, lost: false, final: true });
@@ -3924,7 +4110,11 @@ async function readRow(context, row, deadline = Infinity) {
3924
4110
  }
3925
4111
 
3926
4112
  const isOpen = row => OPEN_STATES.has(row.state) || (row.state === 'unknown' && row.lost);
3927
- const occupiesSlot = row => OPEN_STATES.has(row.state) || (row.state === 'unknown' && row.request_ids?.length);
4113
+ const occupiesSlot = (row, now = Infinity) => OPEN_STATES.has(row.state)
4114
+ || (row.state === 'unknown' && !row.final && Boolean(row.lost) && Boolean(row.request_ids?.length)
4115
+ && now < (row.read_until ?? Infinity));
4116
+ const holdsLocalReservation = row => Boolean(row.reservation)
4117
+ && (OPEN_STATES.has(row.state) || (row.state === 'unknown' && Boolean(row.request_ids?.length)));
3928
4118
 
3929
4119
  // One line every 30 s while checks run.
3930
4120
  function progressLine(rows, ms) {
@@ -4220,14 +4410,18 @@ async function runScheduledChecks(context, rows, toSend) {
4220
4410
  }
4221
4411
  }
4222
4412
  }
4223
- const pendingSends = new Map(), uploads = uploadLimit(context);
4413
+ const pendingSends = new Map(), uploads = uploadLimit(context), localCap = localLimit(context);
4414
+ const localUsed = () => Number.isFinite(localCap)
4415
+ ? rows.filter(row => !pendingSends.has(row) && holdsLocalReservation(row)).length
4416
+ : 0;
4224
4417
  // Refill on a POST's settlement even while the polling loop awaits GETs.
4225
4418
  // Waiting rows stay outside admission and dispatch-claim allocation.
4226
4419
  const pumpSends = () => {
4227
4420
  const now = ports.now();
4228
4421
  if (context.liveLocalSaved || context.interrupted || context.readStop || context.stopped || context.sendError || now >= batchDeadlineOf(context)) return;
4229
- const active = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, now)).length;
4230
- const available = Math.max(0, Math.min(uploads - pendingSends.size, context.checkWindow - active - pendingSends.size));
4422
+ const active = rows.filter(row => occupiesSlot(row, now) && !rowExpired(context, row, now)).length;
4423
+ const localRoom = Number.isFinite(localCap) ? localCap - localUsed() - pendingSends.size : Infinity;
4424
+ const available = Math.max(0, Math.min(uploads - pendingSends.size, context.checkWindow - active - pendingSends.size, localRoom));
4231
4425
  const eligible = toSend.filter(row => !pendingSends.has(row) && !row.awaiting_budget && ['ready', 'waiting'].includes(row.state)
4232
4426
  && !rowExpired(context, row, now) && (!row.retry_at || now >= row.retry_at));
4233
4427
  for (const row of eligible.slice(0, available)) {
@@ -4255,6 +4449,7 @@ async function runScheduledChecks(context, rows, toSend) {
4255
4449
  };
4256
4450
  const sseEnabled = !ports.pollMsExplicit && Boolean(context.serverFeatures?.includes('sse-stream-v1'));
4257
4451
  const activeStreams = new Map();
4452
+ const pendingFinishes = new Set();
4258
4453
  const sseBackoff = new WeakMap();
4259
4454
  let wakeResolve = null;
4260
4455
  const notifyWake = () => { if (wakeResolve) { const fn = wakeResolve; wakeResolve = null; fn(); } };
@@ -4314,7 +4509,13 @@ async function runScheduledChecks(context, rows, toSend) {
4314
4509
  queueProgress(context, enriched);
4315
4510
  applyAnswer(row, enriched, context, null, ports.now());
4316
4511
  row.lost = false;
4317
- finishReservation(context, row, enriched).finally(notifyWake);
4512
+ const finishTask = finishReservation(context, row, enriched)
4513
+ .catch(() => {})
4514
+ .finally(() => {
4515
+ pendingFinishes.delete(finishTask);
4516
+ notifyWake();
4517
+ });
4518
+ pendingFinishes.add(finishTask);
4318
4519
  return true;
4319
4520
  }
4320
4521
  if (event === 'accepted' || event === 'progress') {
@@ -4368,8 +4569,10 @@ async function runScheduledChecks(context, rows, toSend) {
4368
4569
  abortExpiredStreams();
4369
4570
  // Never count an uncertain dispatched job as a free slot while active within its deadline.
4370
4571
  const now = ports.now();
4371
- const active = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, now)).length;
4372
- if (!context.stopped && now < batchDeadlineOf(context) && active < context.checkWindow) {
4572
+ const active = rows.filter(row => occupiesSlot(row, now) && !rowExpired(context, row, now)).length;
4573
+ const localSlotsUsed = localUsed();
4574
+ if (!context.stopped && now < batchDeadlineOf(context) && active < context.checkWindow
4575
+ && (!Number.isFinite(localCap) || localSlotsUsed < localCap)) {
4373
4576
  pumpSends();
4374
4577
  // Admission can wait while previously dispatched rows continue to be read.
4375
4578
  if (!active && pendingSends.size) await Promise.race(pendingSends.values());
@@ -4387,9 +4590,11 @@ async function runScheduledChecks(context, rows, toSend) {
4387
4590
  if (!context.liveLocalSaved) for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
4388
4591
  if (earlyRestarts.length) { for (const item of toSend) item.awaiting_budget = false; pumpSends(); }
4389
4592
  const loopNow = ports.now();
4390
- const activeAfter = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, loopNow)).length;
4593
+ const activeAfter = rows.filter(row => occupiesSlot(row, loopNow) && !rowExpired(context, row, loopNow)).length;
4594
+ const localUsedAfter = localUsed();
4595
+ const blockedBySlots = activeAfter >= context.checkWindow || (Number.isFinite(localCap) && localUsedAfter >= localCap);
4391
4596
  const pending = toSend.some(row => ['ready', 'waiting'].includes(row.state) && !rowExpired(context, row, loopNow));
4392
- if (pending && activeAfter >= context.checkWindow && !rows.some(readable) && !pendingSends.size) break;
4597
+ if (pending && blockedBySlots && !rows.some(readable) && !pendingSends.size) break;
4393
4598
  if ((!pending || context.stopped || loopNow >= batchDeadlineOf(context)) && !rows.some(readable) && !pendingSends.size) break;
4394
4599
  if (loopNow - progress.shownAt >= PROGRESS_MS) { progress.shownAt = loopNow; line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt)); }
4395
4600
  syncRowStreams();
@@ -4409,8 +4614,17 @@ async function runScheduledChecks(context, rows, toSend) {
4409
4614
  const waitMs = Math.max(0, Math.min(cadence, end - loopNow));
4410
4615
  if (activeStreams.size) {
4411
4616
  const wake = new Promise(resolve => { wakeResolve = resolve; });
4412
- await Promise.race([ports.sleep(waitMs, context.signal), wake]);
4413
- wakeResolve = null;
4617
+ const sleepAc = new AbortController();
4618
+ const onSleepAbort = () => sleepAc.abort();
4619
+ context.signal?.addEventListener('abort', onSleepAbort, { once: true });
4620
+ try {
4621
+ if (context.signal?.aborted) sleepAc.abort();
4622
+ else await Promise.race([ports.sleep(waitMs, sleepAc.signal), wake]);
4623
+ } finally {
4624
+ sleepAc.abort();
4625
+ context.signal?.removeEventListener('abort', onSleepAbort);
4626
+ wakeResolve = null;
4627
+ }
4414
4628
  } else {
4415
4629
  await ports.sleep(waitMs, context.signal);
4416
4630
  }
@@ -4425,7 +4639,7 @@ async function runScheduledChecks(context, rows, toSend) {
4425
4639
  } catch (error) { context.sendError ??= error; throw error; }
4426
4640
  finally {
4427
4641
  for (const entry of activeStreams.values()) entry.controller.abort();
4428
- await Promise.all([...pendingSends.values(), ...[...activeStreams.values()].map(entry => entry.promise)]);
4642
+ await Promise.all([...pendingSends.values(), ...[...activeStreams.values()].map(entry => entry.promise), ...pendingFinishes]);
4429
4643
  }
4430
4644
  if (context.sendError) throw context.sendError;
4431
4645
  const stoppedEarly = context.interrupted || !!context.readStop;
@@ -4496,6 +4710,7 @@ function printResult(context, rows, extra = {}) {
4496
4710
  else ports.stdout.write(scrub(renderText({ batch: context.batch, rows, coverage: context.coverage, warnings, details: context.details, timeoutMin: context.timeoutMin, batchTimeoutMin: context.batchTimeoutMin,
4497
4711
  now: ports.now(), noFailed: context.noFailed, interrupted: context.interrupted || !!context.readStop, reading: !!context.reading, exitCode, secrets: context.secrets, ...extra }, ports)));
4498
4712
  if (!context.json && summary.report_url) line(ports.stdout, `Report: ${summary.report_url}`);
4713
+ if (!context.json && exitCode === 1 && context.batch) line(ports.stdout, `Batch: ${context.batch}`);
4499
4714
  if (!context.json) for (const value of checkPlanResultLines(summary.check_scope)) line(ports.stdout, scrub(value));
4500
4715
  if (!context.json && context.checkSelection) {
4501
4716
  line(ports.stdout, AFFECTED_DISCLAIMER);
@@ -5043,12 +5258,13 @@ function heldForLint(row) {
5043
5258
  || /lint result is unknown.*sent no checks/i.test(row.note?.message ?? '')
5044
5259
  || row.phase === 'lint' && row.note?.code === 'lint-finished');
5045
5260
  }
5046
- function validSavedCallCeiling(row) {
5261
+ function validSavedCallCeiling(row, { allowServerDefault = true } = {}) {
5262
+ if (allowServerDefault && row.max_calls === null) return true;
5047
5263
  return Number.isInteger(row.max_calls) && row.max_calls >= 1 && row.max_calls <= 1000;
5048
5264
  }
5049
- function validSavedCheck(row) {
5265
+ function validSavedCheck(row, { allowServerDefault = true } = {}) {
5050
5266
  const text = value => typeof value === 'string' && !!value.trim();
5051
- if (!validSavedCallCeiling(row)
5267
+ if (!validSavedCallCeiling(row, { allowServerDefault })
5052
5268
  || !Number.isInteger(row.criteria_total) || row.criteria_total <= 0
5053
5269
  || !Array.isArray(row.steps) || !row.steps.length) return false;
5054
5270
  const ids = new Set(), criteria = new Set();
@@ -5072,8 +5288,8 @@ async function continueHeld(context, candidates, saved) {
5072
5288
  candidates = candidates.filter(row => runtimeLintRow(row) && !row.request_ids.length && !row.dispatchIncomplete);
5073
5289
  if (!candidates.length) return;
5074
5290
  if (saved.version !== 1 || (saved.intent !== undefined && saved.intent !== 'check')
5075
- || !candidates.every(validSavedCallCeiling)
5076
- || (saved.intent === undefined && !candidates.every(validSavedCheck))
5291
+ || !candidates.every(row => validSavedCallCeiling(row, { allowServerDefault: saved.intent === 'check' }))
5292
+ || (saved.intent === undefined && !candidates.every(row => validSavedCheck(row, { allowServerDefault: false })))
5077
5293
  || candidates.some(row => Object.hasOwn(row, 'calls') && row.calls !== 0)) {
5078
5294
  context.continuationNotice = 'No checks were sent for the lint-held rows: the saved batch lacks valid original call ceilings, unambiguous Check intent or zero-call lint-held proof. Start a fresh selected pdd test.';
5079
5295
  return;
@@ -5535,6 +5751,40 @@ async function refreshCheckBatches(context, identity, origin, id, answer) {
5535
5751
  return owner;
5536
5752
  }
5537
5753
 
5754
+ // Read-only lookup matching a Report URL UUID (/r/<id>) against saved batches for this exact repo, runtime and account.
5755
+ function owningReportBatch({ root, store }, identity, origin, id) {
5756
+ if (!root || !store) return null;
5757
+ const batches = join(store.dir, 'batches'); let names;
5758
+ try { names = readdirSync(batches); } catch { return null; }
5759
+ let expectedOrigin;
5760
+ try { expectedOrigin = new URL(origin).origin; } catch { return null; }
5761
+ const matchesReportId = url => {
5762
+ if (typeof url !== 'string' || !url) return false;
5763
+ try {
5764
+ const parsed = new URL(url);
5765
+ return parsed.origin === expectedOrigin && parsed.pathname === `/r/${id}`;
5766
+ } catch { return false; }
5767
+ };
5768
+ for (const name of names.filter(name => BATCH.test(name)).sort().reverse()) {
5769
+ const folder = join(batches, name);
5770
+ const saved = store.read(join(folder, 'batch.json'));
5771
+ if (saved?.batch !== name || saved.root !== root || saved.origin !== origin
5772
+ || saved.login !== identity.login || String(saved.user_id) !== String(identity.userId)) continue;
5773
+ for (const row of Array.isArray(saved.rows) ? saved.rows : []) {
5774
+ const requestId = Array.isArray(row?.request_ids) ? row.request_ids.at(-1) ?? null : null;
5775
+ if (matchesReportId(row?.report_url)) return { batch: name, requestId };
5776
+ if (!row?.report_url && requestId) {
5777
+ const receipt = store.read(join(folder, `${requestId}.json`));
5778
+ if (matchesReportId(receipt?.report_url)) return { batch: name, requestId };
5779
+ }
5780
+ }
5781
+ const lintId = saved.lint?.request_ids?.at(-1);
5782
+ const lintReceipt = lintId && store.read(join(folder, `${lintId}.json`));
5783
+ if (matchesReportId(lintReceipt?.report_url)) return { batch: name, requestId: lintId };
5784
+ }
5785
+ return null;
5786
+ }
5787
+
5538
5788
  // A read is observation only; it does not replay the call or settle backend accounting.
5539
5789
  async function runCallRead(context, id) {
5540
5790
  const { ports, store } = context;
@@ -5575,17 +5825,27 @@ async function runCallRead(context, id) {
5575
5825
  return printResult(context, [row], { recovery: `pdd test --read ${id}` });
5576
5826
  }
5577
5827
  const state = answer?.state ?? 'unknown', exitCode = ports.exitCodeFor([{ state }]);
5828
+ const notFound = !answer && reply.status === 404;
5829
+ const expired = !answer && reply.status === 410;
5830
+ const reportOwner = notFound && !saved && !localOwner ? owningReportBatch(context, identity, origin, id) : null;
5831
+ const notFoundWhy = reportOwner
5832
+ ? `Run ${id} was not found on the interpreter. That UUID matches the Report URL (/r/${id}) for saved batch ${reportOwner.batch}${reportOwner.requestId ? ` (request ${reportOwner.requestId})` : ''}. Read it with: pdd test --read ${reportOwner.batch}${context.details ? ' --details' : ''}`
5833
+ : (saved || localOwner)
5834
+ ? `Run ${id} was not found on the interpreter.`
5835
+ : `Run ${id} was not found on the interpreter. If this UUID came from a Report URL (/r/${id}), pass the batch ID or request ID instead.`;
5578
5836
  const sanitize = value => typeof value === 'string' ? secrets.reduce((text, secret) => secret ? text.split(secret).join('[secret]') : text, value).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '').replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,})\b/g, '[secret]')
5579
5837
  : Array.isArray(value) ? value.map(sanitize) : isObject(value) ? Object.fromEntries(Object.entries(value).map(([k, v]) => [sanitize(k), sanitize(v)])) : value;
5580
- const out = sanitize({ request_id: id, command: answer?.command ?? saved?.command ?? 'call', state, exit_code: exitCode,
5838
+ const normalizedAnswer = answer ? withReceiptUsage(answer) : answer;
5839
+ const out = sanitize({ request_id: id, command: normalizedAnswer?.command ?? saved?.command ?? 'call', state, exit_code: exitCode,
5581
5840
  ...(localOwner?.diagnostic_subset === true ? { diagnostic_subset: true, selected_steps: localOwner.selected_steps ?? [],
5582
5841
  summary_line: `diagnostic subset, not a full Story pass · selected steps: ${(localOwner.selected_steps ?? []).join(', ')}` } : {}),
5583
- calls: answer?.usage?.calls ?? 'unknown', usage: answer?.usage ?? null,
5584
- program_result: answer?.result?.program_result ?? null, result: answer?.result ?? null,
5585
- report_url: answer?.report_url ? validLink(answer.report_url, origin, 'report') : null,
5586
- why: answer ? answer.why ?? null : reply.status === 401 ? AUTH_TEXT : reply.status === 410 ? 'The result expired.'
5842
+ calls: normalizedAnswer?.usage?.calls ?? 'unknown', usage: normalizedAnswer?.usage ?? null,
5843
+ program_result: normalizedAnswer?.result?.program_result ?? null, result: normalizedAnswer?.result ?? null,
5844
+ report_url: normalizedAnswer?.report_url ? validLink(normalizedAnswer.report_url, origin, 'report') : null,
5845
+ why: normalizedAnswer ? normalizedAnswer.why ?? null : reply.status === 401 ? AUTH_TEXT : expired ? 'The result expired.'
5846
+ : notFound ? notFoundWhy
5587
5847
  : saved?.command === 'try' ? 'The Try receipt could not be verified.' : 'The call receipt could not be verified.' });
5588
- if (answer) store.write(join(store.folder(command === 'try' ? 'tries' : 'calls'), `${id}.json`), answer);
5848
+ if (normalizedAnswer) store.write(join(store.folder(command === 'try' ? 'tries' : 'calls'), `${id}.json`), normalizedAnswer);
5589
5849
  if (!answer && reply.status === 401) line(ports.stderr, AUTH_TEXT);
5590
5850
  if (context.json) line(ports.stdout, JSON.stringify(out));
5591
5851
  else {
@@ -5602,7 +5862,7 @@ async function runCallRead(context, id) {
5602
5862
  if (out.report_url) line(ports.stdout, out.report_url);
5603
5863
  if (out.why) line(ports.stdout, out.why);
5604
5864
  }
5605
- if (exitCode === 3) line(ports.stderr, `Read the result later with: pdd test --read ${id}`);
5865
+ if (exitCode === 3 && !notFound && !expired) line(ports.stderr, `Read the result later with: pdd test --read ${id}`);
5606
5866
  return exitCode;
5607
5867
  }
5608
5868
 
@@ -6714,7 +6974,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
6714
6974
  }
6715
6975
  if (options['--max-calls'] !== undefined) for (const row of rows) row.max_calls = Number(options['--max-calls']);
6716
6976
  if (context.checkOptions) for (const row of rows) {
6717
- if (context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
6977
+ if (Number.isSafeInteger(row.max_calls) && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
6718
6978
  if (context.checkOptions.step_ids && context.checkOptions.step_ids.length < row.steps.length) Object.assign(row,{sample_subset:true,diagnostic_subset:true,selected_steps:[...context.checkOptions.step_ids]});
6719
6979
  }
6720
6980
  base ??= resolveWorkflowBase();
@@ -6919,6 +7179,7 @@ function isPlainCliStep(prompt, step) {
6919
7179
 
6920
7180
  function programEntries(root, found, test, { allowMissingInterfaces = false } = {}) {
6921
7181
  const cli = new Set(), http = new Set();
7182
+ let httpScreenConflict = false;
6922
7183
  for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
6923
7184
  if (!step || typeof step.entry_path !== 'string' || typeof step.operation !== 'string') continue;
6924
7185
  const prompt = readPrompt(root, found.visible, step.entry_path);
@@ -6929,12 +7190,17 @@ function programEntries(root, found, test, { allowMissingInterfaces = false } =
6929
7190
  if (index >= 0) {
6930
7191
  const entry = entries[index];
6931
7192
  if (['input_schema', 'result_schema'].every(name => conventions.some(c => c?.path === `/entries/${index}/${name}` && c.convention === 'cli'))) cli.add(key);
6932
- if (typeof entry.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title)) http.add(key);
7193
+ const routeMatch = typeof entry.input_schema?.title === 'string' ? /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\/\S*)$/.exec(entry.input_schema.title) : null;
7194
+ if (routeMatch) {
7195
+ http.add(key);
7196
+ const [, method, path] = routeMatch;
7197
+ if (((method === 'GET' || method === 'HEAD') && path === '/') || path.startsWith('/__pdd/screen/')) httpScreenConflict = true;
7198
+ }
6933
7199
  } else if (allowMissingInterfaces && isPlainCliStep(prompt, step)) {
6934
7200
  cli.add(key);
6935
7201
  }
6936
7202
  }
6937
- return { test, cli, http };
7203
+ return { test, cli, http, httpScreenConflict };
6938
7204
  }
6939
7205
 
6940
7206
  function simulationSelection(root, found, words, appMap, options, ports, { allowMissingInterfaces = false } = {}) {
@@ -6957,6 +7223,14 @@ function simulationSelection(root, found, words, appMap, options, ports, { allow
6957
7223
  if (!step || typeof step.entry_path !== 'string' || !found.visible.has(step.entry_path)) return false;
6958
7224
  try { return isPlainProseUiPromptText(readPrompt(root, found.visible, step.entry_path, found.workspace).text); } catch { return false; }
6959
7225
  }));
7226
+ const hasScreenConflictHttp = rows.some(row => row.httpScreenConflict === true);
7227
+ const implicitServeScreen = !appMap && !cli.size && !hasScreenConflictHttp && (plainUi || selected.some(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).some(step => {
7228
+ if (!step || typeof step.entry_path !== 'string' || !found.visible.has(step.entry_path)) return false;
7229
+ try {
7230
+ const prompt = readPrompt(root, found.visible, step.entry_path, found.workspace);
7231
+ return isPlainProseUiPromptText(prompt.text) || isInterfaceHtmlScreenPrompt(prompt);
7232
+ } catch { return false; }
7233
+ })));
6960
7234
  const typed = words.length && !cli.size && !hasHttp && !mapped && !plainUi;
6961
7235
  const page = options['--page'] || options['--agent'] !== undefined || options['--tab'] !== undefined;
6962
7236
  const forcedCli = options['--cli'] || options['--shell'];
@@ -6967,7 +7241,7 @@ function simulationSelection(root, found, words, appMap, options, ports, { allow
6967
7241
  if (typed) refusal.formRecovery = `pdd simulate ${target} opens its Form tab.`;
6968
7242
  throw refusal;
6969
7243
  }
6970
- if (options['--serve'] !== undefined && !hasHttp && !appMap) {
7244
+ if (options['--serve'] !== undefined && !hasHttp && !appMap && !implicitServeScreen) {
6971
7245
  const names = eligibleNames(row => row.http.size);
6972
7246
  throw new Stop(2, `This Story has no HTTP routes or screens. ${names.length ? `These are: ${names.join(', ')}.` : 'No Stories have HTTP routes or screens.'}`);
6973
7247
  }
@@ -7002,7 +7276,7 @@ async function readUntil(context, id, command, isDone, ms, label, acceptAnswer =
7002
7276
  if (acceptAnswer && !acceptAnswer(json)) { streamUnknownWhy = 'The receipt could not be verified.'; return true; }
7003
7277
  last = json;
7004
7278
  queueProgress(context, last);
7005
- context.store.write(join(context.store.folder('tries'), `${id}.json`), last);
7279
+ context.store.write(join(context.store.folder('tries'), `${id}.json`), withReceiptUsage(last));
7006
7280
  if (isDone(last)) return true;
7007
7281
  if (label && event === 'progress') tick(`${label}: ${waitWord(last, null)}`);
7008
7282
  return false;
@@ -7021,7 +7295,7 @@ async function readUntil(context, id, command, isDone, ms, label, acceptAnswer =
7021
7295
  read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, remainingMs))), id, command);
7022
7296
  }
7023
7297
  if (read.kind === 'state' && acceptAnswer && !acceptAnswer(read.answer)) return { unknownWhy: 'The receipt could not be verified.' };
7024
- if (read.kind === 'state') { last = read.answer; queueProgress(context, last); context.store.write(join(context.store.folder('tries'), `${id}.json`), last); if (isDone(last)) return { answer: last }; }
7298
+ if (read.kind === 'state') { last = read.answer; queueProgress(context, last); context.store.write(join(context.store.folder('tries'), `${id}.json`), withReceiptUsage(last)); if (isDone(last)) return { answer: last }; }
7025
7299
  else if (read.kind === 'unknown') return { unknownWhy: read.why };
7026
7300
  else if (read.kind === 'auth') throw new Stop(5, AUTH_TEXT);
7027
7301
  else if (read.kind === 'blocked') throw new Stop(5, read.message);
@@ -7414,15 +7688,18 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
7414
7688
  initial_world: seeded?.initial_world ?? (options['--fresh'] ? {} : files.read()), ...(seeded?.simulation ? { simulation: seeded.simulation } : {}),
7415
7689
  ...(options['--fresh'] === true ? { fresh: true } : {}),
7416
7690
  ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
7417
- ...(appMap ? { app_map: appMap } : {}), tab: requestedTab, max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
7691
+ ...(appMap ? { app_map: appMap } : {}), tab: requestedTab, ...(requestedBudget !== null ? { max_calls: requestedBudget } : {}), ...sourceProvenance(context, capture) };
7418
7692
  setup.request_ids.push(request.requestId);
7419
7693
  if (await recordRuntimeRequest(setup.reservation, request.requestId, slotPorts(context)) === false || context.interrupted) throw new Stop(3, 'Stopped before sending the program.');
7420
- record = { id: request.requestId, root, entry, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...setup,
7694
+ record = { id: request.requestId, root, entry, origin, login: identity.login, source_sha256: capture.sha256, max_calls: requestedBudget ?? null, ...setup,
7421
7695
  prompt_hashes: capture.raw_prompt_hashes, effective_prompt_hashes: Object.fromEntries(capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)])),
7422
7696
  app_map: appMap, app_map_hash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null };
7423
7697
  files.set(record); store.posted(context.folder, record.id);
7424
7698
  let reply;
7425
- try { reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs); }
7699
+ const tryPostOpts = context.serverFeatures?.includes('blob-sync-v1') && Array.isArray(capture?.sources)
7700
+ ? { blobSync: true, sources: capture.sources, ...(context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: false } : {}) }
7701
+ : (context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined);
7702
+ try { reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs, tryPostOpts); }
7426
7703
  catch (error) {
7427
7704
  if (unadmittedTryErrors.has(error)) {
7428
7705
  await finishReservation(context, setup, { state: 'not_run' });
@@ -7447,7 +7724,8 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
7447
7724
  answer = done.answer; if (answer) await finishReservation(context, setup, answer);
7448
7725
  if (!tryLink(answer, origin)) throw new Stop(3, `Program setup ${record.id} is not confirmed running. Its original ID is kept.`);
7449
7726
  const cap = answer.result?.session?.max_calls;
7450
- if (cap !== request.max_calls) throw new Stop(3, 'The program call budget was not confirmed. Its session is kept.');
7727
+ if (requestedBudget !== null && cap !== requestedBudget) throw new Stop(3, 'The program call budget was not confirmed. Its session is kept.');
7728
+ if (requestedBudget === null && Number.isSafeInteger(cap) && cap > 0) { record = { ...record, max_calls: cap }; files.set(record); }
7451
7729
  files.save(files.read()); record = await syncProgramWorld(context.runtime, files, record); break;
7452
7730
  }
7453
7731
  }
@@ -7774,7 +8052,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
7774
8052
  const setup = {request_ids:[],reservation:null};
7775
8053
  if (!await admission(context,'try',setup)) throw new Stop(125,'The interpreter could not admit this program.');
7776
8054
  const lazyInterfaces=shouldSendLazyInterfaces(context);
7777
- const id=ports.randomUUID(), request={requestId:id,source_sha256:context.capture.sha256,seed:test.path,max_calls:400,tab:'terminal',...(lazyInterfaces?{lazy_interfaces:true}:{})};
8055
+ const id=ports.randomUUID(), request={requestId:id,source_sha256:context.capture.sha256,seed:test.path,tab:'terminal',...(lazyInterfaces?{lazy_interfaces:true}:{})};
7778
8056
  await recordRuntimeRequest(setup.reservation,id,slotPorts(context));
7779
8057
  descriptor={version:1,directProgram:true,root,prompt:promptPath,operation,login:identity.login,origin,sessionId:id,sourceHash,setupPending:true,
7780
8058
  name:selected.name,inputSchema:selected.entry.input_schema,stateDir:store.dir,programDir:folder,
@@ -7783,10 +8061,13 @@ async function runDirectProgram({words,options,cwd}, ports) {
7783
8061
  directPrivate(lastPath,{state:'unknown',id:null,setupId:id,input});
7784
8062
  store.write(join(store.folder('tries'),`${id}.meta.json`),{id,command:'try',origin,root,login:identity.login,user_id:identity.userId});
7785
8063
  store.posted(store.folder('tries'),id);
7786
- const reply=await context.runtime.post('/v1/try',request,context.capture.tar,ports.postMs), verdict=judgePost(reply,id,'try',secrets);
8064
+ const directTryOpts = context.serverFeatures?.includes('blob-sync-v1') && Array.isArray(context.capture?.sources)
8065
+ ? { blobSync: true, sources: context.capture.sources, ...(context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: false } : {}) }
8066
+ : (context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined);
8067
+ const reply=await context.runtime.post('/v1/try',request,context.capture.tar,ports.postMs,directTryOpts), verdict=judgePost(reply,id,'try',secrets);
7787
8068
  let answer=sameTryReceipt(verdict.answer,id)?verdict.answer:null;
7788
8069
  if (answer && !ENDED.has(answer.state)) answer=(await readUntil(context,id,'try',item=>ENDED.has(item.state),TRY_MS,'Starting program',item=>sameTryReceipt(item,id))).answer;
7789
- if (answer) {store.write(join(store.folder('tries'),`${id}.json`),answer);await finishReservation(context,setup,answer);}
8070
+ if (answer) {store.write(join(store.folder('tries'),`${id}.json`),withReceiptUsage(answer));await finishReservation(context,setup,answer);}
7790
8071
  if (answer&&sameJob(answer,id,'try')&&['failed','refused','not_run'].includes(answer.state))directPrivate(descriptorPath,{...descriptor,setupPending:false,setupFailed:true});
7791
8072
  if (!answer || !sameJob(answer,id,'try') || answer.state !== 'passed' || !LIVE_SESSION.has(answer.result?.session?.state))
7792
8073
  throw Object.assign(new Stop(125,verdict.refusal?.message||reply.json?.error?.message||`The program setup is unconfirmed. Read pdd test --read ${id}.`),{fix:verdict.refusal?.fix||reply.json?.error?.fix||`Read pdd test --read ${id}; do not start another setup.`});
@@ -7936,17 +8217,20 @@ async function runTypedTry(words, cwd, ports) {
7936
8217
  if(rows.some(row=>row.state!=='ready')) throw Error(rows[0].refusals?.map(row=>row.message || row.code).join('; ') || 'The interpreter refused lint.');
7937
8218
  const setup={request_ids:[],reservation:null};
7938
8219
  if(!await admission(context,'try',setup)) throw Error('The interpreter could not start the direct invocation.');
7939
- const request={requestId:ports.randomUUID(),source_sha256:capture.sha256,seed:testPath,max_calls:400,tab:'call',...sourceProvenance(context)};
8220
+ const request={requestId:ports.randomUUID(),source_sha256:capture.sha256,seed:testPath,tab:'call',...sourceProvenance(context)};
7940
8221
  setup.request_ids.push(request.requestId);
7941
8222
  if(await recordRuntimeRequest(setup.reservation,request.requestId,slotPorts(context))===false || context.interrupted) throw Error('Stopped before the direct invocation was sent.');
7942
8223
  const receiptPath=join(context.folder,`${request.requestId}.direct.json`);
7943
8224
  const receipt={id:request.requestId,root,origin,login:identity.login,prompt:path,operation:prepared.operation,source_sha256:capture.sha256,prompt_hashes:capture.raw_prompt_hashes};
7944
8225
  store.write(receiptPath,receipt);store.posted(context.folder,request.requestId);
7945
- const reply=await context.runtime.post('/v1/try',request,capture.tar,ports.postMs);
8226
+ const directCallOpts = context.serverFeatures?.includes('blob-sync-v1') && Array.isArray(capture?.sources)
8227
+ ? { blobSync: true, sources: capture.sources, ...(context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: false } : {}) }
8228
+ : (context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined);
8229
+ const reply=await context.runtime.post('/v1/try',request,capture.tar,ports.postMs,directCallOpts);
7946
8230
  const verdict=judgePost(reply,request.requestId,'try',context.secrets);
7947
8231
  if(verdict.kind!=='accepted' && verdict.kind!=='unknown') throw Error(verdict.note?.message || verdict.refusal?.message || 'The interpreter refused direct setup.');
7948
8232
  const done=verdict.answer && ENDED.has(verdict.answer.state)?{answer:verdict.answer}:await readUntil(context,request.requestId,'try',answer=>ENDED.has(answer.state),TRY_MS,'Still starting the direct invocation');
7949
- if(done.answer) {store.write(join(context.folder,`${request.requestId}.json`),done.answer);await finishReservation(context,setup,done.answer);}
8233
+ if(done.answer) {store.write(join(context.folder,`${request.requestId}.json`),withReceiptUsage(done.answer));await finishReservation(context,setup,done.answer);}
7950
8234
  if(done.answer?.state!=='passed' || !LIVE_SESSION.has(done.answer.result?.session?.state)) throw Error(done.answer?.result?.refusals?.[0]?.message || 'The direct setup result is unavailable.');
7951
8235
  const fresh=ports.captureSource(root,{tests:[path],appMap:null});
7952
8236
  if(Object.entries(capture.raw_file_hashes ?? {}).some(([name,digest])=>fresh.raw_file_hashes?.[name]!==digest)
@@ -8211,7 +8495,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
8211
8495
  const setup = { request_ids: [], reservation: null };
8212
8496
  for (;;) {
8213
8497
  if (!await admission(context, 'try', setup)) throw new Stop(context.interrupted ? 3 : 5, context.interrupted ? 'Stopped before sending.' : 'The interpreter stayed busy until the Try setup wait ended. No new Try was sent.');
8214
- request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, seed: test.path, max_calls: requestedBudget ?? 400, ...(appMap ? { app_map: appMap } : {}), ...(prepared ? {product_parts:prepared.composition.product_parts} : {}),
8498
+ request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, seed: test.path, ...(requestedBudget !== null ? { max_calls: requestedBudget } : {}), ...(appMap ? { app_map: appMap } : {}), ...(prepared ? {product_parts:prepared.composition.product_parts} : {}),
8215
8499
  ...(options['--fresh'] === true ? { fresh: true } : {}),
8216
8500
  ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
8217
8501
  ...sourceProvenance(context, capture),
@@ -8223,16 +8507,19 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
8223
8507
  if (registered === false) { await finishReservation(context, setup, { state: 'not_run' }); throw new Stop(3, context.interrupted ? 'Stopped before sending.' : 'Stopped before the Try was sent.'); }
8224
8508
  if (context.interrupted || ports.now() >= context.deadline) { await finishReservation(context, setup, { state: 'not_run' }); throw new Stop(3, context.interrupted ? 'Stopped before sending.' : 'Stopped before the Try was sent.'); }
8225
8509
  const uploadedSeed=capture.sources.find(file=>file.path===test.path);
8226
- const tryRecord = { ...(context.liveLocal?{live_local:true,resource_setup:localBridge.resource_setup}:{}),id: request.requestId, ...setup, story: test.story, storyPath: test.storyPath, title: test.title, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...(!productSetup && !words.length ? { simulation_scope: { tests: selected.map(item => item.path), appMap, appMapHash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null } } : {}), seed_scenario: uploadedSeed ? parseProgramJson(uploadedSeed.bytes.toString('utf8')) : test.doc, story_sha256: createHash('sha256').update(readFileSync(join(root, test.storyPath))).digest('hex'), prompt_hashes: capture.raw_prompt_hashes,
8510
+ const tryRecord = { ...(context.liveLocal?{live_local:true,resource_setup:localBridge.resource_setup}:{}),id: request.requestId, ...setup, story: test.story, storyPath: test.storyPath, title: test.title, origin, login: identity.login, source_sha256: capture.sha256, max_calls: requestedBudget ?? null, ...(!productSetup && !words.length ? { simulation_scope: { tests: selected.map(item => item.path), appMap, appMapHash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null } } : {}), seed_scenario: uploadedSeed ? parseProgramJson(uploadedSeed.bytes.toString('utf8')) : test.doc, story_sha256: createHash('sha256').update(readFileSync(join(root, test.storyPath))).digest('hex'), prompt_hashes: capture.raw_prompt_hashes,
8227
8511
  effective_prompt_hashes:Object.fromEntries(capture.sources.filter(file=>file.path.endsWith('.prompt.md')).map(file=>[file.path,sha256(file.bytes)])),contract_references:capture.references, ...(productSetup?{product_setup:productSetup,product_parts:prepared.composition.product_parts}:{}) };
8228
8512
  await store.updateRepo(root, current => ({ ...current, tries: { ...current.tries, [test.path]: tryRecord } }));
8229
8513
  store.posted(context.folder, request.requestId);
8230
8514
  line(ports.stderr, `Starting your Try: sending ${capture.files.length} files, ${formatSize(capture.bytes)}${note ? ` ${note}` : ''}…`);
8231
- const dedupTry = context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined;
8515
+ const blobSyncTry = Boolean(context.serverFeatures?.includes('blob-sync-v1') && Array.isArray(capture?.sources));
8516
+ const dedupTry = (blobSyncTry || context.serverFeatures?.includes('source-upload-v1'))
8517
+ ? { ...(blobSyncTry ? { blobSync: true, sources: capture.sources } : {}), ...(context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: !blobSyncTry } : {}) }
8518
+ : undefined;
8232
8519
  reply = await context.runtime.post('/v1/try', request, capture.tar, Math.max(1, Math.min(ports.postMs, context.deadline - ports.now())), dedupTry);
8233
8520
  verdict = judgePost(reply, request.requestId, 'try', context.secrets);
8234
8521
  if (verdict.maintenance) maintenanceNotice(context, verdict, reply);
8235
- if (verdict.answer) { store.write(join(context.folder, `${request.requestId}.json`), verdict.answer); queueProgress(context, verdict.answer); await finishReservation(context, setup, verdict.answer); }
8522
+ if (verdict.answer) { store.write(join(context.folder, `${request.requestId}.json`), withReceiptUsage(verdict.answer)); queueProgress(context, verdict.answer); await finishReservation(context, setup, verdict.answer); }
8236
8523
  if (verdict.admission) store.write(join(context.folder, `${request.requestId}.admission.json`), verdict.admission);
8237
8524
  if (verdict.kind === 'busy') {
8238
8525
  await finishReservation(context, setup, { state: 'not_run' });
@@ -8258,11 +8545,18 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
8258
8545
  const link = tryLink(done.answer, origin);
8259
8546
  if (link) {
8260
8547
  const cap = done.answer?.result?.session?.max_calls;
8261
- if (Number.isSafeInteger(cap) && cap !== request.max_calls) throw new Stop(5, `The interpreter confirmed a budget of ${cap} calls instead of the requested ${request.max_calls}. This Try is kept; its saved data was not reset.`);
8548
+ if (requestedBudget !== null && Number.isSafeInteger(cap) && cap !== requestedBudget) throw new Stop(5, `The interpreter confirmed a budget of ${cap} calls instead of the requested ${requestedBudget}. This Try is kept; its saved data was not reset.`);
8262
8549
  if (requestedBudget !== null && !Number.isSafeInteger(cap)) throw new Stop(3, 'The interpreter did not confirm the requested Try budget. The same Try is kept; read it again without changing its budget.');
8550
+ const confirmedCap = Number.isSafeInteger(cap) && cap > 0 ? cap : null;
8263
8551
  const confirmedEngine = validEngineHex(done.answer?.engine_sha);
8264
- if (confirmedEngine) {
8265
- await store.updateRepo(root, current => { if (current.tries?.[test.path]?.id === request.requestId) current.tries[test.path].engine_sha = confirmedEngine; return current; });
8552
+ if (confirmedEngine || (requestedBudget === null && confirmedCap !== null)) {
8553
+ await store.updateRepo(root, current => {
8554
+ if (current.tries?.[test.path]?.id === request.requestId) {
8555
+ if (confirmedEngine) current.tries[test.path].engine_sha = confirmedEngine;
8556
+ if (requestedBudget === null && confirmedCap !== null) current.tries[test.path].max_calls = confirmedCap;
8557
+ }
8558
+ return current;
8559
+ });
8266
8560
  }
8267
8561
  return await showTry(context, test, link, options, request.requestId, false, done.answer?.result?.session, done.answer, store.repo(root).tries?.[test.path]);
8268
8562
  }
@@ -9227,7 +9521,7 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
9227
9521
  if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped; this command result is unknown. Do not repeat it automatically.' + recovery);
9228
9522
  if (answer && !programReceiptMatches(answer, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
9229
9523
  if (answer && ENDED.has(answer.state)) {
9230
- store.write(join(store.folder('tries'), `${id}.json`), answer);
9524
+ store.write(join(store.folder('tries'), `${id}.json`), withReceiptUsage(answer));
9231
9525
  const rawReport = isObject(answer.result?.report) ? answer.result.report : null;
9232
9526
  const reportError = isObject(rawReport?.error) ? rawReport.error : null;
9233
9527
  const usage = tryUsage(answer, { cap: descriptor.callCap });
@@ -10422,7 +10716,7 @@ export function createProgramContext({ cwd = process.cwd(), options = {} } = {},
10422
10716
  if ([404,410].includes(reply.status)) return {stopped:true,readOnly:true};
10423
10717
  const verdict = judgePost(reply,requestId,'stop',context.secrets);
10424
10718
  let answer = verdict.answer;
10425
- if (answer) store.write(join(context.folder, `${requestId}.json`), answer);
10719
+ if (answer) store.write(join(context.folder, `${requestId}.json`), withReceiptUsage(answer));
10426
10720
  const matches = row => programReceiptMatches(row, requestId, 'stop', sessionId);
10427
10721
  const uncertain = () => Object.assign(new Stop(125, `The stop outcome is unknown. Read the result with: pdd run --read ${requestId}`), { unknownOutcome: true, runId: requestId });
10428
10722
  if (answer && !matches(answer)) throw uncertain();
@@ -10449,7 +10743,7 @@ async function readProgramReceipt(context, id, command, verdict, target, matches
10449
10743
  let answer = verdict.answer;
10450
10744
  if (!answer || matches(answer) && !ENDED.has(answer.state)) answer = (await readUntil(context, id, command, item => !matches(item) || ENDED.has(item.state), TRY_MS, null)).answer;
10451
10745
  if (answer) {
10452
- context.store.write(join(context.folder, `${id}.json`), answer);
10746
+ context.store.write(join(context.folder, `${id}.json`), withReceiptUsage(answer));
10453
10747
  if (matches(answer)) await finishReservation(context, target, answer);
10454
10748
  }
10455
10749
  return answer;
@@ -10484,7 +10778,7 @@ export async function inspectProgram(context, capture, { appMap } = {}) {
10484
10778
  }
10485
10779
  }
10486
10780
 
10487
- export async function admitProgram(context, capture, { entry, appMap, initial_world = {}, simulation = {}, max_calls = 400, tab = 'call', requestId } = {}) {
10781
+ export async function admitProgram(context, capture, { entry, appMap, initial_world = {}, simulation = {}, max_calls = undefined, tab = 'call', requestId } = {}) {
10488
10782
  const { ports, store } = context;
10489
10783
  await inspectProgram(context,capture,{appMap});
10490
10784
  const problem = (message, unknownOutcome = false, id = requestId) => Object.assign(new Stop(125,
@@ -10495,17 +10789,20 @@ export async function admitProgram(context, capture, { entry, appMap, initial_wo
10495
10789
  if (!await admission(context, 'try', setup)) throw problem('The interpreter stayed busy before program setup. No program was sent.');
10496
10790
  id ??= ports.randomUUID();
10497
10791
  if (!UUID.test(id)) throw new Stop(2, 'The program session ID is invalid.');
10498
- const request = { requestId: id, source_sha256: capture.sha256, entry, initial_world, simulation, max_calls, tab,
10792
+ const request = { requestId: id, source_sha256: capture.sha256, entry, initial_world, simulation, ...(max_calls !== undefined ? { max_calls } : {}), tab,
10499
10793
  ...(appMap ? { app_map: appMap } : {}), ...sourceProvenance(context, capture),
10500
10794
  ...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}) };
10501
10795
  setup.request_ids.push(id);
10502
10796
  const registered = await recordRuntimeRequest(setup.reservation, id, slotPorts(context));
10503
10797
  if (registered === false || context.interrupted) { await finishReservation(context, setup, { state: 'not_run' }); throw problem('Stopped before program setup was sent.'); }
10504
10798
  store.posted(context.folder, id);
10505
- const dedupTry = context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined;
10799
+ const blobSyncTry = Boolean(context.serverFeatures?.includes('blob-sync-v1') && Array.isArray(capture?.sources));
10800
+ const dedupTry = (blobSyncTry || context.serverFeatures?.includes('source-upload-v1'))
10801
+ ? { ...(blobSyncTry ? { blobSync: true, sources: capture.sources } : {}), ...(context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: !blobSyncTry } : {}) }
10802
+ : undefined;
10506
10803
  const reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs, dedupTry);
10507
10804
  const verdict = judgePost(reply, id, 'try', context.secrets);
10508
- if (verdict.answer) store.write(join(context.folder, `${id}.json`), verdict.answer);
10805
+ if (verdict.answer) store.write(join(context.folder, `${id}.json`), withReceiptUsage(verdict.answer));
10509
10806
  if (verdict.kind === 'busy') {
10510
10807
  await finishReservation(context, setup, { state: 'not_run' });
10511
10808
  // A caller-owned ID is durable; no second POST may use that ID.
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-output.prompt.md (sha256: 6e4117a1364be9328834407e8b6dd8feb5dbacee947193f1a32476c4bb894457).
1
+ // Generated from prompts/cli/runtime-output.prompt.md (sha256: 1db053c00555d4e67404149d6c34024bed05d39e99ba656ebe5ec59a7e448fee).
2
2
  import { bindingRefusals } from './runtime-binding-plan.mjs';
3
3
  import { describeCompatibility } from './lint-compatibility-display.mjs';
4
4
  import { indexClauseTable, validateStepClauses } from './prompt-clauses.mjs';
@@ -160,6 +160,19 @@ function predecessorErrors(refusal, report, steps, secrets) {
160
160
  return facts;
161
161
  }
162
162
 
163
+ function isDeferredStructuralCompatibility(value) {
164
+ const reported = value?.reported;
165
+ return value?.state === 'unknown'
166
+ && value?.association === 'matched'
167
+ && !value?.issue
168
+ && reported?.complete === false
169
+ && reported?.verdict === 'unknown'
170
+ && Array.isArray(reported.operations) && reported.operations.length === 0
171
+ && Array.isArray(reported.edges) && reported.edges.length === 0
172
+ && Array.isArray(reported.diagnostics) && reported.diagnostics.length > 0
173
+ && reported.diagnostics.every(item => item?.code === 'analysis-incomplete');
174
+ }
175
+
163
176
  // The parts of a server answer that pdd shows.
164
177
  export function projectAnswer(answer, { origin, secrets = [], steps: authoredSteps = [], criterionTexts = {}, test, sourceFiles, capacityUncertain = false, sampleEvidence = 'full', clauseTable = null } = {}) {
165
178
  const result = answer?.result ?? null, report = result?.report ?? null, time_limit = stepTimeLimit(answer, { steps: authoredSteps, secrets });
@@ -185,8 +198,12 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
185
198
  const compatibility = outcome.compatibility ? safeCompatibility(outcome.compatibility) : null;
186
199
  if (compatibility?.reported) for (const row of [...(compatibility.reported.operations ?? []), ...(compatibility.reported.edges ?? [])])
187
200
  row.client_advice = advice(row.reason_code);
188
- const client_advice = compatibility ? advice(compatibility.issue ?? (compatibility.state === 'supported' ? 'supported'
189
- : [...(compatibility.reported?.operations ?? []), ...(compatibility.reported?.edges ?? [])].find(row => row.verdict === compatibility.state)?.reason_code)) : null;
201
+ const client_advice = compatibility
202
+ ? (outcome.state === 'passed' && isDeferredStructuralCompatibility(compatibility)
203
+ ? { owner: 'application author', next_step: 'Structural lint passed; behavioral execution remains required.' }
204
+ : advice(compatibility.issue ?? (compatibility.state === 'supported' ? 'supported'
205
+ : [...(compatibility.reported?.operations ?? []), ...(compatibility.reported?.edges ?? [])].find(row => row.verdict === compatibility.state)?.reason_code)))
206
+ : null;
190
207
  const sampleSteps = (Array.isArray(report?.samples) ? report.samples : [])
191
208
  .flatMap(sample => (Array.isArray(sample?.steps) ? sample.steps : []).map((step, index) => ({ step, index })));
192
209
  const flatSteps = !sampleSteps.length && Array.isArray(report?.steps) ? report.steps.filter(isObjectLike) : [];
@@ -501,6 +518,16 @@ export function tokenUsageOf(answer, { incomplete = false } = {}) {
501
518
  return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens) };
502
519
  }
503
520
 
521
+ export function withReceiptUsage(answer) {
522
+ if (!isObjectLike(answer) || !isObjectLike(answer.usage)) return answer;
523
+ const tokens = tokenUsageOf(answer);
524
+ if (answer.usage.input_tokens === tokens.input_tokens
525
+ && answer.usage.cached_input_tokens === tokens.cached_input_tokens
526
+ && answer.usage.output_tokens === tokens.output_tokens
527
+ && answer.usage.cached_input_share === tokens.cached_input_share) return answer;
528
+ return { ...answer, usage: { ...answer.usage, ...tokens } };
529
+ }
530
+
504
531
  function criterionCoverage(row) {
505
532
  if (!Array.isArray(row.steps)) return null;
506
533
  const counts = new Map(Object.keys(row.criterion_texts ?? {}).map(id => [id, []]));
@@ -946,7 +973,7 @@ export function renderText({ batch, rows, coverage, warnings = [], details = fal
946
973
  for (const row of rows) for (const item of row.not_checked ?? []) out.push(
947
974
  `${row.test} ${item.criterion_id}: not checked: ${cleanText(item.reason,secrets)} (${cleanText(item.text,secrets)})`);
948
975
  for (const row of rows.filter(row=>row.binding_plan)) for (const detail of bindingRefusals(row.binding_plan,row.compatibility)) out.push(cleanText(JSON.stringify(detail),secrets));
949
- for (const row of rows.filter(row => row.compatibility)) out.push(...describeCompatibility({
976
+ for (const row of rows.filter(row => row.compatibility && !(row.state === 'passed' && isDeferredStructuralCompatibility(row.compatibility)))) out.push(...describeCompatibility({
950
977
  label: cleanText(row.test || '', secrets),
951
978
  compatibility: row.compatibility,
952
979
  clientAdvice: row.client_advice || null,
@@ -306,8 +306,8 @@ function discoverTests(root, files, strict = false,workspace=loadRuntimeWorkspac
306
306
 
307
307
  const refusal = (code, section, message, extra = {}) => ({ code, section, message, ...extra });
308
308
  // The PDD interpreter's whole-number range today: prompt_runtime/program_scenario.py (_validate_scenario_integers)
309
- // for test values and prompt_runtime/graph_runtime_protocol.py for schema bounds. Change it only with the interpreter.
310
- const INTERPRETER_INTEGERS = { min: -(2n ** 53n - 1n), max: 2n ** 53n - 1n, text: '-9007199254740991 through 9007199254740991' };
309
+ // for test values and prompt_runtime/graph_runtime_protocol.py for schema bounds (signed 4096-bit exact integers).
310
+ const INTERPRETER_INTEGERS = { min: -(2n ** 4096n - 1n), max: 2n ** 4096n - 1n, text: 'signed 4096-bit exact integers (-(2^4096-1) through 2^4096-1)' };
311
311
  const outsideInterpreter = value => typeof value === 'bigint' && (value < INTERPRETER_INTEGERS.min || value > INTERPRETER_INTEGERS.max);
312
312
  // The interpreter's section of a test value: keys joined by ".", indexes as [N] (steps[10].input.seconds).
313
313
  const interpreterSection = path => path.reduce((text, part) => typeof part === 'number' ? `${text}[${part}]` : text ? `${text}.${part}` : String(part), '');
@@ -2504,10 +2504,10 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
2504
2504
  refused = refusal(error.code ?? 'source-unavailable', 'source', error.message,
2505
2505
  {hint:'Restore the named dependency, make it readable, or correct its declared path.'});
2506
2506
  }
2507
- const closure = summarizePromptClosure(effectiveDoc, { prompts, visible: found.visible, root, workspace: policy, allowMissingInterfaces });
2507
+ // Omit default max_calls when --max-calls is not explicitly set so prompt-runtime owns the cap.
2508
2508
  const row = { test: test.path, story: test.story, title: test.title, refusals: refused ? [refused].flat() : [], warnings: numberWarnings(effectiveDoc, { testPath: test.path, testSha, reviews }),
2509
2509
  ...(stepIds.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:(effectiveDoc?.steps ?? []).filter(step=>stepIds.includes(step?.step_id)).map(step=>step.step_id)} : {}),
2510
- max_calls: defaultMaxCalls(effectiveDoc, closure), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
2510
+ max_calls: null, steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
2511
2511
  criteria_total: plan?.criteria.length ?? (Array.isArray(effectiveDoc?.criteria) ? effectiveDoc.criteria.length : 0),
2512
2512
  ...(plan?.not_checked.length ? {not_checked:plan.not_checked} : {}), draft: false };
2513
2513
  row.native_only = [...executablePaths].map(path => prompts.get(path)).filter(item => item?.interface?.kind === 'native-only').map(item => ({path:item.path,reason:item.interface.reason}));