@promptdriven/runtime-client 0.0.0-stage → 1.0.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 (35) 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 +105 -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 +943 -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/product-composition.mjs +384 -0
  18. package/src/runtime/runtime-binding-plan.mjs +145 -0
  19. package/src/runtime/runtime-bindings.mjs +71 -0
  20. package/src/runtime/runtime-check-plan.mjs +411 -0
  21. package/src/runtime/runtime-client.mjs +6323 -0
  22. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  23. package/src/runtime/runtime-markdown.mjs +215 -0
  24. package/src/runtime/runtime-outcome.mjs +407 -0
  25. package/src/runtime/runtime-output.mjs +714 -0
  26. package/src/runtime/runtime-preflight.mjs +3118 -0
  27. package/src/runtime/runtime-slots.mjs +391 -0
  28. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  29. package/src/runtime/runtime-workspace.mjs +52 -0
  30. package/src/runtime/scenario-json.mjs +91 -0
  31. package/src/runtime/secret-redaction.mjs +53 -0
  32. package/src/runtime/try-doors.mjs +231 -0
  33. package/src/runtime/try-http.mjs +259 -0
  34. package/src/runtime/try-mcp.mjs +223 -0
  35. package/src/runtime/try-session.mjs +95 -0
@@ -0,0 +1,407 @@
1
+ // Generated from prompts/cli/runtime-outcome.prompt.md (sha256: b70ee8a227e1d2fe4788304de5ae87cf28242d91c7be013cce19d02419ac58fe).
2
+ // What happened to one selected test: the one place that turns a server answer into an outcome.
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
+ export const CHECK_STATES = Object.freeze(['waiting', 'sent', 'passed', 'failed', 'refused', 'partial', 'not run']);
5
+
6
+ export function failedCheckCount(row = {}) {
7
+ if (Array.isArray(row?.failed_checks) && row.failed_checks.length > 0) return row.failed_checks.length;
8
+ const passed = row?.checks?.passed, total = row?.checks?.total;
9
+ if (Number.isSafeInteger(passed) && passed >= 0 && Number.isSafeInteger(total) && total > passed) return total - passed;
10
+ return 0;
11
+ }
12
+
13
+ export function providerText(row = {}) {
14
+ const failed = failedCheckCount(row);
15
+ return failed > 0
16
+ ? `the AI provider failed during the run after ${failed} ${failed === 1 ? 'check' : 'checks'} failed. Do not send it again yet.`
17
+ : PROVIDER_TEXT;
18
+ }
19
+
20
+ // The public result is independent of the transport state needed to resume a job.
21
+ export function resultOutcome(row = {}) {
22
+ const supplied = row.note ?? (row.reason && typeof row.reason === 'object' ? row.reason : null);
23
+ const originalCode = supplied?.code || row.code || (row.time_limit ? 'deadline' : null) || row.provider?.code || (row.state === 'sending' ? 'dispatch-uncertain' : null) || row.refusals?.[0]?.code;
24
+ let code = ['check-busy', 'lint-busy'].includes(originalCode) ? 'server-busy' : originalCode === 'lint-pending' ? 'deadline' : originalCode;
25
+ const states = { ready: 'waiting', queued: 'sent', running: 'sent', sending: 'partial', not_run: 'not run', unknown: 'partial' };
26
+ let state = Object.hasOwn(states, row.state) ? states[row.state] : CHECK_STATES.includes(row.state) ? row.state : 'partial';
27
+ if (row.unsent && row.refusals?.length) { code='broken-test'; state='not run'; }
28
+ if (code === 'broken-test') state = 'not run';
29
+ if (state === 'not run' && (row.retryable === true || row.busy_display) && !['timeout-flag', 'deadline', 'interrupted'].includes(code)) code = 'server-busy';
30
+ if (state === 'passed') return { state, reason: null };
31
+ const defaults = { waiting: ['awaiting-admission', 'Waiting for admission.'], sent: ['awaiting-server-verdict', 'Sent; waiting for a server verdict.'],
32
+ failed: ['check-failed', 'A check failed.'], refused: ['admission-refused', 'Admission was refused.'],
33
+ partial: ['no-server-verdict', 'No complete server verdict.'], 'not run': ['no-server-verdict', 'No server verdict for this test.'] };
34
+ const [fallbackCode, fallbackMessage] = defaults[state];
35
+ const message = supplied?.message || (row.time_limit ? [row.time_limit.message, row.time_limit.fix].filter(Boolean).join(' ') : null) || (row.provider ? providerText(row) : null) || row.message || (typeof row.reason === 'string' ? row.reason : null) || row.why || row.refusals?.[0]?.message || fallbackMessage;
36
+ return { state, reason: { code: code || fallbackCode, message } };
37
+ }
38
+
39
+ const objects = value => Array.isArray(value) ? value.filter(item => item && typeof item === 'object' && !Array.isArray(item)) : [];
40
+ const count = value => Number.isSafeInteger(value) && value >= 0;
41
+ const TERMINAL = new Set(['passed', 'failed', 'refused', 'not_run']);
42
+ // Group precedence: the first state present decides. Any state that is not a known end counts as unknown.
43
+ const DECIDES = ['unknown', 'not_run', 'refused', 'failed', 'passed'];
44
+
45
+ const nonEmpty = (...values) => values.find(value => typeof value === 'string' && value.length > 0) ?? null;
46
+
47
+ const refused = (refusals, extra = {}) => {
48
+ const first = refusals[0] ?? {};
49
+ return { state: 'refused', code: first.code ?? null, field: first.field ?? first.at ?? first.section ?? null, fix: first.fix ?? null,
50
+ message: first.reason ?? first.message ?? first.code ?? null, refusals, ...extra };
51
+ };
52
+
53
+ const appMapRefused = (refusals, extra = {}) => {
54
+ const first = refusals[0] ?? {};
55
+ return { state: 'refused', code: nonEmpty(first.code),
56
+ field: nonEmpty(first.field, first.at, first.pointer, first.section, first.file, first.path),
57
+ fix: nonEmpty(first.fix), message: nonEmpty(first.reason, first.message, first.code), refusals, ...extra };
58
+ };
59
+
60
+ // 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
+ const outcome = answerOutcome(answer, { test, steps, appMaps, kind, timeLimit, sourceFiles, capacityUncertain });
63
+ if (outcome.state !== 'passed' && !outcome.code) outcome.code = timeLimit ? 'deadline' : resultOutcome(outcome).reason.code;
64
+ return kind === 'lint' ? { ...outcome, compatibility: selectedCompatibility(answer, test, sourceFiles) } : outcome;
65
+ }
66
+
67
+ function answerOutcome(answer, { test, steps, appMaps, kind, timeLimit, sourceFiles, capacityUncertain }) {
68
+ const result = answer?.result, report = result?.report;
69
+ if (timeLimit) return { state: 'unknown', reason: 'The step was stopped at its time limit.' };
70
+ if (capacityUncertain && kind === 'check') return { state: 'unknown', reason: 'Check capacity accounting is incomplete or conflicting.' };
71
+ if (answer?.state === 'queued') return { state: 'queued', ...(count(answer.queue?.ahead) ? { ahead: answer.queue.ahead } : {}) };
72
+ if (answer?.state === 'running') {
73
+ const progress = progressFrom(answer.progress);
74
+ return { state: 'running', ...(Object.keys(progress).length ? { progress } : {}) };
75
+ }
76
+ // The public refusal list; the report's own refusal stands in only when that list is empty.
77
+ const refusals = objects(result?.refusals);
78
+ if (!refusals.length && report?.refusal && typeof report.refusal === 'object' && !Array.isArray(report.refusal)) refusals.push(report.refusal);
79
+ // A refusal the server declares retryable, before dispatch, is a check that did not run, whatever its code.
80
+ const retry = refusals.find(item => item.retryable === true || item.details?.retryable === true);
81
+ if (retry && (report?.dispatch ?? answer?.dispatch) === 'not_started')
82
+ return { state: 'not_run', code: retry.code ?? 'server-busy', retryable: true, message: retry.reason ?? retry.message ?? retry.code ?? null };
83
+ if (kind === 'lint') return lintOutcome(answer, refusals, test, steps, appMaps, sourceFiles);
84
+ if (answer?.state === 'unknown') return { state: 'unknown', reason: result?.why ?? 'No verdict was returned.' };
85
+ if (answer?.state === 'failed') return { state: 'failed', criteria: objects(report?.criterion_results) };
86
+ if (answer?.state === 'refused' || report?.verdict === 'refused') return refused(refusals);
87
+ if (answer?.state === 'passed' && result && typeof result === 'object') return { state: 'passed' };
88
+ return { state: 'unknown', reason: result?.why ?? 'No verdict was returned.' };
89
+ }
90
+
91
+ function normalizeMapProblem(item, mapPath) {
92
+ const { detail, ...rest } = item;
93
+ const message = nonEmpty(
94
+ item.message,
95
+ [item.reason, item.fix].filter(Boolean).join(' '),
96
+ detail,
97
+ item.engine_message,
98
+ item.code,
99
+ );
100
+ return {
101
+ ...rest,
102
+ code: nonEmpty(item.code) ?? 'lint-refused',
103
+ file: item.file ?? mapPath,
104
+ path: item.path ?? item.file ?? mapPath,
105
+ ...(message ? { message } : {}),
106
+ };
107
+ }
108
+
109
+ // A selected test passes lint on its own evidence: a passing per-test verdict and passing applicable app maps.
110
+ // An ended lint that gives a test or applicable app map no verdict leaves it not run; only a lint that has not ended is unknown.
111
+ function lintOutcome(answer, refusals, test, steps, appMaps, sourceFiles) {
112
+ const result = answer?.result, report = result?.report, program = report?.program;
113
+ if (!['passed', 'failed', 'refused'].includes(answer?.state)) return { state: 'unknown', reason: 'no lint verdict' };
114
+ const complete = report?.lint && typeof report.lint === 'object' ? report.lint.complete === true : result?.problems_complete === true;
115
+ const entries = list => objects(list).filter(item => item.path === test);
116
+ const listed = entries(result?.tests).length ? entries(result.tests) : entries(report?.lint?.tests);
117
+ const verdict = listed.length && listed.every(item => item.verdict === listed[0].verdict) ? listed[0].verdict : null;
118
+ const problems = objects(result?.problems).length ? objects(result.problems) : objects(report?.problems);
119
+ const targetOf = item => nonEmpty(item.file, item.path);
120
+ const own = [...refusals, ...problems].filter(item => targetOf(item) === test && item.severity !== 'warning');
121
+ const hasAppMaps = Array.isArray(result?.app_maps) || Array.isArray(report?.lint?.app_maps);
122
+ const reportAppMaps = objects(report?.lint?.app_maps);
123
+ const rawAppMaps = objects(result?.app_maps).length ? objects(result.app_maps) : reportAppMaps;
124
+ const applicableMaps = Array.isArray(appMaps)
125
+ ? [...new Set(appMaps.filter(path => typeof path === 'string' && path.length > 0))]
126
+ : [...new Set(rawAppMaps.map(item => item.path).filter(path => typeof path === 'string' && path.length > 0))];
127
+ const applicableSet = new Set(applicableMaps);
128
+ const appMapProblems = problems.filter(item => applicableSet.has(targetOf(item)) && item.severity !== 'warning');
129
+ const matchingAppMapRefusals = refusals.filter(item => applicableSet.has(targetOf(item)) && item.severity !== 'warning');
130
+ const reportMapErrors = reportAppMaps
131
+ .filter(entry => applicableSet.has(entry.path))
132
+ .flatMap(entry => objects(entry.errors).filter(item => item.severity !== 'warning').map(item => normalizeMapProblem(item, entry.path)));
133
+ const entryErrors = applicableMaps.flatMap(mapPath => {
134
+ const entry = [...rawAppMaps, ...reportAppMaps].find(item => item.path === mapPath && nonEmpty(item.error));
135
+ return entry ? [normalizeMapProblem({ code: entry.error, ...(nonEmpty(entry.reason) ? { reason: entry.reason } : {}) }, mapPath)] : [];
136
+ });
137
+ const candidateItems = [
138
+ ...appMapProblems.map(item => normalizeMapProblem(item, targetOf(item))),
139
+ ...matchingAppMapRefusals.map(item => normalizeMapProblem(item, targetOf(item))),
140
+ ...reportMapErrors,
141
+ ];
142
+ const specificMaps = new Set(
143
+ candidateItems
144
+ .filter(item => nonEmpty(item.code) && item.code !== 'lint-refused')
145
+ .map(targetOf),
146
+ );
147
+ for (const fallback of entryErrors) {
148
+ const mapPath = targetOf(fallback);
149
+ if (!specificMaps.has(mapPath)) {
150
+ candidateItems.push(fallback);
151
+ specificMaps.add(mapPath);
152
+ }
153
+ }
154
+ const appMapRefusals = [];
155
+ const seenAppMapRefusals = new Map();
156
+ for (const item of candidateItems) {
157
+ const mapPath = targetOf(item);
158
+ if (item.code === 'lint-refused' && specificMaps.has(mapPath)) continue;
159
+ const key = JSON.stringify([
160
+ mapPath,
161
+ nonEmpty(item.code),
162
+ nonEmpty(item.field, item.at, item.pointer, item.section, item.file, item.path),
163
+ nonEmpty(item.reason, item.message, item.code),
164
+ ]);
165
+ const existingIndex = seenAppMapRefusals.get(key);
166
+ if (existingIndex === undefined) {
167
+ seenAppMapRefusals.set(key, appMapRefusals.length);
168
+ appMapRefusals.push(item);
169
+ } else {
170
+ const kept = appMapRefusals[existingIndex];
171
+ const patch = {};
172
+ if (!nonEmpty(kept.fix) && nonEmpty(item.fix)) patch.fix = item.fix;
173
+ if (!nonEmpty(kept.reason) && nonEmpty(item.reason)) patch.reason = item.reason;
174
+ if (Object.keys(patch).length) appMapRefusals[existingIndex] = { ...kept, ...patch };
175
+ }
176
+ }
177
+ const coveredAppMaps = new Set(appMapRefusals.map(targetOf));
178
+ for (const mapPath of applicableMaps) {
179
+ if (!coveredAppMaps.has(mapPath) && [...rawAppMaps, ...reportAppMaps].some(item => item.path === mapPath && item.verdict === 'refused')) {
180
+ appMapRefusals.push({ code: 'lint-refused', field: mapPath, path: mapPath, message: `${mapPath} was refused by complete lint.` });
181
+ }
182
+ }
183
+ const mapEntries = mapPath => rawAppMaps.filter(item => item.path === mapPath);
184
+ const appMapsPassed = !hasAppMaps || applicableMaps.every(mapPath => {
185
+ const mapListed = mapEntries(mapPath);
186
+ return mapListed.length === 1 && mapListed[0].verdict === 'passed';
187
+ });
188
+ const appMapNotChecked = hasAppMaps && applicableMaps.some(mapPath => mapEntries(mapPath).some(item => item.verdict === 'not-checked'));
189
+ const notChecked = verdict === 'not-checked' || appMapNotChecked;
190
+ // The prompts the test reaches: each step's entry prompt and its declared call targets.
191
+ let draft = false, lazyPending = false, unlisted = false, reachedProblem = null;
192
+ if (Array.isArray(program?.prompts) || Array.isArray(program?.refused_prompts)) {
193
+ const byPath = new Map(objects(program.prompts).map(prompt => [prompt.path, prompt]));
194
+ const refusedPrompts = new Map(objects(program.refused_prompts).map(item => [item.path, item]));
195
+ const reached = new Set(), queue = objects(steps).map(step => step.entry_path);
196
+ while (queue.length && !reachedProblem) {
197
+ const path = queue.shift();
198
+ if (reached.has(path)) continue;
199
+ reached.add(path);
200
+ const prompt = byPath.get(path), state = prompt?.admission_state ?? prompt?.state, item = refusedPrompts.get(path);
201
+ const problem = (code, message) => ({ code, path, section: 'lint', message, reached: true });
202
+ if (item) reachedProblem = { ...item, ...problem(item.code || 'lint-refused', `${path}: ${item.message || item.code}`) };
203
+ else if (!Array.isArray(program.prompts)) continue;
204
+ else if (!prompt && !complete) unlisted = true;
205
+ else if (!prompt) reachedProblem = problem('unknown-target', `${path} is not in the lint report.`);
206
+ else if (state === 'stale') reachedProblem = problem('interface-stale', `${path} changed after its hash was filled or approved.`);
207
+ else if (state === 'missing' && prompt.lazy_interface_pending === true) {
208
+ lazyPending = true;
209
+ for (const dep of Array.isArray(prompt.dependencies) ? prompt.dependencies : []) {
210
+ if (typeof dep === 'string' && (byPath.has(dep) || refusedPrompts.has(dep))) queue.push(dep);
211
+ }
212
+ }
213
+ else if (state !== 'approved' && state !== 'draft') reachedProblem = problem(`interface-${typeof state === 'string' && state ? state : 'unapproved'}`,
214
+ `${path} has no usable Runtime interface.`);
215
+ else {
216
+ draft ||= state === 'draft' && prompt.lazy_interface !== true;
217
+ for (const call of objects(prompt.interface?.calls)) if (typeof call.target === 'string') queue.push(call.target);
218
+ if (prompt.lazy_interface === true) {
219
+ for (const dep of Array.isArray(prompt.dependencies) ? prompt.dependencies : []) {
220
+ if (typeof dep === 'string' && (byPath.has(dep) || refusedPrompts.has(dep))) queue.push(dep);
221
+ }
222
+ }
223
+ }
224
+ }
225
+ }
226
+ const notRun = (reason, code = !complete || notChecked ? 'deadline' : 'no-server-verdict') => ({ state: 'not_run', code, retryable: false, reason, draft });
227
+ if (own.some(item => refusals.includes(item))) return refused(own, { draft });
228
+ if (reachedProblem) return refused([reachedProblem], { draft });
229
+ if (appMapRefusals.length) return appMapRefused(appMapRefusals, { draft });
230
+ if (verdict === 'refused') return refused(own.length ? own : [{ code: 'lint-refused', message: `${test} was refused by complete lint.` }], { draft });
231
+ if (verdict === 'passed') {
232
+ if (!appMapsPassed) return notRun(!complete || unlisted || notChecked ? 'lint did not finish' : 'lint gave no verdict for this app map');
233
+ const compatibility = selectedCompatibility(answer, test, sourceFiles);
234
+ if (compatibility.association === 'matched') {
235
+ if (['invalid-source', 'unsupported-capability', 'missing-binding'].includes(compatibility.state)) {
236
+ const rows = [...compatibility.reported.operations, ...compatibility.reported.edges].filter(row => row.verdict === compatibility.state);
237
+ return refused(rows.length ? rows.map(row => ({ code: row.reason_code, path: row.selection.prompt_path,
238
+ section: row.selection.step_id, message: `${row.verdict}: ${row.reason_code}` }))
239
+ : [{ code: compatibility.state, message: compatibility.state }], { draft });
240
+ }
241
+ if (compatibility.state === 'supported' && compatibility.reported.complete) return { state: 'passed', draft };
242
+ if (lazyPending && complete && !own.length && compatibility.state === 'unknown' && compatibility.reported?.complete === false) {
243
+ return { state: 'passed', draft };
244
+ }
245
+ }
246
+ return notRun(compatibility.issue ?? 'selected compatibility is unknown or incomplete', compatibility.issue ?? 'no-server-verdict');
247
+ }
248
+ // A job refusal refuses a selected test that has no verdict of its own.
249
+ if (!listed.length && (answer.state === 'refused' || report?.verdict === 'refused' || refusals.length))
250
+ return refused(refusals.length ? refusals : [{ code: 'lint-refused', message: 'The interpreter refused lint.' }], { draft });
251
+ return notRun(!complete || unlisted || notChecked ? 'lint did not finish' : !appMapsPassed ? 'lint gave no verdict for this app map' : 'lint gave no verdict for this test');
252
+ }
253
+
254
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
255
+ const fields = (value, names) => object(value) && Object.keys(value).length === names.length && names.every(name => Object.hasOwn(value, name));
256
+ const text = value => typeof value === 'string' && value.length <= 4096;
257
+ const hex = (value, length) => typeof value === 'string' && new RegExp(`^[0-9a-f]{${length}}$`).test(value);
258
+ const verdicts = ['invalid-source', 'unsupported-capability', 'missing-binding', 'unknown', 'supported'];
259
+ const reasons = { supported: 'supported', 'engine-build-unknown': 'unknown', 'source-mismatch': 'invalid-source',
260
+ 'source-admission-refused': 'invalid-source', 'retained-attachment-unsupported': 'unsupported-capability',
261
+ 'retained-mutation-unsupported': 'unsupported-capability', 'runtime-mode-unsupported': 'unsupported-capability',
262
+ 'binding-missing': 'missing-binding', 'analysis-unavailable': 'unknown', 'requirement-uninspectable': 'unknown' };
263
+ const canonical = value => Array.isArray(value) ? `[${value.map(canonical).join(',')}]` : object(value)
264
+ ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}` : JSON.stringify(value);
265
+ const diagnostic = value => fields(value, ['code', 'path', 'section']) && text(value.code) && text(value.section) && (value.path === null || text(value.path));
266
+ const sourceShape = value => fields(value, ['scenario_sha256', 'closure_sha256', 'files']) && hex(value.scenario_sha256, 64)
267
+ && hex(value.closure_sha256, 64) && Array.isArray(value.files) && value.files.length <= 10000
268
+ && value.files.every((file, index, files) => fields(file, ['path', 'sha256']) && text(file.path) && hex(file.sha256, 64)
269
+ && (!index || files[index - 1].path < file.path));
270
+
271
+ function capabilityRow(row, edge) {
272
+ if (!fields(row, ['selection', 'feature', 'binding_kind', 'resource_mode', 'evaluator_mode', 'execution_mode', 'verdict', 'reason_code'])
273
+ || !fields(row.selection, ['step_id', 'node_id', 'prompt_path', 'operation', ...(edge ? ['edge'] : [])])
274
+ || !['step_id', 'node_id', 'prompt_path', 'operation'].every(key => text(row.selection[key]) && row.selection[key].length)
275
+ || !['ordinary', 'constructor-retained-read', 'method-attachment', 'retained-mutation', 'uninspectable'].includes(row.feature)
276
+ || !['none', 'internal', 'fixture', 'prompt', 'live', 'missing'].includes(row.binding_kind)
277
+ || !['simulated', 'live'].includes(row.resource_mode) || !text(row.evaluator_mode)
278
+ || !['ordinary', 'checkpoint', 'resume'].includes(row.execution_mode)
279
+ || !text(row.reason_code) || !Object.hasOwn(reasons, row.reason_code) || reasons[row.reason_code] !== row.verdict) return false;
280
+ if (!edge) return row.binding_kind === 'none';
281
+ const e = row.selection.edge;
282
+ if (!fields(e, ['edge_id', 'kind', 'call_operation', 'target_node_id', 'target_path', 'target_operation', 'resource_operation'])
283
+ || !Object.values(e).every(text) || !e.edge_id || !e.call_operation || !['internal', 'resource'].includes(e.kind)
284
+ || row.binding_kind === 'none') return false;
285
+ const targets = [e.target_node_id, e.target_path, e.target_operation];
286
+ return (targets.every(Boolean) || targets.every(value => value === '')) && (e.kind === 'internal'
287
+ ? targets.every(Boolean) && e.resource_operation === '' && row.binding_kind === 'internal'
288
+ : !!e.resource_operation && row.binding_kind !== 'internal');
289
+ }
290
+
291
+ function reportShape(report) {
292
+ if (!fields(report, ['schema_version', 'capability_version', 'engine_build', 'source', 'complete', 'verdict', 'operations', 'edges', 'diagnostics', 'provider_calls', 'resource_calls'])
293
+ || report.schema_version !== 'prompt-runtime.program-capabilities.v1' || !text(report.capability_version) || !text(report.engine_build)
294
+ || typeof report.complete !== 'boolean' || !verdicts.includes(report.verdict) || report.provider_calls !== 0 || report.resource_calls !== 0
295
+ || report.source !== null && !sourceShape(report.source)
296
+ || !Array.isArray(report.operations) || !Array.isArray(report.edges) || report.operations.length + report.edges.length > 10000
297
+ || !Array.isArray(report.diagnostics) || report.diagnostics.length > 10002 || !report.diagnostics.every(diagnostic)
298
+ || !report.operations.every(row => capabilityRow(row, false)) || !report.edges.every(row => capabilityRow(row, true))
299
+ || report.complete && (!report.source || !report.operations.length)) return false;
300
+ return true;
301
+ }
302
+
303
+ function reportConsistent(report) {
304
+ const nodes = new Map(report.operations.map(row => [canonical([row.selection.step_id, row.selection.node_id]), row.selection]));
305
+ for (const row of report.edges) {
306
+ const s = row.selection, e = s.edge;
307
+ for (const [node, path, operation] of [[s.node_id, s.prompt_path, s.operation], [e.target_node_id, e.target_path, e.target_operation]]) {
308
+ const target = nodes.get(canonical([s.step_id, node]));
309
+ if (node && !target && report.complete || target && (target.prompt_path !== path || target.operation !== operation)) return false;
310
+ }
311
+ }
312
+ // Validate reported aggregate consistency, without discovering features or applying the engine's mode policy.
313
+ const classes = new Set([...report.operations, ...report.edges].map(row => row.verdict));
314
+ if (!report.complete) classes.add('unknown');
315
+ if (report.diagnostics.some(item => item.code === 'source-mismatch')) classes.add('invalid-source');
316
+ if (report.engine_build === 'unknown') return report.capability_version === 'unknown' && report.verdict === 'unknown'
317
+ && [...report.operations, ...report.edges].every(row => row.verdict === 'unknown' && row.reason_code === 'engine-build-unknown');
318
+ return report.verdict === (verdicts.find(verdict => classes.has(verdict)) ?? 'unknown');
319
+ }
320
+
321
+ function selectedCompatibility(answer, test, sourceFiles) {
322
+ const result = answer?.result, top = objects(result?.capabilities).filter(item => item.path === test).map(item => item.report);
323
+ const legacy = objects(result?.report?.lint?.tests).filter(item => item.path === test && Object.hasOwn(item, 'capabilities')).map(item => item.capabilities);
324
+ const reports = [...top, ...legacy], report = reports[0];
325
+ const unknown = (issue, reported = null, association = 'unknown') => ({ reported, state: 'unknown', association, issue });
326
+ const unavailable = value => {
327
+ const metadata = object(value) ? Object.fromEntries(['schema_version', 'engine_build', 'capability_version'].filter(key => text(value[key])).map(key => [key, value[key]])) : {};
328
+ if (typeof value?.complete === 'boolean') metadata.complete = value.complete;
329
+ if (sourceShape(value?.source)) metadata.source = structuredClone(value.source);
330
+ if (Array.isArray(value?.diagnostics)) metadata.diagnostics = structuredClone(value.diagnostics.filter(diagnostic).slice(0, 10002));
331
+ return unknown('capability-report-unavailable', Object.keys(metadata).length ? metadata : null);
332
+ };
333
+ if (!reports.length) return unavailable(null);
334
+ // Validate the closed, fixed-depth wire shape before cloning or comparing it.
335
+ // Unexpected fields and malformed identities can contain arbitrarily nested JSON.
336
+ const malformed = reports.findIndex(value => !reportShape(value));
337
+ if (malformed !== -1) return unavailable(reports[malformed]);
338
+ if (reports.some(value => canonical(value) !== canonical(report))) return unknown('capability-report-conflict');
339
+ for (const [name, key] of [['operations', row => [row.selection.step_id, row.selection.node_id]], ['edges', row => [row.selection.step_id, row.selection.edge.edge_id]]]) {
340
+ if (new Set(report[name].map(row => canonical(key(row)))).size !== report[name].length)
341
+ return unknown('capability-report-conflict');
342
+ }
343
+ if (!reportConsistent(report)) return unavailable(report);
344
+ const reported = structuredClone(report);
345
+ const knownBuild = hex(report.engine_build, 40), knownJob = hex(answer?.engine_sha, 40);
346
+ let mismatch = knownBuild && knownJob && report.engine_build !== answer.engine_sha;
347
+ mismatch ||= knownBuild && report.capability_version !== `program-capabilities.v1@${report.engine_build}`;
348
+ const filesValid = Array.isArray(sourceFiles) && sourceFiles.every(file => object(file) && text(file.path) && hex(file.sha256, 64))
349
+ && new Set(sourceFiles.map(file => file.path)).size === sourceFiles.length;
350
+ const files = new Map(filesValid ? sourceFiles.map(file => [file.path, file.sha256]) : []);
351
+ if (filesValid && report.source) {
352
+ mismatch ||= files.has(test) && report.source.scenario_sha256 !== files.get(test);
353
+ mismatch ||= report.source.files.some(file => !files.has(file.path) || files.get(file.path) !== file.sha256);
354
+ }
355
+ if (mismatch) return unknown('capability-association-mismatch', reported, 'mismatch');
356
+ if (!knownBuild || !knownJob || !filesValid || !files.has(test) || !report.source)
357
+ return unknown('capability-association-unavailable', reported);
358
+ return { reported, state: report.verdict, association: 'matched', issue: null };
359
+ }
360
+
361
+ function progressFrom(value) {
362
+ const progress = {};
363
+ for (const key of ['steps_done', 'steps_total', 'calls_settled', 'calls_open']) if (count(value?.[key])) progress[key] = value[key];
364
+ if (Number.isSafeInteger(value?.step) && value.step >= 1 || typeof value?.step === 'string' && value.step.trim()) progress.step = value.step;
365
+ return progress;
366
+ }
367
+
368
+ // An open call has no settled result yet; it can stay open until the check ends, so it is never shown as live traffic.
369
+ const callWords = (settled, open) => [...(count(settled) ? [`${settled} AI call${settled === 1 ? '' : 's'} so far`] : []), ...(open > 0 ? [`${open} not yet settled`] : [])];
370
+
371
+ // Module function: the words for an outcome, or for a saved row that carries its outcome fields.
372
+ export function outcomeText(outcome) {
373
+ const { state, reason } = resultOutcome(outcome);
374
+ const p = outcome.progress ?? {};
375
+ 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
+ const step = number ? `step ${number}${count(p.steps_total) ? ` of ${p.steps_total}` : ''}` : typeof p.step === 'string' ? p.step : null;
377
+ return [state + (reason ? ` (${reason.code})` : ''), ...(count(outcome.ahead) ? [`${outcome.ahead} ahead`] : []),
378
+ ...(step ? [step + (number && typeof p.step === 'string' ? ` (${p.step})` : '')] : []), ...callWords(p.calls_settled, p.calls_open)].join(' · ');
379
+ }
380
+
381
+ export const hasProgress = outcome => ['running', 'sent'].includes(outcome.state) && Object.keys(outcome.progress ?? {}).length > 0;
382
+
383
+ // Module function: one progress fragment for a group of rows; null when no row has server progress.
384
+ // One row keeps its step; several rows add up the counts they report.
385
+ export function progressText(outcomes) {
386
+ const moving = outcomes.filter(hasProgress);
387
+ if (moving.length < 2) return moving.length ? outcomeText(moving[0]) : null;
388
+ const reported = key => moving.filter(outcome => count(outcome.progress[key]));
389
+ const sum = key => reported(key).reduce((total, outcome) => total + outcome.progress[key], 0);
390
+ return ['sent (awaiting-server-verdict)', ...callWords(reported('calls_settled').length ? sum('calls_settled') : undefined, sum('calls_open'))].join(' · ');
391
+ }
392
+
393
+ export const outcomeDone = outcome => TERMINAL.has(outcome.state) || outcome.state === 'not run';
394
+
395
+ // Module function: the state that decides a group's result.
396
+ export function outcomeOverall(outcomes, { interrupted = false, lintUnknown = false } = {}) {
397
+ if (interrupted || lintUnknown || !outcomes.length || outcomes.some(outcome => outcome.state === 'partial')) return 'unknown';
398
+ const present = new Set(outcomes.map(outcome => outcomeDone(outcome) ? outcome.state === 'not run' ? 'not_run' : outcome.state : 'unknown'));
399
+ return DECIDES.find(state => present.has(state));
400
+ }
401
+
402
+ // Public aggregate keeps the deciding row's explanation, not a raw job's label.
403
+ export function resultOverall(outcomes, options) {
404
+ const state = outcomeOverall(outcomes, options);
405
+ const row = outcomes.find(row => (outcomeDone(row) ? row.state === 'not run' ? 'not_run' : row.state : 'unknown') === state);
406
+ return resultOutcome(row ?? { state });
407
+ }