@promptdriven/runtime-client 1.0.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.
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-outcome.prompt.md (sha256: b70ee8a227e1d2fe4788304de5ae87cf28242d91c7be013cce19d02419ac58fe).
1
+ // Generated from prompts/cli/runtime-outcome.prompt.md (sha256: 98302ea9052a277f10fe8dec361bc72e0825fc2d5d6d031def30bcc5eb1d67f2).
2
2
  // What happened to one selected test: the one place that turns a server answer into an outcome.
3
3
  export const PROVIDER_TEXT = 'the AI provider failed during the run. It is not a failed check. Do not send it again yet.';
4
4
  export const CHECK_STATES = Object.freeze(['waiting', 'sent', 'passed', 'failed', 'refused', 'partial', 'not run']);
@@ -27,6 +27,7 @@ export function resultOutcome(row = {}) {
27
27
  if (row.unsent && row.refusals?.length) { code='broken-test'; state='not run'; }
28
28
  if (code === 'broken-test') state = 'not run';
29
29
  if (state === 'not run' && (row.retryable === true || row.busy_display) && !['timeout-flag', 'deadline', 'interrupted'].includes(code)) code = 'server-busy';
30
+ if (state === 'passed' && row.diagnostic_subset === true && !row.sample_subset) return {state:'partial',reason:{code:'diagnostic-subset',message:'diagnostic subset, not a full Story pass'}};
30
31
  if (state === 'passed') return { state, reason: null };
31
32
  const defaults = { waiting: ['awaiting-admission', 'Waiting for admission.'], sent: ['awaiting-server-verdict', 'Sent; waiting for a server verdict.'],
32
33
  failed: ['check-failed', 'A check failed.'], refused: ['admission-refused', 'Admission was refused.'],
@@ -58,12 +59,72 @@ const appMapRefused = (refusals, extra = {}) => {
58
59
  };
59
60
 
60
61
  // Module function: one outcome for one selected test from one server answer.
61
- export function outcomeFor(answer, { test, steps = [], appMaps, kind = answer?.command, timeLimit = false, sourceFiles, capacityUncertain = false } = {}) {
62
+ export function outcomeFor(answer, { test, steps = [], appMaps, kind = answer?.command, timeLimit = false, sourceFiles, capacityUncertain = false, sampleEvidence: evidenceView = 'full' } = {}) {
62
63
  const outcome = answerOutcome(answer, { test, steps, appMaps, kind, timeLimit, sourceFiles, capacityUncertain });
63
64
  if (outcome.state !== 'passed' && !outcome.code) outcome.code = timeLimit ? 'deadline' : resultOutcome(outcome).reason.code;
65
+ if (kind === 'check') Object.assign(outcome, sampleEvidence(answer?.result?.report));
66
+ if (evidenceView === 'flat' && outcome.sample_divergence) {
67
+ const {differences, ...summary} = outcome.sample_divergence;
68
+ outcome.sample_divergence = summary;
69
+ outcome.sample_differences = differences;
70
+ }
64
71
  return kind === 'lint' ? { ...outcome, compatibility: selectedCompatibility(answer, test, sourceFiles) } : outcome;
65
72
  }
66
73
 
74
+ // Compare semantic snapshots, never their sibling execution metadata.
75
+ function sampleEvidence(report) {
76
+ if (!report || typeof report !== 'object') return {};
77
+ const evidence = Object.hasOwn(report, 'field_agreement') ? { field_agreement: report.field_agreement } : {};
78
+ const raw = objects(report.samples), requested = Number.isSafeInteger(report.requested_samples) && report.requested_samples > 0
79
+ ? report.requested_samples : raw.length;
80
+ if (!(requested > 1 || raw.length > 1)) return evidence;
81
+ const targets = ['result', 'error', 'world', 'calls'], ids = new Set(), order = [];
82
+ let complete = raw.length === requested;
83
+ const samples = raw.map((sample, index) => {
84
+ const id = Number.isSafeInteger(sample.sample) && sample.sample > 0 ? sample.sample : index + 1;
85
+ if (ids.has(id) || id > requested) complete = false;
86
+ ids.add(id);
87
+ const steps = new Map();
88
+ for (const step of objects(sample.steps)) {
89
+ if (typeof step.step_id !== 'string' || !step.step_id || steps.has(step.step_id)) { complete = false; continue; }
90
+ steps.set(step.step_id, step);
91
+ if (!order.includes(step.step_id)) order.push(step.step_id);
92
+ if (!targets.every(target => Object.hasOwn(step, target)) || ['queued', 'running', 'not_run'].includes(step.verdict)) complete = false;
93
+ }
94
+ return { id, steps };
95
+ });
96
+ if (!order.length || samples.some(sample => sample.steps.size !== order.length || order.some(id => !sample.steps.has(id)))) complete = false;
97
+ const differences = [], pointer = key => String(key).replace(/~/g, '~0').replace(/\//g, '~1');
98
+ const equal = values => values.every(value => value.present === values[0].present && (!value.present || canonical(value.value) === canonical(values[0].value)));
99
+ const visit = (step_id, target, path, values) => {
100
+ if (values.length < 2 || equal(values)) return;
101
+ // Recurse through matching containers; unlike objects, array indices retain order.
102
+ if (values.every(item => item.present && object(item.value)) || values.every(item => item.present && Array.isArray(item.value))) {
103
+ const keys = [...new Set(values.flatMap(item => Object.keys(item.value)))].sort();
104
+ for (const key of keys) visit(step_id, target, `${path}/${pointer(key)}`, values.map(item => ({ sample: item.sample,
105
+ present: Object.hasOwn(item.value, key), value: Object.hasOwn(item.value, key) ? item.value[key] : null })));
106
+ } else differences.push({ step_id, target, path, values });
107
+ };
108
+ for (const step_id of order) for (const target of targets) {
109
+ const start = differences.length;
110
+ visit(step_id, target, '', samples.filter(sample => sample.steps.has(step_id)).map(sample => {
111
+ const step = sample.steps.get(step_id), present = Object.hasOwn(step, target);
112
+ return { sample: sample.id, present, value: present ? step[target] : null };
113
+ }));
114
+ const sorted = differences.splice(start).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
115
+ differences.push(...sorted);
116
+ }
117
+ let varied = false;
118
+ for (const row of objects(report.field_agreement)) {
119
+ if (row.unavailable_samples > 0 || row.fields_truncated === true || row.fields_truncated > 0 || row.result_samples < row.requested_samples) complete = false;
120
+ for (const field of objects(row.fields)) {
121
+ varied ||= field.status === 'varied';
122
+ if (['incomplete', 'redacted', 'truncated', 'single-sample'].includes(field.status) || field.missing_samples > 0 || field.other_samples > 0) complete = false;
123
+ }
124
+ }
125
+ return { ...evidence, sample_divergence: { advisory: true, divergent: differences.length > 0 || varied, complete, samples: requested, differences } };
126
+ }
127
+
67
128
  function answerOutcome(answer, { test, steps, appMaps, kind, timeLimit, sourceFiles, capacityUncertain }) {
68
129
  const result = answer?.result, report = result?.report;
69
130
  if (timeLimit) return { state: 'unknown', reason: 'The step was stopped at its time limit.' };
@@ -362,6 +423,7 @@ function progressFrom(value) {
362
423
  const progress = {};
363
424
  for (const key of ['steps_done', 'steps_total', 'calls_settled', 'calls_open']) if (count(value?.[key])) progress[key] = value[key];
364
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();
365
427
  return progress;
366
428
  }
367
429
 
@@ -374,7 +436,9 @@ export function outcomeText(outcome) {
374
436
  const p = outcome.progress ?? {};
375
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;
376
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;
377
440
  return [state + (reason ? ` (${reason.code})` : ''), ...(count(outcome.ahead) ? [`${outcome.ahead} ahead`] : []),
441
+ ...(stage ? [stage] : []),
378
442
  ...(step ? [step + (number && typeof p.step === 'string' ? ` (${p.step})` : '')] : []), ...callWords(p.calls_settled, p.calls_open)].join(' · ');
379
443
  }
380
444
 
@@ -1,4 +1,4 @@
1
- // Generated from prompts/cli/runtime-output.prompt.md (sha256: bc2afa9bf8fbaa0dfa531eb6b86900959bb3e1a53d57c35e4734989af74b3ef5).
1
+ // Generated from prompts/cli/runtime-output.prompt.md (sha256: 6e4117a1364be9328834407e8b6dd8feb5dbacee947193f1a32476c4bb894457).
2
2
  import { bindingRefusals } from './runtime-binding-plan.mjs';
3
3
  import { describeCompatibility } from './lint-compatibility-display.mjs';
4
4
  import { failedCheckCount, hasProgress, outcomeFor, outcomeText, progressText, providerText, resultOutcome, PROVIDER_TEXT } from './runtime-outcome.mjs';
@@ -22,6 +22,20 @@ export function progressTicker(stream, now, everyMs = 15_000) {
22
22
  }
23
23
  // The real reason of a tool or server error: its first line, without control characters, secrets or tokens.
24
24
  const TOKENS = /\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,})\b|Bearer\s+\S+/g;
25
+ // Advisory strings are semantic JSON evidence; tabs, CR/LF and spaces remain data.
26
+ function cleanEvidenceString(value, secrets = []) {
27
+ let text = String(value ?? '')
28
+ .replace(/(?:\x1b\]|\x9d)[\s\S]*?(?:\x07|\x1b\\|\x9c|$)/g, '')
29
+ .replace(/(?:\x1b[P^_]|[\x90\x98\x9e\x9f])[\s\S]*?(?:\x1b\\|\x9c|$)/g, '')
30
+ .replace(/(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]/g, '').replace(/\x1b[ -/]*[@-~]/g, '')
31
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, ' ');
32
+ for (const secret of secrets) if (secret) text = text.split(secret).join('[secret]');
33
+ return text.replace(TOKENS, '[secret]');
34
+ }
35
+ const evidenceLabel = (value, secrets) => {
36
+ const text = cleanEvidenceString(value, secrets);
37
+ return /\s/.test(text) ? JSON.stringify(text) : text;
38
+ };
25
39
  export const causeText = (value, secrets = []) => (String(value ?? '').split(/\r?\n/).map(text => cleanField(text, secrets)).find(Boolean) ?? '')
26
40
  .replace(TOKENS, '[secret]').slice(0, 300);
27
41
  const shown = (value, secrets) => cleanField(JSON.stringify(value) ?? 'nothing', secrets);
@@ -146,9 +160,12 @@ function predecessorErrors(refusal, report, steps, secrets) {
146
160
  }
147
161
 
148
162
  // The parts of a server answer that pdd shows.
149
- export function projectAnswer(answer, { origin, secrets = [], steps: authoredSteps = [], criterionTexts = {}, test, sourceFiles, capacityUncertain = false } = {}) {
163
+ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSteps = [], criterionTexts = {}, test, sourceFiles, capacityUncertain = false, sampleEvidence = 'full' } = {}) {
150
164
  const result = answer?.result ?? null, report = result?.report ?? null, time_limit = stepTimeLimit(answer, { steps: authoredSteps, secrets });
151
- const outcome = outcomeFor(answer, { test, steps: authoredSteps, timeLimit: !!time_limit, sourceFiles, capacityUncertain });
165
+ const outcome = outcomeFor(answer, { test, steps: authoredSteps, timeLimit: !!time_limit, sourceFiles, capacityUncertain, sampleEvidence });
166
+ const safeEvidence = value => typeof value === 'string' ? cleanEvidenceString(value, secrets)
167
+ : Array.isArray(value) ? value.map(safeEvidence)
168
+ : isObjectLike(value) ? Object.fromEntries(Object.entries(value).map(([key, item]) => [cleanEvidenceString(key, secrets), safeEvidence(item)])) : value;
152
169
  const safeCompatibility = (value, key = '') => typeof value === 'string'
153
170
  ? /^(?:path|prompt_path|target_path)$/.test(key) && /^(?:\/|[A-Za-z]:[\\/])/.test(value) ? '<server path>' : cleanText(value, secrets).replace(TOKENS, '[secret]')
154
171
  : Array.isArray(value) ? value.map(item => safeCompatibility(item, key))
@@ -191,6 +208,26 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
191
208
  evidence: Array.isArray(check.diagnosis.evidence) ? check.diagnosis.evidence.map(item => cleanText(item, secrets)).filter(Boolean) : undefined,
192
209
  likely: check.diagnosis.likely === true ? true : undefined,
193
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;
194
231
  const ref_target = typeof check?.ref_target === 'string' && check.ref_target ? cleanField(check.ref_target, secrets) : undefined;
195
232
  const ref_path = typeof check?.ref_path === 'string' ? cleanField(check.ref_path, secrets) : undefined;
196
233
  const ref_json_path = typeof check?.ref_json_path === 'string' ? cleanField(check.ref_json_path, secrets) : undefined;
@@ -199,11 +236,44 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
199
236
  step_id: cleanField(step?.step_id ?? check?.step_id, secrets) || (stepIndex !== undefined ? cleanField(authoredSteps[stepIndex]?.step_id, secrets) : '') || null,
200
237
  criterion_text: typeof criterionTexts[criterion_id] === 'string' && criterionTexts[criterion_id].length <= 160 ? cleanField(criterionTexts[criterion_id], secrets) : null,
201
238
  target: cleanField(check?.target, secrets), path: cleanField(check?.path, secrets),
239
+ ...(json_path !== undefined ? { json_path } : {}),
240
+ ...(html !== undefined ? { html } : {}),
202
241
  ...(ref_target !== undefined ? { op: cleanField(check?.op, secrets), ref_target, ...(ref_path !== undefined ? { ref_path } : {}), ...(ref_json_path !== undefined ? { ref_json_path } : {}) } : {}),
203
242
  expected: cleanValues(check?.expected, secrets),
204
243
  actual: cleanValues(check?.actual, secrets), passed: check?.passed === true,
205
244
  normal_result: step ? Object.prototype.hasOwnProperty.call(step, 'result') && !step.error : false, ...(diagnosis ? { diagnosis } : {}) };
206
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
+ : [];
207
277
  const all = sampleSteps.flatMap(({ step, index }) => Array.isArray(step?.checks) ? step.checks.map(check => ({ step, check, index })) : [])
208
278
  .map(({ step, check, index }) => projectCheck(check, step, index));
209
279
  const sampleFailed = all.filter(check => !check.passed).map(({ passed, ...check }) => check);
@@ -257,6 +327,9 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
257
327
  const tokens = tokenUsageOf(answer, { incomplete });
258
328
  return {
259
329
  ...(compatibility ? { compatibility, client_advice } : {}),
330
+ ...(Object.hasOwn(outcome, 'field_agreement') ? { field_agreement: safeEvidence(outcome.field_agreement) } : {}),
331
+ ...(outcome.sample_divergence ? { sample_divergence: safeEvidence(outcome.sample_divergence) } : {}),
332
+ ...(Object.hasOwn(outcome, 'sample_differences') ? { sample_differences: safeEvidence(outcome.sample_differences) } : {}),
260
333
  busy_display: busyRefusal ? { max_wait_seconds: busyRefusal.max_wait_seconds } : null,
261
334
  state: outcome.state, ...(outcome.progress ? { progress: { ...outcome.progress, ...(typeof outcome.progress.step === 'string' ? { step: cleanText(outcome.progress.step, secrets) } : {}) } } : {}),
262
335
  ...(outcome.ahead !== undefined ? { ahead: outcome.ahead } : {}),
@@ -264,6 +337,8 @@ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSte
264
337
  time_limit, checks,
265
338
  criteria: results.length ? { passed: results.filter(item => item?.status === 'passed').length, total: results.length } : null,
266
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 } : {}),
267
342
  calls: !incomplete ? usageCalls : 'unknown',
268
343
  ...tokens,
269
344
  ...(incomplete ? { known_calls: knownCalls } : {}), unknown_calls: unknownCalls, accounting_complete: !incomplete, requested_model: model ? cleanText(model, secrets) : null,
@@ -338,20 +413,27 @@ export function tokenUsageOf(answer, { incomplete = false } = {}) {
338
413
  if (allCurrent && ((tIn !== undefined && tIn !== cIn) || (tCached !== undefined && tCached !== cCached))) return unknownTokens();
339
414
  muIn = cIn;
340
415
  muCached = cCached;
341
- 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)) {
342
419
  muOut = dispatched.reduce((sum, call) => sum + call.output_tokens, 0);
420
+ } else if (tOut !== undefined) {
421
+ muOut = tOut;
343
422
  }
344
423
  } else if (complete === true) {
345
424
  muIn = tIn ?? 0;
346
425
  muCached = tCached ?? 0;
347
- muOut = tOut;
426
+ muOut = tOut ?? 0;
348
427
  }
349
428
  } else if (complete === true) {
350
429
  if (tIn === undefined || tCached === undefined) return unknownTokens();
351
430
  muIn = tIn;
352
431
  muCached = tCached;
353
- muOut = tOut;
432
+ muOut = tOut ?? (tIn === 0 && usage.calls === 0 ? 0 : undefined);
354
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 };
355
437
  }
356
438
  const input_tokens = muIn ?? uIn ?? 'unknown';
357
439
  const cached_input_tokens = muCached ?? uCached ?? 'unknown';
@@ -387,7 +469,7 @@ export function jsonRow(row) {
387
469
  if (typeof input_tokens === 'number' && typeof cached_input_tokens === 'number' && cached_input_tokens > input_tokens) return unknownTokens();
388
470
  return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens) };
389
471
  })();
390
- return { story: row.story, title: row.title, test: row.test, ...(row.native_only?.length ? {native_only:row.native_only} : {}), ...resultOutcome(row), ...(row.unsent ? {unsent:true} : {}), ...(row.not_checked?.length ? {not_checked:row.not_checked} : {}), ...(row.binding_plan ? {binding_plan:row.binding_plan,binding_diagnostics:bindingRefusals(row.binding_plan,row.compatibility)} : {}), ...(row.compatibility ? { compatibility: row.compatibility, client_advice: row.client_advice } : {}), criterion_coverage: criterionCoverage(row), ...(row.progress ? { progress: row.progress } : {}), ...(row.ahead !== undefined && row.ahead !== null ? { ahead: row.ahead } : {}), checks: row.checks ?? null, criteria: row.criteria ?? null,
472
+ return { story: row.story, title: row.title, test: row.test, ...(row.diagnostic_subset === true ? {diagnostic_subset:true,selected_steps:row.selected_steps ?? []} : {}), ...(row.native_only?.length ? {native_only:row.native_only} : {}), ...resultOutcome(row), ...(row.unsent ? {unsent:true} : {}), ...(row.not_checked?.length ? {not_checked:row.not_checked} : {}), ...(row.binding_plan ? {binding_plan:row.binding_plan,binding_diagnostics:bindingRefusals(row.binding_plan,row.compatibility)} : {}), ...(row.compatibility ? { compatibility: row.compatibility, client_advice: row.client_advice } : {}), criterion_coverage: criterionCoverage(row), ...(row.progress ? { progress: row.progress } : {}), ...(row.ahead !== undefined && row.ahead !== null ? { ahead: row.ahead } : {}), checks: row.checks ?? null, criteria: row.criteria ?? null,
391
473
  failed_checks: publicChecks(row.failed_checks), refusals: (row.refusals ?? []).map(item => ({ code: item.code, ...(item.path ? { path: item.path } : {}), field: item.field ?? null, section: item.section ?? null,
392
474
  message: item.message ?? null, engine_message: item.engine_message ?? null, hint: item.hint ?? null, reason: item.reason ?? null, fix: item.fix ?? null,
393
475
  where: item.where ?? null, cause: item.cause ?? null,
@@ -398,6 +480,10 @@ export function jsonRow(row) {
398
480
  request_id: row.request_ids?.at(-1) ?? null, draft: !!row.draft, busy: !!row.busy, can_retry: !!row.can_retry, time_limit: row.time_limit ?? null,
399
481
  why: row.why ?? null, who: row.who ?? null, next_step: row.next_step ?? null,
400
482
  rerun: row.rerun ?? null, ...(typeof row.cache_reason === 'string' ? { cache_reason: row.cache_reason } : {}), ...(row.cached ? { cached: true, passed_at: row.passed_at } : {}),
483
+ ...(Object.hasOwn(row, 'field_agreement') ? { field_agreement: row.field_agreement } : {}),
484
+ ...(row.sample_divergence ? { sample_divergence: row.sample_divergence } : {}),
485
+ ...(Object.hasOwn(row, 'sample_differences') ? { sample_differences: row.sample_differences } : {}),
486
+ ...(row.diagnostic || row.diagnostic_subset ? { diagnostic: true, diagnostic_subset: true, selected_steps: row.selected_steps ?? [] } : {}),
401
487
  ...resultOutcome(row) };
402
488
  }
403
489
 
@@ -411,12 +497,18 @@ function batchTokenUsage(publicRows) {
411
497
  return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens), complete };
412
498
  }
413
499
 
414
- 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 = {}) {
415
501
  rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
416
502
  line = line ?? summaryLine(rows, null, ports);
417
503
  const perStory = new Map(storyLines(rows, ports).map(([story, text]) => [story, text]));
418
- const publicRows = rows.map(row => ({ ...jsonRow(row), summary_line: perStory.get(row.story) ?? null }));
419
- return { batch, repo, ...(coverage ? { coverage } : {}), source_sha256: sourceSha256, exit_code: exitCode, summary_line: line, draft: rows.some(row => row.draft),
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
+ }));
510
+ const diagnostic = rows.filter(row=>row.diagnostic_subset === true);
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),
420
512
  token_usage: batchTokenUsage(publicRows), rows: publicRows, warnings };
421
513
  }
422
514
 
@@ -451,8 +543,10 @@ export function summaryLine(rows, story = null, ports = {}) {
451
543
  const labels = rows.filter(row => row.state !== 'passed').map(row => outcomeText({ ...row, progress: undefined, ahead: undefined }));
452
544
  const others = [...new Set(labels)].map(label => `${labels.filter(value => value === label).length} ${label}`);
453
545
  // A cross for any failed row or failed check; a check without failures that still runs or has no verdict says so (cli 12b).
546
+ const diagnostic = rows.some(row=>row.diagnostic_subset === true);
454
547
  const mark = rows.some(row => row.state === 'failed' || failedCheckCount(row) > 0) ? '✗'
455
- : rows.length && rows.every(row => row.state === 'passed') ? '✓'
548
+ : diagnostic ? 'diagnostic subset, not a full Story pass ·'
549
+ : rows.length && rows.every(row => row.state === 'passed' && !row.diagnostic && !row.diagnostic_subset) ? '✓'
456
550
  : rows.some(row => OPEN_STATES.has(row.state)) ? 'running ·'
457
551
  : rows.some(row => row.busy && ['not_run', 'not run'].includes(row.state)) && rows.every(row => row.state === 'passed' || (row.busy && ['not_run', 'not run'].includes(row.state))) ? 'busy ·' : 'no verdict ·';
458
552
  const rerunShare = rerunCalls ? `${rerunCalls} for reruns` : '';
@@ -460,7 +554,7 @@ export function summaryLine(rows, story = null, ports = {}) {
460
554
  const skipped = rows.some(row => row.cached) ? [count(new Set(rows.filter(row => row.cached).map(row => row.story_path ?? row.story)).size, 'Story').replace('Storys', 'Stories') + ' skipped'] : [];
461
555
  const broken = rows.filter(row=>row.unsent).length, unchecked = rows.reduce((n,row)=>n+(row.not_checked?.length??0),0);
462
556
  return [`${labelText}${story ? ` (${story})` : ''}${rows.some(row => row.draft) ? ' (DRAFT)' : ''}: ${mark} ${criteriaText}`,
463
- `${checks.passed}/${checks.total} checks`, ...(extraFailed > 0 ? [`${extraFailed} failed`] : []), ...(broken ? [`${broken} tests could not run`] : []), ...(unchecked ? [`${unchecked} criteria not checked; the Story is not a full pass`] : []), ...(progress ? [progress] : []), ...others, ...skipped, ...(progress && !sent.length ? [] : [`${usage}${unknownCalls ? ` + ${unknownCalls} unknown` : ''}`])].join(' · ');
557
+ ...(diagnostic ? [`selected steps: ${[...new Set(rows.flatMap(row=>row.selected_steps ?? []))].join(', ')}`, ...(mark.startsWith('diagnostic') ? [] : ['diagnostic subset, not a full Story pass'])] : []), `${checks.passed}/${checks.total} checks`, ...(extraFailed > 0 ? [`${extraFailed} failed`] : []), ...(broken ? [`${broken} tests could not run`] : []), ...(unchecked ? [`${unchecked} criteria not checked; the Story is not a full pass`] : []), ...(progress ? [progress] : []), ...others, ...skipped, ...(progress && !sent.length ? [] : [`${usage}${unknownCalls ? ` + ${unknownCalls} unknown` : ''}`])].join(' · ');
464
558
  }
465
559
 
466
560
  const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -486,9 +580,75 @@ const plainLine = (text, secrets) => secrets.reduce((value, secret) => secret ?
486
580
  const oneLine = value => typeof value !== 'string' || !/\n(?!$)/.test(value);
487
581
  const valueLines = value => typeof value === 'string' ? value.replace(/\n$/, '').split('\n') : (JSON.stringify(value, null, 2) ?? 'nothing').split('\n');
488
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
+
489
647
  // The check line: one line when both values fit, else the check and a block for each value, never cut inside a line.
490
648
  function checkLines(check, secrets) {
491
- 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}` : ''}`;
492
652
  const noError = check.target === 'error' && check.actual && typeof check.actual === 'object' && !Array.isArray(check.actual)
493
653
  && check.actual.missing === true && Object.keys(check.actual).length === 1
494
654
  && (check.normal_result === true || ['no-error', 'needs-tool'].includes(check.diagnosis?.kind));
@@ -603,6 +763,14 @@ export function renderText({ batch, rows, coverage, warnings = [], details = fal
603
763
  const key = check.step_id ?? '', line = rerunByStep.get(key);
604
764
  if (line) { lines.push(line); rerunByStep.delete(key); }
605
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
+ }
606
774
  if (reruns.some(item => item.key === null)) lines.push(reruns.find(item => item.key === null).line);
607
775
  if (fullFailure) lines.push(...(row.warnings ?? []).map(text => ` ${text}`));
608
776
  const diagnosed = failed.some(check => check.diagnosis?.why || check.diagnosis?.next_step);
@@ -643,10 +811,29 @@ export function renderText({ batch, rows, coverage, warnings = [], details = fal
643
811
  out.push(`UNKNOWN ${row.title}: ${providerText(row)}`, ` ${row.provider.code}${row.provider.detail ? ` (${row.provider.detail})` : ''}${row.report_url ? ` Report: ${row.report_url}` : ''}`,
644
812
  ...(row.next_step ? [] : [' To try again, run `pdd test` again (a new request).']), ...serverAdvice(row, secrets));
645
813
  }
646
- if (details) for (const row of rows.filter(row => row.all_checks?.length || !row.cached && formatPromptCacheTokens(row))) {
814
+ for (const row of rows.filter(row => row.sample_divergence)) {
815
+ const evidence = row.sample_divergence;
816
+ if (evidence.divergent) {
817
+ out.push(`Sample divergence (advisory): ${cleanText(row.title, secrets)}`);
818
+ for (const difference of evidence.differences) out.push(` ${evidenceLabel(difference.step_id, secrets)} ${difference.target} ${evidenceLabel(difference.path, secrets) || '""'}`,
819
+ ` ${difference.values.map(item => `Sample ${item.sample}: ${item.present ? shown(item.value, secrets) : 'missing'}`).join('; ')}`);
820
+ for (const agreement of row.field_agreement ?? []) for (const field of agreement.fields ?? []) if (field.status === 'varied') out.push(
821
+ ` ${evidenceLabel(agreement.step_id, secrets)} result ${evidenceLabel(field.path, secrets) || '""'}: ${field.buckets.map(bucket => `${shown(bucket.value, secrets)} (${bucket.count})`).join('; ')}`);
822
+ }
823
+ if (!evidence.complete) out.push('Sample comparison incomplete; agreement is unknown.');
824
+ }
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))) {
647
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
+ : [];
648
833
  out.push(`Checks for ${row.title} (${row.test}):`,
649
834
  ...(tokenText ? [` Tokens: ${tokenText}`] : []),
835
+ ...draftLines,
836
+ ...stepLines,
650
837
  ...[...(row.all_checks ?? [])].sort((a, b) => a.passed - b.passed).flatMap(check => checkLines(check, secrets)
651
838
  .map((text, index) => index ? ` ${text}` : ` ${check.passed ? 'passed' : 'failed'} ${text}`)));
652
839
  }
@@ -665,7 +852,7 @@ export function renderText({ batch, rows, coverage, warnings = [], details = fal
665
852
  }).text.split('\n'));
666
853
  if (coverage) out.push(coverageText(coverage, {busy: rows.some(row => row.busy_display || row.busy) && rows.every(row => row.state === 'passed' || row.busy_display || row.busy)}));
667
854
  const models = [...new Set(rows.map(row => row.requested_model).filter(Boolean))];
668
- out.push(`${rows.filter(row => row.state === 'passed').length} of ${rows.length} stories passed.${models.length ? ` Model asked for: ${models.join(', ')}.` : ''}`);
855
+ out.push(`${rows.filter(row => resultOutcome(row).state === 'passed').length} of ${rows.length} stories passed.${models.length ? ` Model asked for: ${models.join(', ')}.` : ''}`);
669
856
  const activeRows = rows.filter(row => !row.cached);
670
857
  const cacheRows = activeRows.filter(row => formatPromptCacheTokens(row) !== null);
671
858
  if (cacheRows.length) {