@promptdriven/runtime-client 1.1.0 → 1.1.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.
@@ -423,6 +423,7 @@ function progressFrom(value) {
423
423
  const progress = {};
424
424
  for (const key of ['steps_done', 'steps_total', 'calls_settled', 'calls_open']) if (count(value?.[key])) progress[key] = value[key];
425
425
  if (Number.isSafeInteger(value?.step) && value.step >= 1 || typeof value?.step === 'string' && value.step.trim()) progress.step = value.step;
426
+ if (typeof value?.stage === 'string' && value.stage.trim()) progress.stage = value.stage.trim();
426
427
  return progress;
427
428
  }
428
429
 
@@ -435,7 +436,9 @@ export function outcomeText(outcome) {
435
436
  const p = outcome.progress ?? {};
436
437
  const number = typeof p.step === 'number' ? p.step : count(p.steps_done) && count(p.steps_total) && p.steps_done < p.steps_total ? p.steps_done + 1 : null;
437
438
  const step = number ? `step ${number}${count(p.steps_total) ? ` of ${p.steps_total}` : ''}` : typeof p.step === 'string' ? p.step : null;
439
+ const stage = !step && typeof p.stage === 'string' && p.stage && !['running', 'queued'].includes(p.stage) ? p.stage : null;
438
440
  return [state + (reason ? ` (${reason.code})` : ''), ...(count(outcome.ahead) ? [`${outcome.ahead} ahead`] : []),
441
+ ...(stage ? [stage] : []),
439
442
  ...(step ? [step + (number && typeof p.step === 'string' ? ` (${p.step})` : '')] : []), ...callWords(p.calls_settled, p.calls_open)].join(' · ');
440
443
  }
441
444
 
@@ -208,6 +208,26 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
208
208
  evidence: Array.isArray(check.diagnosis.evidence) ? check.diagnosis.evidence.map(item => cleanText(item, secrets)).filter(Boolean) : undefined,
209
209
  likely: check.diagnosis.likely === true ? true : undefined,
210
210
  ...(isObjectLike(check.diagnosis.rerun) ? { rerun: rerunStep(check.diagnosis.rerun) } : {}) } : null;
211
+ const json_path = typeof check?.json_path === 'string' ? cleanField(check.json_path, secrets) : undefined;
212
+ const html = isObjectLike(check?.html) ? (() => {
213
+ const meta = {};
214
+ if (typeof check.html.kind === 'string' && check.html.kind) meta.kind = cleanField(check.html.kind, secrets);
215
+ if (typeof check.html.attribute === 'string' && check.html.attribute) meta.attribute = cleanField(check.html.attribute, secrets);
216
+ if (isObjectLike(check.html.selector)) {
217
+ const sel = {};
218
+ if (typeof check.html.selector.tag === 'string' && check.html.selector.tag) sel.tag = cleanField(check.html.selector.tag, secrets);
219
+ if (isObjectLike(check.html.selector.attributes)) {
220
+ const attrs = Object.fromEntries(
221
+ Object.entries(check.html.selector.attributes).slice(0, 20)
222
+ .filter(([k, v]) => typeof k === 'string' && k && typeof v === 'string')
223
+ .map(([k, v]) => [cleanField(k, secrets), cleanField(v, secrets)])
224
+ );
225
+ if (Object.keys(attrs).length) sel.attributes = attrs;
226
+ }
227
+ if (Object.keys(sel).length) meta.selector = sel;
228
+ }
229
+ return Object.keys(meta).length ? meta : undefined;
230
+ })() : undefined;
211
231
  const ref_target = typeof check?.ref_target === 'string' && check.ref_target ? cleanField(check.ref_target, secrets) : undefined;
212
232
  const ref_path = typeof check?.ref_path === 'string' ? cleanField(check.ref_path, secrets) : undefined;
213
233
  const ref_json_path = typeof check?.ref_json_path === 'string' ? cleanField(check.ref_json_path, secrets) : undefined;
@@ -216,11 +236,44 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
216
236
  step_id: cleanField(step?.step_id ?? check?.step_id, secrets) || (stepIndex !== undefined ? cleanField(authoredSteps[stepIndex]?.step_id, secrets) : '') || null,
217
237
  criterion_text: typeof criterionTexts[criterion_id] === 'string' && criterionTexts[criterion_id].length <= 160 ? cleanField(criterionTexts[criterion_id], secrets) : null,
218
238
  target: cleanField(check?.target, secrets), path: cleanField(check?.path, secrets),
239
+ ...(json_path !== undefined ? { json_path } : {}),
240
+ ...(html !== undefined ? { html } : {}),
219
241
  ...(ref_target !== undefined ? { op: cleanField(check?.op, secrets), ref_target, ...(ref_path !== undefined ? { ref_path } : {}), ...(ref_json_path !== undefined ? { ref_json_path } : {}) } : {}),
220
242
  expected: cleanValues(check?.expected, secrets),
221
243
  actual: cleanValues(check?.actual, secrets), passed: check?.passed === true,
222
244
  normal_result: step ? Object.prototype.hasOwnProperty.call(step, 'result') && !step.error : false, ...(diagnosis ? { diagnosis } : {}) };
223
245
  };
246
+ const primarySteps = Array.isArray(report?.samples?.[0]?.steps)
247
+ ? report.samples[0].steps
248
+ : Array.isArray(report?.steps) ? report.steps : [];
249
+ const step_details = primarySteps.filter(isObjectLike).map((step, index) => {
250
+ const step_id = cleanField(step.step_id, secrets) || cleanField(authoredSteps[index]?.step_id, secrets) || `step-${index + 1}`;
251
+ const calls = isObjectLike(step.calls) ? {
252
+ ...(isObjectLike(step.calls.internal) ? { internal: scrubTokens(step.calls.internal) } : {}),
253
+ ...(isObjectLike(step.calls.resources) ? { resources: scrubTokens(step.calls.resources) } : {}),
254
+ } : null;
255
+ const hasCalls = calls && (Object.keys(calls.internal ?? {}).length > 0 || Object.keys(calls.resources ?? {}).length > 0);
256
+ return {
257
+ step_id,
258
+ verdict: typeof step.verdict === 'string' ? cleanField(step.verdict, secrets) : null,
259
+ ...(step.error != null ? { error: scrubTokens(step.error) } : {}),
260
+ ...(Object.prototype.hasOwnProperty.call(step, 'result') ? { result: scrubTokens(step.result) } : {}),
261
+ ...(hasCalls ? { calls } : {}),
262
+ };
263
+ });
264
+ const rawDraftInterfaces = [result?.draft_interfaces, report?.draft_interfaces, report?.summary?.draft_interfaces]
265
+ .find(list => Array.isArray(list) && list.length > 0);
266
+ const draft_interfaces = rawDraftInterfaces
267
+ ? rawDraftInterfaces.map(item => isObjectLike(item)
268
+ ? {
269
+ path: typeof item.path === 'string' ? cleanField(item.path, secrets) : null,
270
+ ...(typeof item.prose_sha256 === 'string' ? { prose_sha256: cleanField(item.prose_sha256, secrets) } : {}),
271
+ ...(typeof item.state === 'string' ? { state: cleanField(item.state, secrets) } : {}),
272
+ }
273
+ : typeof item === 'string' ? { path: cleanField(item, secrets) } : null).filter(item => item?.path)
274
+ : Array.isArray(answer?.draft_prompts) && answer.draft_prompts.length > 0
275
+ ? answer.draft_prompts.filter(item => typeof item === 'string' && item).map(path => ({ path: cleanField(path, secrets) }))
276
+ : [];
224
277
  const all = sampleSteps.flatMap(({ step, index }) => Array.isArray(step?.checks) ? step.checks.map(check => ({ step, check, index })) : [])
225
278
  .map(({ step, check, index }) => projectCheck(check, step, index));
226
279
  const sampleFailed = all.filter(check => !check.passed).map(({ passed, ...check }) => check);
@@ -284,6 +337,8 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
284
337
  time_limit, checks,
285
338
  criteria: results.length ? { passed: results.filter(item => item?.status === 'passed').length, total: results.length } : null,
286
339
  all_checks: all, failed_checks, refusals,
340
+ ...(step_details.length && sampleEvidence !== 'flat' && (outcome.state === 'failed' || failed_checks.length > 0 || primarySteps.some(step => typeof step?.verdict === 'string' || Array.isArray(step?.checks))) ? { step_details } : {}),
341
+ ...(draft_interfaces.length ? { draft_interfaces } : {}),
287
342
  calls: !incomplete ? usageCalls : 'unknown',
288
343
  ...tokens,
289
344
  ...(incomplete ? { known_calls: knownCalls } : {}), unknown_calls: unknownCalls, accounting_complete: !incomplete, requested_model: model ? cleanText(model, secrets) : null,
@@ -358,20 +413,27 @@ export function tokenUsageOf(answer, { incomplete = false } = {}) {
358
413
  if (allCurrent && ((tIn !== undefined && tIn !== cIn) || (tCached !== undefined && tCached !== cCached))) return unknownTokens();
359
414
  muIn = cIn;
360
415
  muCached = cCached;
361
- if (dispatched.length > 0 && dispatched.every(call => tokenInt(call.output_tokens) !== undefined)) {
416
+ if (dispatched.length === 0 && complete === true) {
417
+ muOut = tOut ?? 0;
418
+ } else if (dispatched.length > 0 && dispatched.every(call => tokenInt(call.output_tokens) !== undefined)) {
362
419
  muOut = dispatched.reduce((sum, call) => sum + call.output_tokens, 0);
420
+ } else if (tOut !== undefined) {
421
+ muOut = tOut;
363
422
  }
364
423
  } else if (complete === true) {
365
424
  muIn = tIn ?? 0;
366
425
  muCached = tCached ?? 0;
367
- muOut = tOut;
426
+ muOut = tOut ?? 0;
368
427
  }
369
428
  } else if (complete === true) {
370
429
  if (tIn === undefined || tCached === undefined) return unknownTokens();
371
430
  muIn = tIn;
372
431
  muCached = tCached;
373
- muOut = tOut;
432
+ muOut = tOut ?? (tIn === 0 && usage.calls === 0 ? 0 : undefined);
374
433
  } else return unknownTokens();
434
+ } else if (['passed', 'failed', 'refused'].includes(answer?.state) && usage.calls === 0
435
+ && uIn === undefined && uCached === undefined && uOut === undefined) {
436
+ return { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, cached_input_share: null };
375
437
  }
376
438
  const input_tokens = muIn ?? uIn ?? 'unknown';
377
439
  const cached_input_tokens = muCached ?? uCached ?? 'unknown';
@@ -435,11 +497,16 @@ function batchTokenUsage(publicRows) {
435
497
  return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens), complete };
436
498
  }
437
499
 
438
- export function renderJson({ batch = null, repo, sourceSha256 = null, coverage, rows, warnings = [], exitCode, summaryLine: line }, ports = {}) {
500
+ export function renderJson({ batch = null, repo, sourceSha256 = null, coverage, rows, warnings = [], exitCode, summaryLine: line, details = false }, ports = {}) {
439
501
  rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
440
502
  line = line ?? summaryLine(rows, null, ports);
441
503
  const perStory = new Map(storyLines(rows, ports).map(([story, text]) => [story, text]));
442
- const publicRows = rows.map(row => ({ ...jsonRow(row), summary_line: perStory.get(row.story) ?? null }));
504
+ const publicRows = rows.map(row => ({
505
+ ...jsonRow(row),
506
+ ...(details && row.step_details?.length ? { step_details: row.step_details } : {}),
507
+ ...(details && row.draft_interfaces?.length ? { draft_interfaces: row.draft_interfaces } : {}),
508
+ summary_line: perStory.get(row.story) ?? null,
509
+ }));
443
510
  const diagnostic = rows.filter(row=>row.diagnostic_subset === true);
444
511
  return { batch, repo, ...(diagnostic.length ? {diagnostic_subset:true,selected_steps:[...new Set(diagnostic.flatMap(row=>row.selected_steps ?? []))]} : {}), ...(coverage ? { coverage } : {}), source_sha256: sourceSha256, exit_code: exitCode, summary_line: line, draft: rows.some(row => row.draft),
445
512
  token_usage: batchTokenUsage(publicRows), rows: publicRows, warnings };
@@ -513,9 +580,75 @@ const plainLine = (text, secrets) => secrets.reduce((value, secret) => secret ?
513
580
  const oneLine = value => typeof value !== 'string' || !/\n(?!$)/.test(value);
514
581
  const valueLines = value => typeof value === 'string' ? value.replace(/\n$/, '').split('\n') : (JSON.stringify(value, null, 2) ?? 'nothing').split('\n');
515
582
 
583
+ const formatHtmlCheckLabel = (html, secrets) => {
584
+ if (!isObjectLike(html)) return '';
585
+ const tag = typeof html.selector?.tag === 'string' ? cleanField(html.selector.tag, secrets) : '';
586
+ const attrs = isObjectLike(html.selector?.attributes)
587
+ ? Object.entries(html.selector.attributes).slice(0, 6).map(([k, v]) => `[${cleanField(k, secrets)}=${JSON.stringify(cleanField(v, secrets))}]`).join('')
588
+ : '';
589
+ const sel = `${tag}${attrs}`;
590
+ const kind = typeof html.kind === 'string' ? cleanField(html.kind, secrets) : '';
591
+ const attr = typeof html.attribute === 'string' ? `@${cleanField(html.attribute, secrets)}` : '';
592
+ const desc = [sel, kind && `${kind}${attr}`].filter(Boolean).join(' ');
593
+ return desc ? `(html ${desc})` : '';
594
+ };
595
+
596
+ const boundedPreview = (value, secrets, limit = 400) => {
597
+ const raw = typeof value === 'string' ? cleanField(value, secrets) : shown(value, secrets);
598
+ return raw.length <= limit ? raw : `${raw.slice(0, limit - 1)}…`;
599
+ };
600
+
601
+ const formatStepCalls = (calls, secrets) => {
602
+ if (!isObjectLike(calls)) return null;
603
+ const parts = [];
604
+ for (const [group, label] of [['internal', 'internal'], ['resources', 'resources']]) {
605
+ if (!isObjectLike(calls[group])) continue;
606
+ const entries = Object.entries(calls[group]);
607
+ if (!entries.length) continue;
608
+ const shownEntries = entries.slice(0, 12).map(([name, count]) => `${cleanField(name, secrets)}=${count}`);
609
+ if (entries.length > 12) shownEntries.push(`… (+${entries.length - 12} more)`);
610
+ parts.push(`${label}: ${shownEntries.join(', ')}`);
611
+ }
612
+ return parts.length ? parts.join('; ') : null;
613
+ };
614
+
615
+ function stepContextLines(step, secrets, { indent = ' ', includeVerdict = false } = {}) {
616
+ if (!isObjectLike(step)) return [];
617
+ const body = [];
618
+ if (step.error != null) body.push(`${indent} Error: ${boundedPreview(step.error, secrets, 400)}`);
619
+ if (Object.prototype.hasOwnProperty.call(step, 'result') && step.result !== undefined) {
620
+ if (isObjectLike(step.result)) {
621
+ const hasCliOrCode = ['exit_code', 'exitCode', 'code', 'stdout', 'stderr'].some(key => Object.hasOwn(step.result, key));
622
+ if (hasCliOrCode) {
623
+ const meta = [];
624
+ for (const key of ['exit_code', 'exitCode', 'code']) {
625
+ if (Object.hasOwn(step.result, key) && step.result[key] !== undefined) meta.push(`${key}=${boundedPreview(step.result[key], secrets, 120)}`);
626
+ }
627
+ if (meta.length) body.push(`${indent} Output: ${meta.join(' · ')}`);
628
+ if (typeof step.result.stdout === 'string' && step.result.stdout.trim()) body.push(`${indent} stdout: ${boundedPreview(step.result.stdout, secrets, 500)}`);
629
+ else if (step.result.stdout !== undefined && typeof step.result.stdout !== 'string') body.push(`${indent} stdout: ${boundedPreview(step.result.stdout, secrets, 500)}`);
630
+ if (typeof step.result.stderr === 'string' && step.result.stderr.trim()) body.push(`${indent} stderr: ${boundedPreview(step.result.stderr, secrets, 300)}`);
631
+ else if (step.result.stderr !== undefined && typeof step.result.stderr !== 'string') body.push(`${indent} stderr: ${boundedPreview(step.result.stderr, secrets, 300)}`);
632
+ } else {
633
+ body.push(`${indent} Result: ${boundedPreview(step.result, secrets, 500)}`);
634
+ }
635
+ } else {
636
+ body.push(`${indent} Result: ${boundedPreview(step.result, secrets, 500)}`);
637
+ }
638
+ }
639
+ const callsText = formatStepCalls(step.calls, secrets);
640
+ if (callsText) body.push(`${indent} Calls: ${callsText}`);
641
+ if (!body.length && !includeVerdict) return [];
642
+ const label = cleanField(step.step_id || 'unnamed', secrets);
643
+ const verdict = includeVerdict && step.verdict ? ` (${cleanField(step.verdict, secrets)})` : '';
644
+ return [`${indent}Step ${label}${verdict}:`, ...body];
645
+ }
646
+
516
647
  // The check line: one line when both values fit, else the check and a block for each value, never cut inside a line.
517
648
  function checkLines(check, secrets) {
518
- const head = `${check.criterion_id}${check.step_id ? ` step ${check.step_id}` : ''} ${check.target} ${check.path}`;
649
+ const jsonPath = typeof check.json_path === 'string' ? ` (${check.json_path || '/'})` : '';
650
+ const htmlDesc = isObjectLike(check.html) ? formatHtmlCheckLabel(check.html, secrets) : '';
651
+ const head = `${check.criterion_id}${check.step_id ? ` step ${check.step_id}` : ''} ${check.target} ${check.path}${jsonPath}${htmlDesc ? ` ${htmlDesc}` : ''}`;
519
652
  const noError = check.target === 'error' && check.actual && typeof check.actual === 'object' && !Array.isArray(check.actual)
520
653
  && check.actual.missing === true && Object.keys(check.actual).length === 1
521
654
  && (check.normal_result === true || ['no-error', 'needs-tool'].includes(check.diagnosis?.kind));
@@ -630,6 +763,14 @@ export function renderText({ batch, rows, coverage, warnings = [], details = fal
630
763
  const key = check.step_id ?? '', line = rerunByStep.get(key);
631
764
  if (line) { lines.push(line); rerunByStep.delete(key); }
632
765
  }
766
+ if (Array.isArray(row.step_details) && row.step_details.length) {
767
+ const failedStepIds = [...new Set(failed.map(check => check.step_id).filter(Boolean))];
768
+ const stepMap = new Map(row.step_details.map(step => [step.step_id, step]));
769
+ for (const stepId of failedStepIds) {
770
+ const ctx = stepContextLines(stepMap.get(stepId), secrets, { indent: ' ' });
771
+ if (ctx.length) lines.push(...ctx);
772
+ }
773
+ }
633
774
  if (reruns.some(item => item.key === null)) lines.push(reruns.find(item => item.key === null).line);
634
775
  if (fullFailure) lines.push(...(row.warnings ?? []).map(text => ` ${text}`));
635
776
  const diagnosed = failed.some(check => check.diagnosis?.why || check.diagnosis?.next_step);
@@ -681,10 +822,18 @@ export function renderText({ batch, rows, coverage, warnings = [], details = fal
681
822
  }
682
823
  if (!evidence.complete) out.push('Sample comparison incomplete; agreement is unknown.');
683
824
  }
684
- if (details) for (const row of rows.filter(row => row.all_checks?.length || !row.cached && formatPromptCacheTokens(row))) {
825
+ if (details) for (const row of rows.filter(row => row.all_checks?.length || row.step_details?.length || row.draft_interfaces?.length || !row.cached && formatPromptCacheTokens(row))) {
685
826
  const tokenText = !row.cached ? formatPromptCacheTokens(row) : null;
827
+ const draftLines = Array.isArray(row.draft_interfaces) && row.draft_interfaces.length
828
+ ? [' Draft interfaces:', ...row.draft_interfaces.map(item => ` ${cleanField(item.path, secrets)}${item.prose_sha256 ? ` (${cleanField(item.prose_sha256, secrets).slice(0, 12)})` : ''}`)]
829
+ : [];
830
+ const stepLines = Array.isArray(row.step_details) && row.step_details.length
831
+ ? [' Steps:', ...row.step_details.flatMap(step => stepContextLines(step, secrets, { indent: ' ', includeVerdict: true }))]
832
+ : [];
686
833
  out.push(`Checks for ${row.title} (${row.test}):`,
687
834
  ...(tokenText ? [` Tokens: ${tokenText}`] : []),
835
+ ...draftLines,
836
+ ...stepLines,
688
837
  ...[...(row.all_checks ?? [])].sort((a, b) => a.passed - b.passed).flatMap(check => checkLines(check, secrets)
689
838
  .map((text, index) => index ? ` ${text}` : ` ${check.passed ? 'passed' : 'failed'} ${text}`)));
690
839
  }
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: 82c0d4c07385035d6555f688ddda347268bd17777f02d8394079955bc0d7d0c9).
1
+ // Generated from prompts/cli/runtime-preflight.prompt.md (sha256: e4f44576c9130a890ca3b7c16284bcabb7a9c42788e097f636419ed7f1ddabd2).
2
2
  import { markdownLinks, markdownDefinitions, markdownSectionText } from './runtime-markdown.mjs';
3
3
  import { buildBindingPlan, runtimeBoundary } from './runtime-binding-plan.mjs';
4
4
  import { createHash } from 'node:crypto';
@@ -26,6 +26,15 @@ const OPTIONAL_STEP_KEYS = ['expected_error', 'simulation_overrides', 'model'];
26
26
  const STEP_KEYS = new Set([...REQUIRED_STEP_KEYS, ...OPTIONAL_STEP_KEYS]);
27
27
  const RULE_OPS = new Set(['at_most', 'at_least', 'lt', 'lte', 'gt', 'gte', 'not_contains', 'all_in', 'equals_ignore_case']);
28
28
  const EXACT_OPS = new Set(['equals', 'not_equals', 'one_of', 'count', 'integer_relation', ...RULE_OPS]);
29
+ const CHECK_OPS = new Set([...EXACT_OPS, 'exists', 'contains']);
30
+ const CALLS_OPS = new Set(['count', 'equals', 'not_equals', 'one_of']);
31
+ const ERROR_OPS = new Set(['count', 'equals', 'exists', 'not_equals', 'one_of']);
32
+ const CHECK_KEYS = new Set(['criterion_id', 'target', 'path', 'op', 'value', 'json_path', 'html', 'measure',
33
+ 'ref_target', 'ref_path', 'ref_json_path', 'derivation']);
34
+ const hasCheckRef = check => isObject(check) && (
35
+ Object.hasOwn(check, 'ref_target') || Object.hasOwn(check, 'ref_path') || Object.hasOwn(check, 'ref_json_path')
36
+ || (isObject(check.value) && (Object.hasOwn(check.value, 'ref_target') || Object.hasOwn(check.value, 'ref_path')))
37
+ );
29
38
  const SCHEMA_RULES = new Set(['type', 'properties', 'required', 'additionalProperties', 'items', 'enum', 'const', 'oneOf',
30
39
  'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf', 'minLength', 'maxLength', 'pattern',
31
40
  'minItems', 'maxItems', 'uniqueItems', 'minProperties', 'maxProperties']);
@@ -831,7 +840,7 @@ export function analyzePromptSelectorWords(prompt, { appMapScreens = [] } = {})
831
840
  || (Array.isArray(entry.conventions) && entry.conventions.includes('screen'))
832
841
  || conventions.some(c => isObject(c) && typeof c.path === 'string' && c.path.startsWith(`/entries/${index}/`) && c.convention === 'screen');
833
842
  const screenBoundOp = typeof entry.operation === 'string'
834
- && appMapScreens.some(screen => screen?.source === 'operation' && screen.prompt_path === prompt.path && screen.operation === entry.operation);
843
+ && appMapScreens.some(screen => (screen?.source ?? 'operation') === 'operation' && screen.prompt_path === prompt.path && (screen.operation ?? 'render') === entry.operation);
835
844
 
836
845
  if (entryIsCli) {
837
846
  kinds.add('cli');
@@ -1033,9 +1042,91 @@ export function numberWarnings(doc, { testPath, testSha, reviews = [] } = {}) {
1033
1042
  return [...warnings];
1034
1043
  }
1035
1044
 
1045
+ export const LAZY_INTERFACE_SYNTHESIS_CALLS = 2;
1046
+ const LAZY_INTERFACE_SYNTHESIS_HEADROOM = 4;
1047
+ const CALL_GRAPH_FANOUT_PER_PROMPT = 5;
1048
+ const CALL_GRAPH_EXECUTION_HEADROOM = 1.75;
1049
+
1050
+ export const hasSimulationBindings = (doc, step = null) =>
1051
+ (typeof doc?.$simulation === 'string' && doc.$simulation.trim().length > 0)
1052
+ || (isObject(doc?.simulation) && Object.keys(doc.simulation).length > 0)
1053
+ || (isObject(step?.simulation_overrides) && Object.keys(step.simulation_overrides).length > 0);
1054
+
1055
+ export function analyzeStepCallCost(entryPath, {
1056
+ getPrompt,
1057
+ visible,
1058
+ allowMissingInterfaces = false,
1059
+ hasSimulationPorts = false,
1060
+ onProblem = null,
1061
+ missingInterfaces = null,
1062
+ reachablePrompts = null,
1063
+ }) {
1064
+ const walk = (path, stack = new Set(), proseOnly = false) => {
1065
+ if (stack.has(path)) {
1066
+ if (!proseOnly && onProblem) onProblem('recursive-call-bound', path, '/calls');
1067
+ return 0;
1068
+ }
1069
+ const prompt = getPrompt(path);
1070
+ const iface = prompt?.interface;
1071
+ if (!iface) {
1072
+ if (allowMissingInterfaces && prompt?.error === 'interface-missing') {
1073
+ missingInterfaces?.add(path);
1074
+ reachablePrompts?.add(path);
1075
+ const next = new Set([...stack, path]);
1076
+ const targets = [...new Set(promptMarkdownTargets(prompt.text, path, visible))];
1077
+ const activeChildren = [];
1078
+ for (const target of targets) {
1079
+ const nested = walk(target, next, true);
1080
+ if (nested > 0) activeChildren.push(nested);
1081
+ }
1082
+ const ownBase = hasSimulationPorts || activeChildren.length > 0 || stack.size > 0 ? 2 : 1;
1083
+ return ownBase + activeChildren.reduce((sum, nested) => sum + nested + 1, 0);
1084
+ }
1085
+ if (onProblem) onProblem(prompt?.error ?? 'interface-missing', path, '/interface');
1086
+ return 0;
1087
+ }
1088
+ if (iface.kind === 'native-only') return 0;
1089
+ reachablePrompts?.add(path);
1090
+ if ((!Number.isSafeInteger(iface.limits?.max_model_calls) || iface.limits.max_model_calls < 1) && onProblem) {
1091
+ onProblem('undefined-call-bound', path, '/limits/max_model_calls');
1092
+ }
1093
+ const next = new Set([...stack, path]);
1094
+ let count = 1 + (Array.isArray(iface.resources) ? iface.resources : []).reduce(
1095
+ (sum, resource) => sum + (Array.isArray(resource.operations) ? resource.operations.length : 0),
1096
+ 0,
1097
+ );
1098
+ for (const [index, call] of (Array.isArray(iface.calls) ? iface.calls : []).entries()) {
1099
+ if ((!Number.isSafeInteger(call?.max_calls) || call.max_calls < 1) && onProblem) {
1100
+ onProblem('undefined-call-bound', path, `/calls/${index}/max_calls`);
1101
+ }
1102
+ const nested = walk(call?.target, next, false);
1103
+ if (Number.isSafeInteger(call?.max_calls) && call.max_calls >= 1 && nested > 0) {
1104
+ count += call.max_calls * (nested + 1);
1105
+ }
1106
+ }
1107
+ return count;
1108
+ };
1109
+ return walk(entryPath, new Set(), false);
1110
+ }
1111
+
1036
1112
  const stepCount = doc => Array.isArray(doc?.steps) ? doc.steps.length : 0;
1113
+ const positiveInt = value => Number.isSafeInteger(value) && value > 0 ? value : 0;
1037
1114
  // Leave room for the whole call graph; the budget is a ceiling, not a charge.
1038
- export const defaultMaxCalls = doc => Math.min(1000, Math.max(18, stepCount(doc) * 12));
1115
+ export function defaultMaxCalls(doc, closure = null) {
1116
+ const steps = stepCount(doc);
1117
+ const baseline = Math.max(18, steps * 12);
1118
+ if (steps === 0 || !isObject(closure)) return Math.min(1000, baseline);
1119
+ const estimatedStepCalls = positiveInt(closure.estimatedStepCalls);
1120
+ const missingInterfaces = positiveInt(closure.missingInterfaceCount);
1121
+ const stepPromptCount = positiveInt(closure.stepPromptCount);
1122
+ const perStepNodes = positiveInt(closure.maxChainFanOut) || positiveInt(closure.promptCount);
1123
+ const fanOutBudget = stepPromptCount > 0
1124
+ ? stepPromptCount * CALL_GRAPH_FANOUT_PER_PROMPT
1125
+ : perStepNodes > 0 ? steps * perStepNodes * CALL_GRAPH_FANOUT_PER_PROMPT : 0;
1126
+ const graphBudget = Math.max(Math.ceil(estimatedStepCalls * CALL_GRAPH_EXECUTION_HEADROOM), fanOutBudget)
1127
+ + missingInterfaces * LAZY_INTERFACE_SYNTHESIS_HEADROOM;
1128
+ return Math.min(1000, Math.max(baseline, graphBudget));
1129
+ }
1039
1130
 
1040
1131
  function firstDifference(testTexts, storyTexts) {
1041
1132
  const left = [...storyTexts];
@@ -1050,7 +1141,7 @@ function firstDifference(testTexts, storyTexts) {
1050
1141
  // Coverage is structural. A negative assertion with an exact calls/world check is checkable.
1051
1142
  const exactCheck = check => EXACT_OPS.has(check?.op) || (isObject(check) && Object.hasOwn(check, 'html') && check.op === 'exists');
1052
1143
  const ordinaryInexactCheck = check => isObject(check) && ['exists','contains'].includes(check.op)
1053
- && ['result','world','calls','error'].includes(check.target) && typeof check.path === 'string'
1144
+ && ['result','world','calls','error','input'].includes(check.target) && typeof check.path === 'string'
1054
1145
  && (check.path === '' || check.path.startsWith('/')) && !/~(?![01])/.test(check.path)
1055
1146
  && (check.op !== 'contains' || Object.hasOwn(check,'value'));
1056
1147
  function criterionPlan(doc, story) {
@@ -1232,7 +1323,7 @@ function stepProblem(step) {
1232
1323
  return null;
1233
1324
  }
1234
1325
  const checkShape = check => isObject(check) && ['criterion_id','target','path','op'].every(key=>Object.hasOwn(check,key));
1235
- const checkTargets = new Set(['result', 'world', 'calls', 'error']);
1326
+ const checkTargets = new Set(['result', 'world', 'calls', 'error', 'input']);
1236
1327
 
1237
1328
  // Reject only paths whose absence is established by every schema alternative.
1238
1329
  function resultPathPossible(schema, path) {
@@ -1858,12 +1949,72 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false,
1858
1949
  return done(refusal('invalid-check', `${section}.checks[${checkIndex}]`, 'A check has criterion_id, target, path and op.', at), story);
1859
1950
  }
1860
1951
  const checkSection = `${section}.checks[${checkIndex}]`;
1861
- if (!checkTargets.has(check.target)) return done(refusal('invalid-check', checkSection, 'A check target must be "result", "world", "calls" or "error".', at), story);
1952
+ const extraKeys = Object.keys(check).filter(key => !CHECK_KEYS.has(key)).sort();
1953
+ if (extraKeys.length) {
1954
+ const isPredicate = typeof check.op === 'string' && (RULE_OPS.has(check.op) || check.op === 'integer_relation');
1955
+ return done(refusal(
1956
+ isPredicate ? 'invalid-predicate' : 'invalid-check',
1957
+ checkSection,
1958
+ isPredicate
1959
+ ? `The check predicate has unsupported keys: ${extraKeys.map(show).join(', ')}.`
1960
+ : `The check has unknown keys: ${extraKeys.map(show).join(', ')}.`,
1961
+ at,
1962
+ ), story);
1963
+ }
1964
+ if (typeof check.target !== 'string' || !checkTargets.has(check.target)) {
1965
+ const message = check.target === 'output'
1966
+ ? 'A check target must be "result", "world", "calls", "error" or "input". Use target "result" to check a step\'s returned output.'
1967
+ : 'A check target must be "result", "world", "calls", "error" or "input".';
1968
+ return done(refusal('invalid-check', checkSection, message, at), story);
1969
+ }
1970
+ if (typeof check.op !== 'string' || !CHECK_OPS.has(check.op)) {
1971
+ return done(refusal(
1972
+ 'unsupported-check',
1973
+ checkSection,
1974
+ `Unsupported check op ${show(check.op)}. Supported ops: ${[...CHECK_OPS].sort().join(', ')}.`,
1975
+ at,
1976
+ ), story);
1977
+ }
1978
+ if (check.target === 'calls' || check.target === 'error') {
1979
+ const allowed = [...(check.target === 'calls' ? CALLS_OPS : ERROR_OPS)].join(', ');
1980
+ if (hasCheckRef(check)) {
1981
+ return done(refusal(
1982
+ 'unsupported-check',
1983
+ checkSection,
1984
+ `Cross-path reference checks (ref_target/ref_path) apply only to "result", "world", and "input" targets, not "${check.target}".`,
1985
+ { ...at, hint: `Check target "result", "world", or "input", or use a literal value with an op supported for "${check.target}" (${allowed}).` },
1986
+ ), story);
1987
+ }
1988
+ if (RULE_OPS.has(check.op) || check.op === 'integer_relation') {
1989
+ return done(refusal(
1990
+ 'unsupported-check',
1991
+ checkSection,
1992
+ `Check op "${check.op}" applies only to "result", "world", and "input" targets; target "${check.target}" supports ${allowed}.`,
1993
+ { ...at, hint: `Change target to "result", "world", or "input", or use a supported op for "${check.target}" (${allowed}).` },
1994
+ ), story);
1995
+ }
1996
+ if (check.op === 'contains') {
1997
+ return done(refusal(
1998
+ 'invalid-contains',
1999
+ checkSection,
2000
+ `Check op "contains" applies only to "result", "world", and "input" targets, not "${check.target}".`,
2001
+ { ...at, hint: `Change target to "result", "world", or "input", or use a supported op for "${check.target}" (${allowed}).` },
2002
+ ), story);
2003
+ }
2004
+ if (check.target === 'calls' && check.op === 'exists') {
2005
+ return done(refusal(
2006
+ 'invalid-call-check',
2007
+ checkSection,
2008
+ 'Target "calls" does not support op "exists"; it supports count, equals, not_equals, and one_of.',
2009
+ { ...at, hint: 'Use "equals" with an integer call count (including 0) on /internal/<id> or /resources/<id>, or "count" on /internal or /resources.' },
2010
+ ), story);
2011
+ }
2012
+ }
1862
2013
  if (check.target === 'result' && errorStep) resultWithErrorRefusal ??= refusal('invalid-check', checkSection, 'A step with expected_error cannot check a successful result. Check the error instead.', at);
1863
2014
  if (check.target === 'result' && entry?.result_schema && !resultPathPossible(entry.result_schema, check.path)) {
1864
2015
  return done(refusal('invalid-check', `${checkSection}.path`, `${show(check.path)} cannot address a value in the result schema of ${step.operation} in ${step.entry_path}.`, at), story);
1865
2016
  }
1866
- if (!ids.has(check.criterion_id)) return done(refusal('unknown-criterion', `${section}.checks[${checkIndex}]`, `The check names ${show(check.criterion_id)}, which is not a criterion ID.`, at), story);
2017
+ if (typeof check.criterion_id !== 'string' || !ids.has(check.criterion_id)) return done(refusal('unknown-criterion', `${section}.checks[${checkIndex}]`, `The check names ${show(check.criterion_id)}, which is not a criterion ID.`, at), story);
1867
2018
  if (EXACT_OPS.has(check.op) || (Object.hasOwn(check, 'html') && check.op === 'exists')) exact.add(check.criterion_id);
1868
2019
  if (check.target === 'error' && check.path === '/code' && check.op === 'equals' && check.value === step.expected_error) errorChecks += 1;
1869
2020
  }
@@ -1887,6 +2038,42 @@ function checkTest(root, found, test, prompts, { allowMissingInterfaces = false,
1887
2038
  return done(null, story);
1888
2039
  }
1889
2040
 
2041
+ function summarizePromptClosure(doc, { prompts, visible, root, workspace, allowMissingInterfaces }) {
2042
+ const steps = Array.isArray(doc?.steps) ? doc.steps : [];
2043
+ if (!steps.length) return null;
2044
+ const getPrompt = path => {
2045
+ if (typeof path !== 'string' || !path) return { error: 'entry-missing' };
2046
+ if (!prompts.has(path)) {
2047
+ try { prompts.set(path, readPrompt(root, visible, path, workspace)); }
2048
+ catch { prompts.set(path, { error: 'interface-unavailable' }); }
2049
+ }
2050
+ return prompts.get(path);
2051
+ };
2052
+ const allPrompts = new Set(), missingInterfaces = new Set();
2053
+ let estimatedStepCalls = 0, stepPromptCount = 0, maxChainFanOut = 0;
2054
+ for (const step of steps) {
2055
+ const stepPrompts = new Set();
2056
+ estimatedStepCalls += analyzeStepCallCost(step?.entry_path, {
2057
+ getPrompt,
2058
+ visible,
2059
+ allowMissingInterfaces,
2060
+ hasSimulationPorts: hasSimulationBindings(doc, step),
2061
+ missingInterfaces,
2062
+ reachablePrompts: stepPrompts,
2063
+ });
2064
+ for (const path of stepPrompts) allPrompts.add(path);
2065
+ stepPromptCount += stepPrompts.size;
2066
+ if (stepPrompts.size > maxChainFanOut) maxChainFanOut = stepPrompts.size;
2067
+ }
2068
+ return {
2069
+ estimatedStepCalls,
2070
+ promptCount: allPrompts.size,
2071
+ stepPromptCount,
2072
+ maxChainFanOut,
2073
+ missingInterfaceCount: missingInterfaces.size,
2074
+ };
2075
+ }
2076
+
1890
2077
  // Rules P1-P10 for the selected tests. Returns rows and warnings; never throws for a test problem.
1891
2078
  export function preflight({ root, found, selected,workspace=found.workspace??loadRuntimeWorkspace({root}), allowMissingInterfaces = false, localLint = false, stepIds = [] }) {
1892
2079
  found={...found,workspace};for(const test of selected)requireRuntimePath(workspace,{path:test.path,from:'Selected test'});
@@ -1926,9 +2113,10 @@ export function preflight({ root, found, selected,workspace=found.workspace??loa
1926
2113
  refused = refusal(error.code ?? 'source-unavailable', 'source', error.message,
1927
2114
  {hint:'Restore the named dependency, make it readable, or correct its declared path.'});
1928
2115
  }
2116
+ const closure = summarizePromptClosure(effectiveDoc, { prompts, visible: found.visible, root, workspace, allowMissingInterfaces });
1929
2117
  const row = { test: test.path, story: test.story, title: test.title, refusals: refused ? [refused].flat() : [], warnings: numberWarnings(effectiveDoc, { testPath: test.path, testSha, reviews }),
1930
2118
  ...(stepIds.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:(effectiveDoc?.steps ?? []).filter(step=>stepIds.includes(step?.step_id)).map(step=>step.step_id)} : {}),
1931
- max_calls: defaultMaxCalls(effectiveDoc), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
2119
+ max_calls: defaultMaxCalls(effectiveDoc, closure), steps: Array.isArray(effectiveDoc?.steps) ? effectiveDoc.steps : [],
1932
2120
  criteria_total: plan?.criteria.length ?? (Array.isArray(effectiveDoc?.criteria) ? effectiveDoc.criteria.length : 0),
1933
2121
  ...(plan?.not_checked.length ? {not_checked:plan.not_checked} : {}), draft: false };
1934
2122
  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}));
@@ -2735,7 +2923,7 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
2735
2923
  if (output.role !== undefined) {
2736
2924
  if (output.role !== 'app-map' || prepared.filter(file=>file.role==='app-map').length !== 1 || appMap !== null) throw new PreflightError(4,'prepareSource may mark exactly one app-map and cannot override an explicit map.');
2737
2925
  let map;try{map=JSON.parse(Buffer.from(output.bytes).toString('utf8'));}catch{throw new PreflightError(4,'Prepared app-map must be valid JSON.');}
2738
- if(!isObject(map)||map.schema_version!=='prompt-runtime.app-map.v1')throw new PreflightError(4,'Prepared app-map must be a v1 app map.');
2926
+ if(!isObject(map)||(Object.hasOwn(map,'schema_version')&&!['prompt-runtime.app-map.v1','prompt-runtime.app-map.v2'].includes(map.schema_version))||!Array.isArray(map.screens))throw new PreflightError(4,'Prepared app-map must be a valid app map.');
2739
2927
  appMap=path;
2740
2928
  }
2741
2929
  if (overlay.has(path)) throw sourceProblem('prepareSource', path, `duplicates prepared file ${path}.`);
@@ -2800,10 +2988,15 @@ function captureOnce(root, { tests, appMap = null, prepareSource,sourceIncludes=
2800
2988
  const mapRefusal=appMapsRefusal(doc);
2801
2989
  if (mapRefusal) throw Object.assign(new PreflightError(4,path+': '+mapRefusal.section+': '+mapRefusal.message),
2802
2990
  {code:mapRefusal.code,section:mapRefusal.section});
2803
- if (typeof doc.story_path === 'string') {
2804
- if (selecting) { if (!storyTests.has(doc.story_path)) storyTests.set(doc.story_path,[]); if (!storyTests.get(doc.story_path).includes(path)) storyTests.get(doc.story_path).push(path); }
2805
- add(doc.story_path, path, 'story');
2991
+ const effectiveStoryPath = typeof doc.story_path === 'string' && doc.story_path
2992
+ ? doc.story_path
2993
+ : (path.endsWith('.json') && visible.has(`user_stories/${basename(path, '.json')}.md`)
2994
+ ? `user_stories/${basename(path, '.json')}.md` : null);
2995
+ if (typeof effectiveStoryPath === 'string') {
2996
+ if (selecting) { if (!storyTests.has(effectiveStoryPath)) storyTests.set(effectiveStoryPath,[]); if (!storyTests.get(effectiveStoryPath).includes(path)) storyTests.get(effectiveStoryPath).push(path); }
2997
+ add(effectiveStoryPath, path, 'story');
2806
2998
  }
2999
+ if (typeof doc.entry_path === 'string' && doc.entry_path) add(doc.entry_path, path);
2807
3000
  addStrings(doc.entry_paths, path);
2808
3001
  addStrings(doc.app_maps, path, 'app-map');
2809
3002
  for (const step of Array.isArray(doc.steps) ? doc.steps : []) if (typeof step?.entry_path === 'string') add(step.entry_path, path);