@promptdriven/runtime-client 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +152 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +974 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/live-local-bridge.mjs +178 -0
  18. package/src/runtime/live-local.mjs +181 -0
  19. package/src/runtime/product-composition.mjs +384 -0
  20. package/src/runtime/run-program.mjs +797 -0
  21. package/src/runtime/runtime-binding-plan.mjs +145 -0
  22. package/src/runtime/runtime-bindings.mjs +81 -0
  23. package/src/runtime/runtime-check-plan.mjs +411 -0
  24. package/src/runtime/runtime-client.mjs +8114 -0
  25. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  26. package/src/runtime/runtime-markdown.mjs +215 -0
  27. package/src/runtime/runtime-outcome.mjs +468 -0
  28. package/src/runtime/runtime-output.mjs +752 -0
  29. package/src/runtime/runtime-preflight.mjs +3832 -0
  30. package/src/runtime/runtime-slots.mjs +462 -0
  31. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  32. package/src/runtime/runtime-workspace.mjs +52 -0
  33. package/src/runtime/scenario-json.mjs +257 -0
  34. package/src/runtime/secret-redaction.mjs +54 -0
  35. package/src/runtime/try-doors.mjs +597 -0
  36. package/src/runtime/try-http.mjs +285 -0
  37. package/src/runtime/try-mcp.mjs +223 -0
  38. package/src/runtime/try-session.mjs +95 -0
  39. package/src/runtime/try-update-policy.mjs +43 -0
@@ -0,0 +1,752 @@
1
+ // Generated from prompts/cli/runtime-output.prompt.md (sha256: 6e4117a1364be9328834407e8b6dd8feb5dbacee947193f1a32476c4bb894457).
2
+ import { bindingRefusals } from './runtime-binding-plan.mjs';
3
+ import { describeCompatibility } from './lint-compatibility-display.mjs';
4
+ import { failedCheckCount, hasProgress, outcomeFor, outcomeText, progressText, providerText, resultOutcome, PROVIDER_TEXT } from './runtime-outcome.mjs';
5
+ export const OPEN_STATES = new Set(['queued', 'running', 'sent']);
6
+
7
+ const SERVER_PATH = /(?<![\w.:/-])\/(?:home|Users|srv|var|tmp|private|opt|mnt|workspace|usr|etc)\/[^\s"'<>)\]]*/g;
8
+ // Server text in the terminal: no control characters, no token and, in free text, no server paths.
9
+ export function cleanText(value, secrets = [], { paths = true } = {}) {
10
+ let text = String(value ?? '').replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x1f\x7f-\x9f]/g, ' ');
11
+ for (const secret of secrets) if (secret) text = text.split(secret).join('[secret]');
12
+ return (paths ? text.replace(SERVER_PATH, '<server path>') : text).trim();
13
+ }
14
+ const cleanField = (value, secrets) => cleanText(value, secrets, { paths: false });
15
+
16
+ // Progress for slow steps: plain lines on stderr, the same for a person and an agent; stdout keeps the result.
17
+ export const sinceText = ms => ms < 60_000 ? `${Math.floor(ms / 1000)} s` : `${Math.floor(ms / 60_000)} min`;
18
+ export function progressTicker(stream, now, everyMs = 15_000) {
19
+ const start = now();
20
+ let shown = start;
21
+ return text => { if (now() - shown < everyMs) return; shown = now(); stream.write(`${text} · ${sinceText(shown - start)}\n`); };
22
+ }
23
+ // The real reason of a tool or server error: its first line, without control characters, secrets or tokens.
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
+ };
39
+ export const causeText = (value, secrets = []) => (String(value ?? '').split(/\r?\n/).map(text => cleanField(text, secrets)).find(Boolean) ?? '')
40
+ .replace(TOKENS, '[secret]').slice(0, 300);
41
+ const shown = (value, secrets) => cleanField(JSON.stringify(value) ?? 'nothing', secrets);
42
+
43
+ // A secret browser link from the runtime: same scheme and host as the origin, the expected path, no user or password.
44
+ export function validLink(value, origin, kind) {
45
+ if (typeof value !== 'string') return null;
46
+ try {
47
+ const url = new URL(value), base = new URL(origin);
48
+ const path = kind === 'try' ? /^\/s\/[A-Za-z0-9_-]+\/$/ : /^\/r\/[A-Za-z0-9_.-]+$/;
49
+ return url.protocol === base.protocol && url.host === base.host && !url.username && !url.password
50
+ && !url.search && !url.hash && path.test(url.pathname) ? url.href : null;
51
+ } catch { return null; }
52
+ }
53
+
54
+ const scrub = (value, secrets) => typeof value === 'string' ? secrets.reduce((text, secret) => secret ? text.split(secret).join('[secret]') : text, value)
55
+ : Array.isArray(value) ? value.map(item => scrub(item, secrets))
56
+ : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrub(item, secrets)])) : value;
57
+
58
+ // A server step deadline is execution evidence, separate from a polling deadline or a queue wait.
59
+ export function stepTimeLimit(answer, { steps = [], secrets = [] } = {}) {
60
+ const report = answer?.result?.report, candidates = [];
61
+ const add = (refusal, index, step) => { if (refusal && typeof refusal === 'object') candidates.push({ refusal, index, step }); };
62
+ const refusals = Array.isArray(answer?.result?.refusals) ? answer.result.refusals : [];
63
+ for (const refusal of refusals) add(refusal);
64
+ add(report?.refusal);
65
+ for (const sample of Array.isArray(report?.samples) ? report.samples : []) {
66
+ add(sample?.refusal);
67
+ for (const [index, step] of (Array.isArray(sample?.steps) ? sample.steps : []).entries()) add(step?.refusal, index, step?.step_id);
68
+ }
69
+ for (const { refusal, index, step } of candidates) {
70
+ const cause = refusal.failure_cause ?? {}, details = refusal.details ?? {};
71
+ const text = [cause.detail, refusal.engine_message, refusal.message].filter(value => typeof value === 'string').join(' ');
72
+ const typed = cause.kind === 'step_timeout';
73
+ if (!typed && !(refusal.code === 'graph-provider-failure' && (cause.kind === 'timeout' || /\b(?:timeout|timed[ -]out|time[ -]limit|deadline[ -]exceeded)\b/i.test(text)))) continue;
74
+ const explicit = [refusal.timeout_seconds, refusal.limit_seconds, details.timeout_seconds, details.limit_seconds, cause.timeout_seconds]
75
+ .find(value => typeof value === 'number' && Number.isFinite(value) && value > 0 && value <= 86400);
76
+ const duration = /(?:after|timeout[=:]?|limit(?: of)?)\s*(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m)\b/i.exec(text);
77
+ const parsed = duration ? Number(duration[1]) * (/^m/i.test(duration[2]) ? 60 : 1) : null;
78
+ const seconds = explicit ?? (parsed > 0 && parsed <= 86400 ? parsed : typed ? 600 : 180);
79
+ const companions = refusals.filter(item => item?.code === refusal.code);
80
+ const section = refusal.section ?? refusal.at ?? (companions.length === 1 ? companions[0].section ?? companions[0].at : '');
81
+ const at = index ?? refusal.step_index ?? Number(/(?:^|\.)steps\[(\d+)\]/.exec(section)?.[1] ?? -1);
82
+ const name = [refusal.step_id, details.step_id, refusal.step_name, step, Number.isInteger(at) && steps[at]?.step_id]
83
+ .find(value => typeof value === 'string' && value.trim());
84
+ const label = cleanText(name || 'unnamed step', secrets).slice(0, 200), minutes = Number((seconds / 60).toFixed(3));
85
+ return { code: cleanText(refusal.code || 'step_timeout', secrets), step: label, minutes,
86
+ message: `Step ${label} took more than ${minutes} minutes and was stopped.`,
87
+ fix: 'Make the step smaller, for example split 30 moves into 3 steps of 10.' };
88
+ }
89
+ return null;
90
+ }
91
+
92
+ // One server refusal as pdd shows it, cleaned; each field is null when missing.
93
+ export const refusalView = (item, secrets = []) => ({
94
+ code: cleanText(item?.code, secrets) || 'unknown', path: cleanText(item?.file ?? item?.path, secrets) || null,
95
+ field: cleanText(item?.field ?? item?.at ?? item?.section, secrets) || null, section: cleanText(item?.section, secrets) || null,
96
+ message: cleanText(item?.message, secrets) || null, engine_message: cleanText(item?.engine_message, secrets) || null, hint: null,
97
+ reason: cleanText(item?.reason, secrets) || null, fix: cleanText(item?.fix, secrets) || null,
98
+ where: cleanText(item?.where, secrets) || [item?.file, item?.at].map(part => cleanText(part, secrets)).filter(Boolean).join(' ') || null,
99
+ cause: cleanText(item?.cause, secrets) || null });
100
+
101
+ // Attribute only direct authored references backed by this sample's raw error.
102
+ function predecessorErrors(refusal, report, steps, secrets) {
103
+ if (typeof refusal?.section !== 'string') return [];
104
+ const anchor = /^samples\[(\d+)\]\.steps\[(\d+)\]$/.exec(refusal?.section);
105
+ if (!anchor || !Array.isArray(steps) || !Array.isArray(report?.samples)) return [];
106
+ const sampleIndex = Number(anchor[1]), index = Number(anchor[2]);
107
+ if (!Number.isSafeInteger(sampleIndex) || !Number.isSafeInteger(index)) return [];
108
+ const reported = report.samples[sampleIndex]?.steps, dependent = steps[index];
109
+ if (!Array.isArray(reported) || !isObjectLike(dependent) || !Object.hasOwn(dependent, 'input')) return [];
110
+ // A relative location can corroborate this anchor, but cannot select a sample.
111
+ for (const location of [refusal.at, refusal.field, refusal.where]) {
112
+ if (location == null) continue;
113
+ if (typeof location !== 'string') return [];
114
+ let conflict = false;
115
+ const remainder = location.replace(/(?:samples\[(\d+)\]\.)?steps\[(\d+)\]/g, (text, sample, step) => {
116
+ if (Number(step) !== index || sample !== undefined && Number(sample) !== sampleIndex) conflict = true;
117
+ return '';
118
+ });
119
+ if (conflict || /\b(?:samples|steps)\[/.test(remainder)) return [];
120
+ }
121
+ const safe = (value, pointers = false) => {
122
+ let text = String(value ?? '').replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x1f\x7f-\x9f]/g, '');
123
+ for (const secret of secrets) if (secret) text = text.split(secret).join('[secret]');
124
+ text = text.replace(TOKENS, '[secret]');
125
+ // Pointer spaces name members. Host paths in identities/codes need no word delimiter.
126
+ return pointers ? text : text.replace(/\/(?:home|Users|srv|var|tmp|private|opt|mnt|workspace|usr|etc)\/[^\s"'<>)\]]*/g, '<server path>').trim();
127
+ };
128
+ const identity = value => typeof value === 'string' && value.trim() && safe(value)
129
+ && !/^(?:\[(?:secret|redacted)\]|<(?:secret|redacted|server path)>|redacted|\*+)$/i.test(safe(value));
130
+ const id = dependent.step_id;
131
+ if (!identity(id) || steps.filter(step => step?.step_id === id).length !== 1) return [];
132
+ if (reported[index] !== undefined && reported[index]?.step_id !== id) return [];
133
+ if (reported.some((step, at) => step?.step_id === id && at !== index)) return [];
134
+ const facts = [];
135
+ const pending = [{ value: dependent.input, path: '' }];
136
+ while (pending.length) {
137
+ const { value, path } = pending.pop();
138
+ if (!value || typeof value !== 'object') continue;
139
+ const ref = value.$step_result;
140
+ if (isObjectLike(value) && Object.keys(value).length === 1 && isObjectLike(ref)
141
+ && Object.keys(ref).length === 2 && Object.hasOwn(ref, 'step_id') && Object.hasOwn(ref, 'path')
142
+ && typeof ref.path === 'string' && identity(ref.step_id)) {
143
+ const authored = steps.map((step, at) => ({ step, at })).filter(({ step }) => step?.step_id === ref.step_id);
144
+ const matches = reported.filter(step => step?.step_id === ref.step_id);
145
+ if (authored.length !== 1 || authored[0].at >= index || matches.length !== 1) continue;
146
+ const predecessor = matches[0];
147
+ if (predecessor.result != null || !identity(predecessor.error?.code)) continue;
148
+ facts.push({ step_id: safe(id), input_path: safe(path, true), predecessor_step_id: safe(ref.step_id),
149
+ result_path: safe(ref.path, true), error_code: safe(predecessor.error.code) });
150
+ continue;
151
+ }
152
+ const children = Object.entries(value);
153
+ // Reverse stack insertion keeps authored object/array traversal order.
154
+ for (let at = children.length - 1; at >= 0; at--) {
155
+ const [key, item] = children[at];
156
+ pending.push({ value: item, path: `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}` });
157
+ }
158
+ }
159
+ return facts;
160
+ }
161
+
162
+ // The parts of a server answer that pdd shows.
163
+ export function projectAnswer(answer, { origin, secrets = [], steps: authoredSteps = [], criterionTexts = {}, test, sourceFiles, capacityUncertain = false, sampleEvidence = 'full' } = {}) {
164
+ const result = answer?.result ?? null, report = result?.report ?? null, time_limit = stepTimeLimit(answer, { steps: authoredSteps, secrets });
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;
169
+ const safeCompatibility = (value, key = '') => typeof value === 'string'
170
+ ? /^(?:path|prompt_path|target_path)$/.test(key) && /^(?:\/|[A-Za-z]:[\\/])/.test(value) ? '<server path>' : cleanText(value, secrets).replace(TOKENS, '[secret]')
171
+ : Array.isArray(value) ? value.map(item => safeCompatibility(item, key))
172
+ : isObjectLike(value) ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, safeCompatibility(item, key)])) : value;
173
+ const advice = reason => {
174
+ if (reason === 'binding-missing') return { owner: 'application/binding author', next_step: 'Run pdd test --explain-bindings STORY. Fix the fixture resource/operation name, add the named binding, or declare the Story Runtime boundary. If the exact fixture is selected, ask the compatibility owner to diagnose the refusal before retrying.' };
175
+ if (['source-mismatch', 'source-admission-refused'].includes(reason)) return { owner: 'source/prompt author', next_step: 'Repair the reported source/admission problem.' };
176
+ if (['retained-attachment-unsupported', 'retained-mutation-unsupported', 'runtime-mode-unsupported'].includes(reason))
177
+ return { owner: 'interpreter owner', next_step: 'Review the unsupported capability or mode.' };
178
+ if (reason === 'engine-build-unknown') return { owner: 'interpreter deployment owner', next_step: 'Identify the executing build.' };
179
+ if (reason === 'supported') return { owner: 'application author', next_step: 'Behavioral execution remains required. Installed-engine, host/profile and physical-observation proof remains unproved.' };
180
+ return { owner: 'unresolved', next_step: reason === 'capability-association-mismatch'
181
+ ? 'Review captured source and interpreter deployment identity.' : 'Review the source and interpreter evidence.' };
182
+ };
183
+ const compatibility = outcome.compatibility ? safeCompatibility(outcome.compatibility) : null;
184
+ if (compatibility?.reported) for (const row of [...(compatibility.reported.operations ?? []), ...(compatibility.reported.edges ?? [])])
185
+ row.client_advice = advice(row.reason_code);
186
+ const client_advice = compatibility ? advice(compatibility.issue ?? (compatibility.state === 'supported' ? 'supported'
187
+ : [...(compatibility.reported?.operations ?? []), ...(compatibility.reported?.edges ?? [])].find(row => row.verdict === compatibility.state)?.reason_code)) : null;
188
+ const sampleSteps = (Array.isArray(report?.samples) ? report.samples : [])
189
+ .flatMap(sample => (Array.isArray(sample?.steps) ? sample.steps : []).map((step, index) => ({ step, index })));
190
+ const nonNegativeInt = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
191
+ const rerunStep = item => ({
192
+ step_id: cleanField(item.step_id, secrets) || null,
193
+ ...(nonNegativeInt(item.runs) !== undefined ? { runs: nonNegativeInt(item.runs) } : {}),
194
+ ...(nonNegativeInt(item.failed) !== undefined ? { failed: nonNegativeInt(item.failed) } : {}),
195
+ ...(item.stable === true ? { stable: true } : {}),
196
+ ...(Array.isArray(item.changed_paths) ? { changed_paths: item.changed_paths.map(path => cleanField(path, secrets)) } : {}) });
197
+ const rerun = isObjectLike(report?.rerun) ? {
198
+ ...(nonNegativeInt(report.rerun.calls) !== undefined ? { calls: nonNegativeInt(report.rerun.calls) } : {}),
199
+ ...(typeof report.rerun.skipped === 'string' ? { skipped: cleanField(report.rerun.skipped, secrets) } : {}),
200
+ ...(Array.isArray(report.rerun.steps) ? { steps: report.rerun.steps.filter(isObjectLike).map(rerunStep) } : {}) } : null;
201
+ const scrubTokens = value => typeof value === 'string' ? scrub(value, secrets).replace(TOKENS, '[secret]')
202
+ : Array.isArray(value) ? value.map(scrubTokens)
203
+ : isObjectLike(value) ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrubTokens(item)])) : value;
204
+ const projectCheck = (check, step = null, index = undefined, cleanValues = scrub) => {
205
+ const criterion_id = cleanField(check?.criterion_id, secrets), diagnosis = isObjectLike(check?.diagnosis) ? {
206
+ kind: cleanText(check.diagnosis.kind, secrets) || null, who: cleanText(check.diagnosis.who, secrets) || null,
207
+ why: cleanText(check.diagnosis.why, secrets) || null, next_step: cleanText(check.diagnosis.next_step, secrets) || null,
208
+ evidence: Array.isArray(check.diagnosis.evidence) ? check.diagnosis.evidence.map(item => cleanText(item, secrets)).filter(Boolean) : undefined,
209
+ likely: check.diagnosis.likely === true ? true : undefined,
210
+ ...(isObjectLike(check.diagnosis.rerun) ? { rerun: rerunStep(check.diagnosis.rerun) } : {}) } : null;
211
+ const ref_target = typeof check?.ref_target === 'string' && check.ref_target ? cleanField(check.ref_target, secrets) : undefined;
212
+ const ref_path = typeof check?.ref_path === 'string' ? cleanField(check.ref_path, secrets) : undefined;
213
+ const ref_json_path = typeof check?.ref_json_path === 'string' ? cleanField(check.ref_json_path, secrets) : undefined;
214
+ const stepIndex = Number.isInteger(index) && index >= 0 ? index : Number.isInteger(check?.step_number) && check.step_number >= 1 ? check.step_number - 1 : undefined;
215
+ return { criterion_id,
216
+ step_id: cleanField(step?.step_id ?? check?.step_id, secrets) || (stepIndex !== undefined ? cleanField(authoredSteps[stepIndex]?.step_id, secrets) : '') || null,
217
+ criterion_text: typeof criterionTexts[criterion_id] === 'string' && criterionTexts[criterion_id].length <= 160 ? cleanField(criterionTexts[criterion_id], secrets) : null,
218
+ target: cleanField(check?.target, secrets), path: cleanField(check?.path, secrets),
219
+ ...(ref_target !== undefined ? { op: cleanField(check?.op, secrets), ref_target, ...(ref_path !== undefined ? { ref_path } : {}), ...(ref_json_path !== undefined ? { ref_json_path } : {}) } : {}),
220
+ expected: cleanValues(check?.expected, secrets),
221
+ actual: cleanValues(check?.actual, secrets), passed: check?.passed === true,
222
+ normal_result: step ? Object.prototype.hasOwnProperty.call(step, 'result') && !step.error : false, ...(diagnosis ? { diagnosis } : {}) };
223
+ };
224
+ const all = sampleSteps.flatMap(({ step, index }) => Array.isArray(step?.checks) ? step.checks.map(check => ({ step, check, index })) : [])
225
+ .map(({ step, check, index }) => projectCheck(check, step, index));
226
+ const sampleFailed = all.filter(check => !check.passed).map(({ passed, ...check }) => check);
227
+ const failed_checks = sampleFailed.length ? sampleFailed
228
+ : Array.isArray(result?.failed_checks) ? result.failed_checks.filter(isObjectLike).map(check => {
229
+ const { passed, ...item } = projectCheck(check, null, undefined, scrubTokens);
230
+ return item;
231
+ }) : [];
232
+ const checks = all.length ? { passed: all.filter(check => check.passed).length, total: all.length }
233
+ : nonNegativeInt(result?.checks?.passed) !== undefined && nonNegativeInt(result?.checks?.total) !== undefined && result.checks.total >= result.checks.passed
234
+ ? { passed: result.checks.passed, total: result.checks.total }
235
+ : failed_checks.length ? { passed: 0, total: failed_checks.length } : null;
236
+ // Server refusal items may include reason, fix, file, at, where and cause; older responses may omit them.
237
+ const refusals = (Array.isArray(result?.refusals) ? result.refusals : []).map(item => {
238
+ const view = refusalView(item, secrets);
239
+ const facts = answer?.command === 'check' && ['passed', 'failed', 'refused'].includes(answer?.state)
240
+ ? predecessorErrors(item, report, authoredSteps, secrets) : [];
241
+ return { ...view, ...(facts.length ? { dependency_errors: facts } : {}) };
242
+ });
243
+ const usage = answer?.usage ?? {};
244
+ const accountingSurfaces = [answer, usage, result, report].filter(isObjectLike);
245
+ const accountingValues = key => accountingSurfaces.filter(surface => Object.hasOwn(surface, key)).map(surface => nonNegativeInt(surface[key]));
246
+ const accountingKeys = ['calls', 'known_calls', 'unknown_calls', 'provider_calls'];
247
+ const invalidCounter = accountingKeys.some(key => accountingValues(key).some(value => value === undefined));
248
+ const conflictingCounters = accountingKeys.some(key => new Set(accountingValues(key).filter(value => value !== undefined)).size > 1);
249
+ const flags = [[answer, 'accounting_complete'], [usage, 'accounting_complete'], [result, 'accounting_complete'], [report, 'accounting_complete']]
250
+ .filter(([source, key]) => source && Object.hasOwn(source, key)).map(([source, key]) => source[key]);
251
+ const invalidFlag = flags.some(value => typeof value !== 'boolean'), conflictingFlags = new Set(flags.filter(value => typeof value === 'boolean')).size > 1;
252
+ const usageCalls = nonNegativeInt(usage.calls);
253
+ const knownValues = accountingValues('known_calls').filter(value => value !== undefined);
254
+ const callValues = accountingValues('calls').filter(value => value !== undefined);
255
+ const providerValues = accountingValues('provider_calls').filter(value => value !== undefined);
256
+ const providerCalls = providerValues.length ? Math.max(...providerValues) : undefined;
257
+ const unknownValues = accountingValues('unknown_calls').filter(value => value !== undefined);
258
+ const reportedUnknown = Math.max(...unknownValues, 0);
259
+ const deductedTotals = [...callValues, ...providerValues].map(value => Math.max(0, value - reportedUnknown));
260
+ const knownCalls = knownValues.length ? Math.max(...knownValues, 0) : Math.max(...deductedTotals, 0);
261
+ const incomplete = capacityUncertain || invalidCounter || conflictingCounters || invalidFlag || conflictingFlags || flags.includes(false)
262
+ || reportedUnknown > 0 || usageCalls === undefined || knownCalls > usageCalls
263
+ || (providerCalls !== undefined && providerCalls > usageCalls);
264
+ const unknownCalls = incomplete ? Math.max(1, reportedUnknown) : 0;
265
+ const model = [usage.requested_model, report?.evaluation?.requested_model].find(value => typeof value === 'string' && value && value !== 'unknown');
266
+ const results = Array.isArray(report?.criterion_results) ? report.criterion_results : [];
267
+ const cause = Array.isArray(report?.samples) ? report.samples.map(sample => sample?.refusal?.failure_cause).find(isObjectLike) : null;
268
+ const provider = answer?.state === 'unknown' && (refusals.some(item => item.code === 'graph-provider-failure') || cause?.kind === 'transport_unknown')
269
+ ? { code: refusals.find(item => item.code === 'graph-provider-failure')?.code ?? 'graph-provider-failure',
270
+ detail: [cause?.kind, cause?.detail].filter(Boolean).map(text => cleanText(text, secrets)).join(', ') || null } : null;
271
+ const rawRefusals = Array.isArray(result?.refusals) && result.refusals.length ? result.refusals : [report?.refusal];
272
+ const busyRefusal = outcome.state === 'not_run' && outcome.retryable === true && answer?.command === 'check'
273
+ ? rawRefusals.find(item => item?.retryable === true || item?.details?.retryable === true) : null;
274
+ const tokens = tokenUsageOf(answer, { incomplete });
275
+ return {
276
+ ...(compatibility ? { compatibility, client_advice } : {}),
277
+ ...(Object.hasOwn(outcome, 'field_agreement') ? { field_agreement: safeEvidence(outcome.field_agreement) } : {}),
278
+ ...(outcome.sample_divergence ? { sample_divergence: safeEvidence(outcome.sample_divergence) } : {}),
279
+ ...(Object.hasOwn(outcome, 'sample_differences') ? { sample_differences: safeEvidence(outcome.sample_differences) } : {}),
280
+ busy_display: busyRefusal ? { max_wait_seconds: busyRefusal.max_wait_seconds } : null,
281
+ state: outcome.state, ...(outcome.progress ? { progress: { ...outcome.progress, ...(typeof outcome.progress.step === 'string' ? { step: cleanText(outcome.progress.step, secrets) } : {}) } } : {}),
282
+ ...(outcome.ahead !== undefined ? { ahead: outcome.ahead } : {}),
283
+ note: outcome.state === 'not_run' ? { code: cleanText(outcome.code, secrets) || null, message: cleanText(outcome.message, secrets) || null } : null,
284
+ time_limit, checks,
285
+ criteria: results.length ? { passed: results.filter(item => item?.status === 'passed').length, total: results.length } : null,
286
+ all_checks: all, failed_checks, refusals,
287
+ calls: !incomplete ? usageCalls : 'unknown',
288
+ ...tokens,
289
+ ...(incomplete ? { known_calls: knownCalls } : {}), unknown_calls: unknownCalls, accounting_complete: !incomplete, requested_model: model ? cleanText(model, secrets) : null,
290
+ server_seconds: typeof usage.seconds === 'number' ? usage.seconds : null,
291
+ report_url: validLink(answer?.report_url, origin, 'report'), why: result?.why ? cleanText(result.why, secrets) : null,
292
+ who: result?.who ? cleanText(result.who, secrets) : null, next_step: result?.next_step ? cleanText(result.next_step, secrets) : null,
293
+ rerun,
294
+ engine_sha: typeof answer?.engine_sha === 'string' ? answer.engine_sha : null, provider: time_limit ? null : provider,
295
+ // The server's list of draft prompts wins over local detection; null when the server sends none.
296
+ draft: Array.isArray(answer?.draft_prompts) ? answer.draft_prompts.length > 0 : null };
297
+ }
298
+
299
+ const isObjectLike = value => value !== null && typeof value === 'object' && !Array.isArray(value);
300
+ export { PROVIDER_TEXT } from './runtime-outcome.mjs';
301
+ const round = seconds => typeof seconds === 'number' ? Math.round(seconds * 10) / 10 : null;
302
+ const sentRow = row => row.phase === 'server' || !!row.request_id || row.state === 'sent';
303
+ const tokenInt = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
304
+ const absentToken = value => value === undefined || value === null || value === 'unknown';
305
+ const malformedToken = value => !absentToken(value) && tokenInt(value) === undefined;
306
+ const shareOf = (input, cached) => typeof input === 'number' && typeof cached === 'number' && input > 0 && cached <= input ? cached / input : null;
307
+ const unknownTokens = () => ({ input_tokens: 'unknown', cached_input_tokens: 'unknown', output_tokens: 'unknown', cached_input_share: null });
308
+ const formatPromptCacheTokens = usage => {
309
+ if (typeof usage?.input_tokens !== 'number' || typeof usage?.cached_input_tokens !== 'number' || usage.cached_input_tokens > usage.input_tokens) return null;
310
+ const share = shareOf(usage.input_tokens, usage.cached_input_tokens);
311
+ const pct = share !== null ? `, ${(share * 100).toFixed(1)}%` : '';
312
+ const out = typeof usage.output_tokens === 'number' ? ` · ${usage.output_tokens} output` : '';
313
+ return `${usage.input_tokens} input (${usage.cached_input_tokens} cached${pct})${out}`;
314
+ };
315
+
316
+ export function tokenUsageOf(answer, { incomplete = false } = {}) {
317
+ const usage = isObjectLike(answer?.usage) ? answer.usage : {};
318
+ const result = isObjectLike(answer?.result) ? answer.result : {};
319
+ const report = isObjectLike(result.report) ? result.report : null;
320
+ const topReport = isObjectLike(answer?.report) ? answer.report : null;
321
+ const surfaces = [answer, usage, result, report, topReport].filter(isObjectLike);
322
+ if (incomplete || surfaces.some(s => Object.hasOwn(s, 'accounting_complete') && s.accounting_complete !== true)) return unknownTokens();
323
+ if (surfaces.some(s => ['not_started', 'pre-dispatch'].includes(s.dispatch) || s.dispatch_state === 'pre-dispatch')) return unknownTokens();
324
+ if (['input_tokens', 'cached_input_tokens', 'output_tokens'].some(key => malformedToken(usage[key]))) return unknownTokens();
325
+ const uIn = tokenInt(usage.input_tokens), uCached = tokenInt(usage.cached_input_tokens), uOut = tokenInt(usage.output_tokens);
326
+ if (uIn !== undefined && uCached !== undefined && uCached > uIn) return unknownTokens();
327
+ const modelUsage = report?.model_usage ?? topReport?.model_usage;
328
+ let muIn, muCached, muOut;
329
+ if (modelUsage !== undefined && modelUsage !== null) {
330
+ if (!isObjectLike(modelUsage)) return unknownTokens();
331
+ const totals = isObjectLike(modelUsage.totals) ? modelUsage.totals : null;
332
+ const complete = totals && Object.hasOwn(totals, 'complete') ? totals.complete : Object.hasOwn(modelUsage, 'complete') ? modelUsage.complete : undefined;
333
+ const cov = isObjectLike(modelUsage.coverage) ? modelUsage.coverage : null;
334
+ if (complete === false || (complete !== undefined && typeof complete !== 'boolean')
335
+ || cov?.accounting_incomplete === true
336
+ || (Number.isSafeInteger(cov?.unobserved_current_calls) && cov.unobserved_current_calls > 0)) return unknownTokens();
337
+ if (totals) {
338
+ if (['input_tokens', 'cached_input_tokens', 'output_tokens'].some(key => malformedToken(totals[key]))) return unknownTokens();
339
+ const shareRaw = totals.cached_input_share;
340
+ if (shareRaw !== undefined && shareRaw !== null && !(typeof shareRaw === 'number' && Number.isFinite(shareRaw) && shareRaw >= 0 && shareRaw <= 1)) return unknownTokens();
341
+ }
342
+ const tIn = totals ? tokenInt(totals.input_tokens) : tokenInt(modelUsage.input_tokens);
343
+ const tCached = totals ? tokenInt(totals.cached_input_tokens) : tokenInt(modelUsage.cached_input_tokens);
344
+ const tOut = totals ? tokenInt(totals.output_tokens) : tokenInt(modelUsage.output_tokens);
345
+ if (tIn !== undefined && tCached !== undefined && tCached > tIn) return unknownTokens();
346
+ if (Array.isArray(modelUsage.calls)) {
347
+ if (modelUsage.calls.some(call => !isObjectLike(call))) return unknownTokens();
348
+ const current = modelUsage.calls.filter(call => (call.origin ?? 'current') === 'current');
349
+ const dispatched = current.filter(call => call.dispatch_state !== 'pre-dispatch');
350
+ if (current.length > 0 && dispatched.length === 0) return unknownTokens();
351
+ if (dispatched.some(call => call.dispatch_state === 'transport-uncertain' || call.usage_status === 'unknown'
352
+ || tokenInt(call.input_tokens) === undefined || tokenInt(call.cached_input_tokens) === undefined
353
+ || call.cached_input_tokens > call.input_tokens || malformedToken(call.output_tokens))) return unknownTokens();
354
+ if (modelUsage.calls.length > 0) {
355
+ const cIn = dispatched.reduce((sum, call) => sum + call.input_tokens, 0);
356
+ const cCached = dispatched.reduce((sum, call) => sum + call.cached_input_tokens, 0);
357
+ const allCurrent = modelUsage.calls.every(call => (call.origin ?? 'current') === 'current');
358
+ if (allCurrent && ((tIn !== undefined && tIn !== cIn) || (tCached !== undefined && tCached !== cCached))) return unknownTokens();
359
+ muIn = cIn;
360
+ muCached = cCached;
361
+ if (dispatched.length > 0 && dispatched.every(call => tokenInt(call.output_tokens) !== undefined)) {
362
+ muOut = dispatched.reduce((sum, call) => sum + call.output_tokens, 0);
363
+ }
364
+ } else if (complete === true) {
365
+ muIn = tIn ?? 0;
366
+ muCached = tCached ?? 0;
367
+ muOut = tOut;
368
+ }
369
+ } else if (complete === true) {
370
+ if (tIn === undefined || tCached === undefined) return unknownTokens();
371
+ muIn = tIn;
372
+ muCached = tCached;
373
+ muOut = tOut;
374
+ } else return unknownTokens();
375
+ }
376
+ const input_tokens = muIn ?? uIn ?? 'unknown';
377
+ const cached_input_tokens = muCached ?? uCached ?? 'unknown';
378
+ const output_tokens = muOut ?? uOut ?? 'unknown';
379
+ if (typeof input_tokens === 'number' && typeof cached_input_tokens === 'number' && cached_input_tokens > input_tokens) return unknownTokens();
380
+ return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens) };
381
+ }
382
+
383
+ function criterionCoverage(row) {
384
+ if (!Array.isArray(row.steps)) return null;
385
+ const counts = new Map(Object.keys(row.criterion_texts ?? {}).map(id => [id, []]));
386
+ for (const step of row.steps) {
387
+ if (!isObjectLike(step) || !Array.isArray(step.checks)) return null;
388
+ for (const check of step.checks) {
389
+ if (!isObjectLike(check) || typeof check.criterion_id !== 'string' || !check.criterion_id.trim()
390
+ || typeof check.target !== 'string' || typeof check.path !== 'string') return null;
391
+ if (!counts.has(check.criterion_id)) counts.set(check.criterion_id, []);
392
+ counts.get(check.criterion_id).push(check);
393
+ }
394
+ }
395
+ return [...counts].map(([criterion_id, checks]) => ({ criterion_id, check_count: checks.length,
396
+ exit_code_only: checks.length > 0 && checks.every(check => check.target === 'result' && ['/exit_code', '/exitCode'].includes(check.path)) }));
397
+ }
398
+
399
+ export function jsonRow(row) {
400
+ const publicChecks = checks => (checks ?? []).map(({ normal_result, ...check }) => check);
401
+ const rowTokens = row.cached
402
+ ? { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, cached_input_share: null }
403
+ : (() => {
404
+ const input_tokens = tokenInt(row.input_tokens) ?? 'unknown';
405
+ const cached_input_tokens = tokenInt(row.cached_input_tokens) ?? 'unknown';
406
+ const output_tokens = tokenInt(row.output_tokens) ?? 'unknown';
407
+ if (typeof input_tokens === 'number' && typeof cached_input_tokens === 'number' && cached_input_tokens > input_tokens) return unknownTokens();
408
+ return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens) };
409
+ })();
410
+ 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,
411
+ 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,
412
+ message: item.message ?? null, engine_message: item.engine_message ?? null, hint: item.hint ?? null, reason: item.reason ?? null, fix: item.fix ?? null,
413
+ where: item.where ?? null, cause: item.cause ?? null,
414
+ ...(item.dependency_errors?.length ? { dependency_errors: item.dependency_errors } : {}) })), calls: sentRow(row) ? row.calls ?? 'unknown' : 0,
415
+ ...rowTokens,
416
+ seconds: round(row.seconds), requested_model: row.requested_model ?? null, report_url: row.report_url ?? null,
417
+ ...(row.accounting_complete !== undefined ? { known_calls: row.known_calls ?? null, unknown_calls: row.unknown_calls ?? 0, accounting_complete: row.accounting_complete } : {}),
418
+ 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,
419
+ why: row.why ?? null, who: row.who ?? null, next_step: row.next_step ?? null,
420
+ rerun: row.rerun ?? null, ...(typeof row.cache_reason === 'string' ? { cache_reason: row.cache_reason } : {}), ...(row.cached ? { cached: true, passed_at: row.passed_at } : {}),
421
+ ...(Object.hasOwn(row, 'field_agreement') ? { field_agreement: row.field_agreement } : {}),
422
+ ...(row.sample_divergence ? { sample_divergence: row.sample_divergence } : {}),
423
+ ...(Object.hasOwn(row, 'sample_differences') ? { sample_differences: row.sample_differences } : {}),
424
+ ...(row.diagnostic || row.diagnostic_subset ? { diagnostic: true, diagnostic_subset: true, selected_steps: row.selected_steps ?? [] } : {}),
425
+ ...resultOutcome(row) };
426
+ }
427
+
428
+ function batchTokenUsage(publicRows) {
429
+ const sumKey = key => publicRows.every(row => typeof row[key] === 'number')
430
+ ? publicRows.reduce((sum, row) => sum + row[key], 0) : 'unknown';
431
+ const input_tokens = sumKey('input_tokens');
432
+ const cached_input_tokens = typeof input_tokens === 'number' ? sumKey('cached_input_tokens') : 'unknown';
433
+ const output_tokens = sumKey('output_tokens');
434
+ const complete = typeof input_tokens === 'number' && typeof cached_input_tokens === 'number';
435
+ return { input_tokens, cached_input_tokens, output_tokens, cached_input_share: shareOf(input_tokens, cached_input_tokens), complete };
436
+ }
437
+
438
+ export function renderJson({ batch = null, repo, sourceSha256 = null, coverage, rows, warnings = [], exitCode, summaryLine: line }, ports = {}) {
439
+ rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
440
+ line = line ?? summaryLine(rows, null, ports);
441
+ 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 }));
443
+ const diagnostic = rows.filter(row=>row.diagnostic_subset === true);
444
+ 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
+ token_usage: batchTokenUsage(publicRows), rows: publicRows, warnings };
446
+ }
447
+
448
+ const count = (number, word) => `${number} ${word}${number === 1 ? '' : 's'}`;
449
+ // One line an agent can paste into a PR: ✓ only when every story passed.
450
+ // One paste line per Story (0.1.6: many Stories in one run), in table order; a Story with two test files gets one line.
451
+ export function storyLines(rows, ports = {}) {
452
+ const groups = new Map();
453
+ for (const row of rows) groups.set(row.story, [...(groups.get(row.story) ?? []), row]);
454
+ return [...groups].map(([story, own]) => [story, summaryLine(own, story, ports)]);
455
+ }
456
+
457
+ const DEFAULT_PROMPT_TESTS_LABEL = 'Prompt tests';
458
+ export function summaryLine(rows, story = null, ports = {}) {
459
+ const labelText = ports?.promptTestsLabel ?? DEFAULT_PROMPT_TESTS_LABEL;
460
+ // A passed row proves only the criteria its report lists; without the list its criteria are not reported, never counted.
461
+ const unreported = row => row.state === 'passed' && !row.criteria;
462
+ const own = row => row.criteria ?? { passed: 0, total: row.criteria_total ?? 0 };
463
+ const criteria = rows.filter(row => !unreported(row)).reduce((sum, row) => ({ passed: sum.passed + own(row).passed, total: sum.total + own(row).total }), { passed: 0, total: 0 });
464
+ const notReported = rows.some(unreported), someCounted = rows.some(row => !unreported(row));
465
+ const criteriaText = [...(someCounted || !notReported ? [`${criteria.passed} of ${count(criteria.total, 'criterion').replace(/criterions$/, 'criteria')}`] : ['passed']),
466
+ ...(notReported ? ['criteria details not reported'] : [])].join(' · ');
467
+ const checks = rows.reduce((sum, row) => ({ passed: sum.passed + (row.checks?.passed ?? 0), total: sum.total + (row.checks?.total ?? 0) }), { passed: 0, total: 0 });
468
+ // A running row with server progress reports its calls in the one progress fragment; the calls part counts the other rows.
469
+ const progress = progressText(rows), counted = rows.filter(row => !hasProgress(row));
470
+ const sent = counted.filter(sentRow), known = sent.filter(row => typeof row.calls === 'number' && !OPEN_STATES.has(row.state));
471
+ const partial = sent.filter(row => !OPEN_STATES.has(row.state) && typeof row.calls !== 'number');
472
+ const calls = known.reduce((sum, row) => sum + row.calls, 0) + partial.reduce((sum, row) => sum + (row.known_calls ?? 0), 0);
473
+ const unknownCalls = sent.reduce((sum, row) => sum + (known.includes(row) ? 0 : row.unknown_calls || 1), 0);
474
+ const rerunCalls = rows.reduce((sum, row) => sum + (Number.isInteger(row.rerun?.calls) && row.rerun.calls > 0 ? row.rerun.calls : 0), 0);
475
+ const extraFailed = rows.filter(row => row.state !== 'failed').reduce((n, row) => n + failedCheckCount(row), 0);
476
+ const labels = rows.filter(row => row.state !== 'passed').map(row => outcomeText({ ...row, progress: undefined, ahead: undefined }));
477
+ const others = [...new Set(labels)].map(label => `${labels.filter(value => value === label).length} ${label}`);
478
+ // A cross for any failed row or failed check; a check without failures that still runs or has no verdict says so (cli 12b).
479
+ const diagnostic = rows.some(row=>row.diagnostic_subset === true);
480
+ const mark = rows.some(row => row.state === 'failed' || failedCheckCount(row) > 0) ? '✗'
481
+ : diagnostic ? 'diagnostic subset, not a full Story pass ·'
482
+ : rows.length && rows.every(row => row.state === 'passed' && !row.diagnostic && !row.diagnostic_subset) ? '✓'
483
+ : rows.some(row => OPEN_STATES.has(row.state)) ? 'running ·'
484
+ : 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 ·';
485
+ const rerunShare = rerunCalls ? `${rerunCalls} for reruns` : '';
486
+ const usage = known.length ? `${count(calls, 'AI call')}${rerunShare ? ` (${rerunShare})` : ''}` : rerunShare || count(calls, 'AI call');
487
+ 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'] : [];
488
+ const broken = rows.filter(row=>row.unsent).length, unchecked = rows.reduce((n,row)=>n+(row.not_checked?.length??0),0);
489
+ return [`${labelText}${story ? ` (${story})` : ''}${rows.some(row => row.draft) ? ' (DRAFT)' : ''}: ${mark} ${criteriaText}`,
490
+ ...(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(' · ');
491
+ }
492
+
493
+ const shellWord = word => /^[A-Za-z0-9_./:@%+=,-]+$/.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
494
+
495
+ function table(rows, now) {
496
+ const previousPass = row => {
497
+ const date = new Date(row.passed_at), today = new Date(now), two = number => String(number).padStart(2, '0');
498
+ return 'unchanged, passed ' + (date.toDateString() === today.toDateString() ? `${two(date.getHours())}:${two(date.getMinutes())}` : `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())}`)
499
+ + `; force with pdd test --cache-clear ${shellWord(row.story)}`;
500
+ };
501
+ const lines = [['Story', 'Test', 'Result', 'Checks', 'Time'], ...rows.map(row => [row.title ?? row.story, row.test,
502
+ `${row.cached ? previousPass(row) : outcomeText(row)}${row.draft ? ' (DRAFT)' : ''}${row.cache_reason ? `; ${cleanText(row.cache_reason)}` : ''}`, row.checks ? `${row.checks.passed}/${row.checks.total}` : '-',
503
+ typeof row.seconds === 'number' ? `${round(row.seconds).toFixed(1)} s` : '-'])];
504
+ const widths = lines[0].map((_, column) => Math.max(...lines.map(line => line[column].length)));
505
+ return lines.map(line => line.map((cell, column) => column === line.length - 1 ? cell : cell.padEnd(widths[column])).join(' ').trimEnd());
506
+ }
507
+
508
+ // ---- Expected and got (round-2 tester: a CLI's stdout lost its line breaks and was cut near the difference) ----
509
+ const VALUE_LINES = 20;
510
+ // One line of a value: no control characters and no token, but its spaces stay.
511
+ const plainLine = (text, secrets) => secrets.reduce((value, secret) => secret ? value.split(secret).join('[secret]') : value,
512
+ text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, ' '));
513
+ const oneLine = value => typeof value !== 'string' || !/\n(?!$)/.test(value);
514
+ const valueLines = value => typeof value === 'string' ? value.replace(/\n$/, '').split('\n') : (JSON.stringify(value, null, 2) ?? 'nothing').split('\n');
515
+
516
+ // The check line: one line when both values fit, else the check and a block for each value, never cut inside a line.
517
+ function checkLines(check, secrets) {
518
+ const head = `${check.criterion_id}${check.step_id ? ` step ${check.step_id}` : ''} ${check.target} ${check.path}`;
519
+ const noError = check.target === 'error' && check.actual && typeof check.actual === 'object' && !Array.isArray(check.actual)
520
+ && check.actual.missing === true && Object.keys(check.actual).length === 1
521
+ && (check.normal_result === true || ['no-error', 'needs-tool'].includes(check.diagnosis?.kind));
522
+ const actualValue = noError ? 'no error (a normal result)' : check.actual, actualDisplay = noError ? actualValue : shown(actualValue, secrets);
523
+ const criterion = check.criterion_text ? [` Criterion: ${plainLine(check.criterion_text, secrets)}`] : [];
524
+ const refLabel = check.ref_target && check.ref_path !== undefined
525
+ ? `${check.op ? `${check.op} ` : ''}${check.ref_target} ${check.ref_path || '/'}${check.ref_json_path ? ` (${check.ref_json_path})` : ''}` : null;
526
+ const fits = [check.expected, check.actual].every(value => oneLine(value) && shown(value, secrets).length <= 80);
527
+ if (fits) return [`${head} expected ${refLabel ? `${refLabel} (${shown(check.expected, secrets)})` : shown(check.expected, secrets)}, got ${actualDisplay}`, ...criterion];
528
+ const expected = valueLines(check.expected), actual = valueLines(actualValue);
529
+ // Start 2 lines before the first line where two strings differ, when it is past the first 20.
530
+ const differ = typeof check.expected === 'string' && typeof check.actual === 'string' ? expected.findIndex((text, index) => text !== actual[index]) : -1;
531
+ const from = differ >= VALUE_LINES ? differ - 2 : 0;
532
+ const block = (word, value, lines) => [` ${word}:`, ...(from ? [` … ${from} lines before`] : []),
533
+ ...lines.slice(from, from + VALUE_LINES).map(text => ` ${plainLine(text, secrets)}`),
534
+ ...(lines.length > from + VALUE_LINES ? [` … ${lines.length - from - VALUE_LINES} more lines in the report`] : []),
535
+ ...(typeof value === 'string' && value.endsWith('\n') ? [' (ends with a line break)'] : [])];
536
+ return [head, ...criterion, ...block(refLabel ? `expected (${refLabel})` : 'expected', check.expected, expected), ...block('got', check.actual, actual)];
537
+ }
538
+ // With a plain reason (#379): the reason, where and the fix; an AI service failure is not a problem in the test.
539
+ function refusalLines(item, serverNext = false) {
540
+ const lines = item.reason ? [` ${item.code}: ${item.reason}`, ...(item.where ? [` Where: ${item.where}`] : []),
541
+ ...(serverNext ? [] : item.cause === 'ai-service' ? [' Your test is fine. Run it again.'] : item.fix ? [` Fix: ${item.fix}`] : [])]
542
+ : [` ${[item.code, item.section, item.message].filter(Boolean).join(' ')}`];
543
+ if (!item.reason && item.engine_message && item.engine_message !== item.code && item.engine_message !== item.message) lines.push(` engine: ${item.engine_message}`);
544
+ if (item.hint && !serverNext) lines.push(` ${item.hint}`);
545
+ for (const fact of item.dependency_errors ?? []) lines.push(` Dependency: step ${JSON.stringify(fact.step_id)} input ${JSON.stringify(fact.input_path)} references step ${JSON.stringify(fact.predecessor_step_id)} result ${JSON.stringify(fact.result_path)}; that step reported error code ${JSON.stringify(fact.error_code)}.`);
546
+ return lines;
547
+ }
548
+
549
+ const serverAdvice = (row, secrets = []) => [
550
+ ...(row.why ? [` Why: ${cleanText(row.why, secrets)}`] : []),
551
+ ...(row.next_step ? [` Next: ${cleanText(row.next_step, secrets)}`] : [])];
552
+
553
+ // Text-only metadata comes from the raw refusal; technical JSON keeps its original fields.
554
+ function busyMessage(row, secrets) {
555
+ const seconds = row.busy_display?.max_wait_seconds;
556
+ const duration = Number.isSafeInteger(seconds) && seconds > 0
557
+ ? seconds % 60 === 0 ? count(seconds / 60, 'minute') : count(seconds, 'second') : null;
558
+ const story = typeof row.story === 'string' ? cleanText(row.story, secrets) : '';
559
+ const retry = story && story !== '-' ? `: pdd test ${shellWord(story)}` : '.';
560
+ return `Not run: PDD stayed busy${duration ? ` for ${duration}` : ''}, so your check did not start. Nothing was charged. Try again in a few minutes${retry}`;
561
+ }
562
+
563
+ const validRerun = item => Number.isInteger(item?.runs) && item.runs >= 2
564
+ && Number.isInteger(item?.failed) && item.failed >= 0 && item.failed <= item.runs;
565
+ const rerunVerdict = item => item.failed === 0
566
+ ? `passed ${item.runs} of ${item.runs} reruns.`
567
+ : item.stable === true && item.runs >= 2 && item.failed === item.runs
568
+ ? `failed ${item.failed} of ${item.runs} (stable). A recheck of the same files will not help.`
569
+ : `failed ${item.failed} of ${item.runs} (unstable). Make the rule in the prompt firmer.`;
570
+ function rerunEntries(row, failed) {
571
+ const entries = [], seen = new Set();
572
+ for (const check of failed) {
573
+ const key = check.step_id ?? '';
574
+ if (seen.has(key)) continue;
575
+ seen.add(key);
576
+ const sameStep = failed.filter(item => (item.step_id ?? '') === key);
577
+ const diagnosis = sameStep.map(item => item.diagnosis?.rerun).find(validRerun);
578
+ const reportStep = row.rerun?.steps?.find(item => item.step_id && item.step_id === check.step_id);
579
+ const item = diagnosis ?? (validRerun(reportStep) ? reportStep : null);
580
+ if (item) entries.push({ key, line: ` Rerun: ${rerunVerdict(item)}` });
581
+ }
582
+ if (!entries.length && row.rerun?.skipped) entries.push({ key: null, line: ` Rerun: skipped (${row.rerun.skipped}).` });
583
+ return entries;
584
+ }
585
+
586
+ function localRefusals(rows, secrets) {
587
+ const local = rows.filter(row => row.state === 'refused' && !sentRow(row)), out = [];
588
+ if (local.length) {
589
+ out.push('REFUSED before sending (not sent, 0 AI calls)');
590
+ for (const row of local) {
591
+ for (const item of row.refusals) {
592
+ out.push(` ${row.test}${item.step ? ` step ${item.step}` : ''} ${item.code}`, ` ${item.message}`, ...(item.hint && !row.next_step ? [` ${item.hint}`] : []));
593
+ }
594
+ out.push(...serverAdvice(row, secrets));
595
+ }
596
+ }
597
+ return out;
598
+ }
599
+
600
+ // The terminal result of a batch (stdout).
601
+ export function renderText({ batch, rows, coverage, warnings = [], details = false, timeoutMin = null, interrupted = false, reading = false, exitCode, secrets = [], recovery, now = Date.now(), noFailed = false }, ports = {}) {
602
+ const out = [];
603
+ rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
604
+ out.push(...localRefusals(rows.filter(row=>row.unsent),secrets));
605
+ if (exitCode === 3) out.push(recovery ?? `pdd test --read ${batch}`);
606
+ // One Story: its own line is the result; the overall line comes only with two or more Stories.
607
+ const perStory = storyLines(rows, ports).map(([, text]) => text);
608
+ if (noFailed) return 'No failed Stories. 0 AI calls.\n';
609
+ out.push(...table(rows, now), ...(perStory.length === 1 ? perStory : [...perStory, summaryLine(rows, null, ports)]));
610
+ if ([3, 4, 5].includes(exitCode)) {
611
+ const failed = new Set(rows.filter(row => row.state === 'failed' || failedCheckCount(row) > 0).map(row => row.story));
612
+ const inconclusive = new Set(rows.filter(row => !['passed', 'failed'].includes(row.state)).map(row => row.story));
613
+ const other = [...inconclusive].filter(story => !failed.has(story)).length;
614
+ const overlap = [...inconclusive].filter(story => failed.has(story)).length;
615
+ if (failed.size && inconclusive.size) {
616
+ const first = failed.size === 1 ? '1 Story failed its checks.' : `${failed.size} Stories failed their checks.`;
617
+ const second = other ? other === 1 ? 'Another Story has no verdict' : `${other} other Stories have no verdict`
618
+ : failed.size === 1 ? 'That Story also has checks with no verdict'
619
+ : `${overlap} of those Stories also ${overlap === 1 ? 'has' : 'have'} checks with no verdict`;
620
+ out.push(`${first} ${second}, so the exit code is ${exitCode}.`);
621
+ }
622
+ }
623
+ for (const row of rows.filter(row => row.state === 'failed' || (row.failed_checks ?? []).length > 0)) {
624
+ const fullFailure = row.state === 'failed';
625
+ const failed = row.failed_checks ?? [], reruns = rerunEntries(fullFailure ? row : { ...row, rerun: row.rerun ? { ...row.rerun, skipped: undefined } : null }, failed), rerunByStep = new Map(reruns.filter(item => item.key !== null).map(item => [item.key, item.line])), lines = [`FAILED ${row.title} (${row.test})`];
626
+ for (const check of failed) {
627
+ lines.push(...checkLines(check, secrets).map(text => ` ${text}`));
628
+ if (check.diagnosis?.why) lines.push(` Why: ${check.diagnosis.why}`);
629
+ if (check.diagnosis?.next_step) lines.push(` Next: ${check.diagnosis.next_step}`);
630
+ const key = check.step_id ?? '', line = rerunByStep.get(key);
631
+ if (line) { lines.push(line); rerunByStep.delete(key); }
632
+ }
633
+ if (reruns.some(item => item.key === null)) lines.push(reruns.find(item => item.key === null).line);
634
+ if (fullFailure) lines.push(...(row.warnings ?? []).map(text => ` ${text}`));
635
+ const diagnosed = failed.some(check => check.diagnosis?.why || check.diagnosis?.next_step);
636
+ if (!diagnosed && fullFailure && row.next_step && row.why) lines.push(` Why: ${row.why}`);
637
+ if (!diagnosed && fullFailure && row.next_step) lines.push(` Next: ${row.next_step}`);
638
+ if (!diagnosed && (!fullFailure || !row.next_step)) lines.push(' Next: show this check to the person. A person decides expected values. The agent may propose a change, and never makes it.');
639
+ lines.push(` Report: ${row.report_url ?? 'none'}`); out.push(...lines);
640
+ }
641
+ out.push(...localRefusals(rows.filter(row=>!row.unsent), secrets));
642
+ for (const row of rows.filter(row => row.state === 'refused' && row.native_only?.length)) out.push(` Native-only: ${cleanText(row.note?.message, secrets)}`);
643
+ for (const row of rows.filter(row => row.state === 'refused' && sentRow(row))) {
644
+ out.push(`REFUSED ${row.title} (${row.test})`, ...row.refusals.flatMap(item => refusalLines(item, !!row.next_step)), ...serverAdvice(row, secrets), ...(row.report_url ? [` Report: ${row.report_url}`] : []));
645
+ }
646
+ for (const row of rows.filter(row => ['not_run', 'not run'].includes(row.state))) {
647
+ if ((row.busy_display || row.busy && row.request_ids?.length) && !row.note?.message?.startsWith('Stopped.')) {
648
+ const { reason } = resultOutcome(row);
649
+ if (['timeout-flag', 'deadline', 'interrupted'].includes(reason?.code)) out.push(cleanText(reason.message, secrets));
650
+ out.push(busyMessage(row, secrets));
651
+ continue;
652
+ }
653
+ const note = row.note ?? row.reason;
654
+ const message = note?.message ?? (row.request_ids?.length ? 'No checks ran for this attempt.' : 'pdd did not send it.');
655
+ const explanation = row.next_step ? message.replace(/(?:^|\s)(?:Retry this batch later|Run it again|Run the same command again later|Run a fresh pdd (?:test|check) command to start checks|Try again later)\.?/g, '').trim() : message;
656
+ out.push(`NOT RUN ${row.title} (${row.test})${explanation ? `: ${explanation}` : ''}${note?.code ? ` (${note.code})` : ''}`, ...serverAdvice(row, secrets));
657
+ }
658
+ for (const row of rows.filter(row => OPEN_STATES.has(row.state))) {
659
+ const limit = Number.isInteger(timeoutMin) ? `${timeoutMin} min` : `${Math.round(timeoutMin * 60)} s`;
660
+ out.push(`STILL RUNNING${reading || (!interrupted && !timeoutMin) ? '' : interrupted ? ' when pdd stopped reading' : ` after ${limit}`}: ${row.title}. Do not send it again.${row.note?.code === 'timeout-flag' || row.reason?.code === 'timeout-flag' ? ` ${row.note?.message ?? row.reason.message}` : ''}`);
661
+ }
662
+ for (const row of rows.filter(row => ['unknown', 'partial'].includes(row.state) && !row.provider && !row.time_limit)) {
663
+ out.push(`UNKNOWN ${row.title}: the run may have executed. Its result is unknown.`, ...((row.lost || row.final) && row.why ? [` ${row.why}`, ...(row.next_step ? [` Next: ${cleanText(row.next_step, secrets)}`] : [])] : serverAdvice(row, secrets)));
664
+ }
665
+ for (const row of rows.filter(row => row.time_limit)) {
666
+ out.push(`STOPPED ${row.title}: ${row.time_limit.message}`, ...(row.next_step ? [] : [` ${row.time_limit.fix}`]), ...serverAdvice(row, secrets),
667
+ ...(row.report_url ? [` Report: ${row.report_url}`] : []));
668
+ }
669
+ for (const row of rows.filter(row => row.state === 'unknown' && row.provider)) {
670
+ out.push(`UNKNOWN ${row.title}: ${providerText(row)}`, ` ${row.provider.code}${row.provider.detail ? ` (${row.provider.detail})` : ''}${row.report_url ? ` Report: ${row.report_url}` : ''}`,
671
+ ...(row.next_step ? [] : [' To try again, run `pdd test` again (a new request).']), ...serverAdvice(row, secrets));
672
+ }
673
+ for (const row of rows.filter(row => row.sample_divergence)) {
674
+ const evidence = row.sample_divergence;
675
+ if (evidence.divergent) {
676
+ out.push(`Sample divergence (advisory): ${cleanText(row.title, secrets)}`);
677
+ for (const difference of evidence.differences) out.push(` ${evidenceLabel(difference.step_id, secrets)} ${difference.target} ${evidenceLabel(difference.path, secrets) || '""'}`,
678
+ ` ${difference.values.map(item => `Sample ${item.sample}: ${item.present ? shown(item.value, secrets) : 'missing'}`).join('; ')}`);
679
+ for (const agreement of row.field_agreement ?? []) for (const field of agreement.fields ?? []) if (field.status === 'varied') out.push(
680
+ ` ${evidenceLabel(agreement.step_id, secrets)} result ${evidenceLabel(field.path, secrets) || '""'}: ${field.buckets.map(bucket => `${shown(bucket.value, secrets)} (${bucket.count})`).join('; ')}`);
681
+ }
682
+ if (!evidence.complete) out.push('Sample comparison incomplete; agreement is unknown.');
683
+ }
684
+ if (details) for (const row of rows.filter(row => row.all_checks?.length || !row.cached && formatPromptCacheTokens(row))) {
685
+ const tokenText = !row.cached ? formatPromptCacheTokens(row) : null;
686
+ out.push(`Checks for ${row.title} (${row.test}):`,
687
+ ...(tokenText ? [` Tokens: ${tokenText}`] : []),
688
+ ...[...(row.all_checks ?? [])].sort((a, b) => a.passed - b.passed).flatMap(check => checkLines(check, secrets)
689
+ .map((text, index) => index ? ` ${text}` : ` ${check.passed ? 'passed' : 'failed'} ${text}`)));
690
+ }
691
+ for (const row of rows) for (const item of criterionCoverage(row) ?? []) {
692
+ const text = row.criterion_texts?.[item.criterion_id];
693
+ out.push(`criterion ${item.criterion_id}:${text ? ` ${cleanText(text, secrets)}` : ''}${item.exit_code_only ? ' — checked by exit code only' : ''}`);
694
+ }
695
+ for (const row of rows) for (const item of row.not_checked ?? []) out.push(
696
+ `${row.test} ${item.criterion_id}: not checked: ${cleanText(item.reason,secrets)} (${cleanText(item.text,secrets)})`);
697
+ 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));
698
+ for (const row of rows.filter(row => row.compatibility)) out.push(...describeCompatibility({
699
+ label: cleanText(row.test || '', secrets),
700
+ compatibility: row.compatibility,
701
+ clientAdvice: row.client_advice || null,
702
+ details: Boolean(details),
703
+ }).text.split('\n'));
704
+ 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)}));
705
+ const models = [...new Set(rows.map(row => row.requested_model).filter(Boolean))];
706
+ out.push(`${rows.filter(row => resultOutcome(row).state === 'passed').length} of ${rows.length} stories passed.${models.length ? ` Model asked for: ${models.join(', ')}.` : ''}`);
707
+ const activeRows = rows.filter(row => !row.cached);
708
+ const cacheRows = activeRows.filter(row => formatPromptCacheTokens(row) !== null);
709
+ if (cacheRows.length) {
710
+ const input_tokens = cacheRows.reduce((sum, row) => sum + row.input_tokens, 0);
711
+ const cached_input_tokens = cacheRows.reduce((sum, row) => sum + row.cached_input_tokens, 0);
712
+ const output_tokens = cacheRows.every(row => typeof row.output_tokens === 'number')
713
+ ? cacheRows.reduce((sum, row) => sum + row.output_tokens, 0) : 'unknown';
714
+ const unknownCount = activeRows.length - cacheRows.length;
715
+ out.push(`Token usage: ${formatPromptCacheTokens({ input_tokens, cached_input_tokens, output_tokens })}${unknownCount ? ` + ${unknownCount} unknown` : ''}.`);
716
+ }
717
+ const linked = rows.filter(row => row.report_url);
718
+ if (linked.length) {
719
+ const width = Math.max(...linked.map(row => row.story.length));
720
+ out.push('Reports (anyone with a link can open it):', ...linked.map(row => ` ${row.story.padEnd(width)} ${row.report_url}${row.draft ? ' (DRAFT)' : ''}`));
721
+ }
722
+ const rest = [...warnings, ...rows.filter(row => row.state !== 'failed').flatMap(row => (row.warnings ?? []).map(text => `${text} (${row.test})`))];
723
+ out.push(...rest);
724
+ return `${out.join('\n')}\n`;
725
+ }
726
+
727
+ // Owner-provided Try accounting is separate from a program's stdout/body and from account-wide allowances.
728
+ export function tryUsage(answer, { cap } = {}) {
729
+ const number = value => Number.isSafeInteger(value) && value >= 0 ? value : 'unknown';
730
+ const total = number(answer?.calls?.cap ?? answer?.result?.session?.max_calls ?? cap);
731
+ const remaining = number(answer?.calls?.remaining ?? answer?.result?.session?.remaining_calls ?? answer?.result?.report?.remaining_calls);
732
+ return { calls: number(answer?.usage?.calls), remaining, cap: total,
733
+ used: typeof total === 'number' && typeof remaining === 'number' && remaining <= total ? total - remaining : 'unknown',
734
+ ...tokenUsageOf(answer) };
735
+ }
736
+ export function tryUsageLine(usage, { command = false } = {}) {
737
+ const tokens = formatPromptCacheTokens(usage);
738
+ return `Try AI usage: ${command ? `${usage.calls} this command · ` : ''}${usage.used} used · ${usage.remaining} remaining (session cap ${usage.cap})${tokens ? ` · ${tokens}` : ''}.`;
739
+ }
740
+ export function tryUsageHeaders(usage) {
741
+ return { 'x-pdd-ai-calls': String(usage.calls), 'x-pdd-try-used': String(usage.used),
742
+ 'x-pdd-try-remaining': String(usage.remaining), 'x-pdd-try-cap': String(usage.cap),
743
+ ...(tokenInt(usage?.input_tokens) !== undefined ? { 'x-pdd-input-tokens': String(usage.input_tokens) } : {}),
744
+ ...(tokenInt(usage?.cached_input_tokens) !== undefined ? { 'x-pdd-cached-input-tokens': String(usage.cached_input_tokens) } : {}) };
745
+ }
746
+
747
+ export function coverageText(coverage, {busy = false} = {}) {
748
+ const runtime = coverage?.runtime;
749
+ const promptLine = runtime ? `${busy || runtime.native_only ? 'Runtime' : 'Interpreter'} coverage: ${runtime.checkable} of ${runtime.total} prompts checkable, ${runtime.native_only} native-only\n` : '';
750
+ if (!coverage?.available) return promptLine + 'Module binding coverage unavailable: no pdd-bindings.json.';
751
+ return promptLine + [`${coverage.bound} of ${coverage.total} modules bound`, ...coverage.modules.filter(m => m.state === 'unbound').map(m => ` ${m.path}: ${m.reason} Port attempted: ${m.port_attempt}`)].join('\n');
752
+ }