Files
callstack__agent-device/scripts/help-conformance-runner-output.mjs
Michał Pierzchała 250e30a578 test(bench): falsification fixtures for oracles + typed runner outcomes (#1893)
* test(bench): falsification fixtures for oracles + typed runner outcomes

Two deterministic PR-time quality gates for the help-conformance bench
(the repo's single non-gating small-model planning oracle):

- Every EXPECTATION_SCORERS entry in help-conformance-case-checks.mjs
  now has a falsification fixture (a minimal passing witness plus at
  least one known-bad counterexample, and a metamorphic variant where
  useful) in the new help-conformance-expectation-fixtures.ts, run
  through the real validatePlanCommands/scoreExpectations pipeline.
  help-conformance-expectation-falsification.test.ts is the "what
  enumerates N" completeness gate: a new named expectation with no
  fixture fails it. Counterexamples cover swallowed lifecycle command
  prefixes, unsupported flags/selectors, pseudo refs, shell operators,
  and invalid positional ordering.

- help-conformance-runner-output.mjs now returns a discriminated
  RunnerOutcome ({kind:'success',commands}|{kind:'runner-error',
  message,reason}) instead of a raw-string success inference. Only a
  'success' outcome ever reaches validatePlanCommands/scoreExpectations
  in runCase, so a runner-error result can no longer also carry
  model-validation checks, and an all-runner-error aggregate now
  reports passRate: null (rendered as "N/A") instead of "0/0 (0%)".

Fixes #1481

* refactor(bench): dedupe RunnerOutcome construction, drop leftover narrowing

Thermo-nuclear pass over 4b2df0a38's diff:

- help-conformance-bench.mjs's runOutcome() catch block was hand-building
  the exact {kind:'runner-error', raw, message, reason} shape that
  runner-output.mjs's private runnerError() helper already constructs for
  its own two error paths. Export it as runnerErrorOutcome so the
  discriminated union has exactly one constructor for its error variant,
  reused by both error sources instead of duplicated.
- runCase's two return branches repeated the same
  {runner, caseId, trial, outputPath} fields; pulled into a shared `base`
  object.
- Reverted bench.test.ts's rateLimitedOutcome block: it had an explicit
  `: RunnerOutcome` annotation and an if/throw narrowing guard, added only
  to give fallow's dead-code checker a "real consumer" of the type before
  the actual fix (adding the .d.mts to .fallowrc.json's ignorePatterns,
  matching the existing sample-outputs.d.mts precedent) was found. That
  workaround is now unnecessary scaffolding — replaced with the same
  flat assert.deepEqual style the surrounding assertions already use.
2026-08-20 12:52:42 +02:00

93 lines
3.0 KiB
JavaScript

// Discriminated runner outcome (see the companion .d.mts): a raw-string
// success/error split let infrastructure noise (an empty codex payload, a
// Claude is_error envelope) parse as if it were a command plan. Only a
// 'success' outcome carries `commands`, so a caller cannot accidentally score
// a runner-error's raw text against the command validator or expectations.
export function classifyRunnerOutput(raw) {
if (raw.trim().length === 0) {
return runnerErrorOutcome(raw, 'Runner returned empty output.', 'empty-output');
}
const payload = parseJsonEnvelope(raw);
if (isErrorPayload(payload)) {
return runnerErrorOutcome(raw, errorPayloadMessage(payload), 'error-envelope');
}
return { kind: 'success', raw, commands: extractCommands(raw) };
}
export function extractCommands(raw) {
const json = parseJsonPayload(raw);
if (json && Array.isArray(json.commands)) {
return json.commands.map((command) => String(command).trim()).filter(Boolean);
}
return raw
.split('\n')
.map((line) => line.replace(/^[-*\d.]+\s*/, '').trim())
.filter(
(line) =>
line.startsWith('agent-device ') || line.match(/^(open|snapshot|press|fill|click|close)\b/),
);
}
// The RunnerOutcome union's only 'runner-error' constructor: every caller
// that classifies a runner failure (a bad envelope here, a spawn/timeout
// failure in help-conformance-bench.mjs) builds the outcome through this one
// function, so the shape can't drift between the two error sources.
export function runnerErrorOutcome(raw, message, reason) {
return { kind: 'runner-error', raw, message, reason };
}
function isErrorPayload(payload) {
if (!payload || typeof payload !== 'object') return false;
if (Array.isArray(payload.commands)) return false;
return payload.is_error === true || payload.type === 'error' || payload.status === 'failed';
}
function errorPayloadMessage(payload) {
const nestedError = payload.error;
const candidates = [
payload.result,
payload.message,
typeof nestedError === 'object' && nestedError ? nestedError.message : nestedError,
];
return (
candidates.find((value) => typeof value === 'string' && value.trim().length > 0) ??
'Runner returned an error payload.'
);
}
function parseJsonPayload(raw) {
for (const candidate of jsonPayloadCandidates(raw)) {
const parsed = parseJsonCandidate(candidate);
if (parsed !== undefined) return normalizeParsedJson(parsed);
}
return null;
}
function parseJsonEnvelope(raw) {
for (const candidate of jsonPayloadCandidates(raw)) {
const parsed = parseJsonCandidate(candidate);
if (parsed !== undefined) return parsed;
}
return null;
}
function jsonPayloadCandidates(raw) {
return [raw, raw.match(/```json\s*([\s\S]*?)```/)?.[1], raw.match(/\{[\s\S]*\}/)?.[0]].filter(
Boolean,
);
}
function parseJsonCandidate(candidate) {
try {
return JSON.parse(candidate);
} catch {
return undefined;
}
}
function normalizeParsedJson(parsed) {
if (typeof parsed?.result === 'string') return parseJsonPayload(parsed.result);
return parsed;
}