Files
PaperClipAI/packages/paperclip-runner/scripts/render-runner-workflow-evalbook.mjs
T
Dotta af8439a70b feat(runner): restore direct live eval campaigns and reports (#12909)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Runner executes agents through native and managed provider
drivers.
> - The direct live eval layer had drifted from the current Runner
contracts.
> - The old local workflow did not provide a complete parallel campaign
or durable report history.
> - The Runner also needed current native OpenCode and OpenRouter
qualification.
> - This pull request restores the direct campaign, corrects the runtime
gaps that the campaign found, and adds safe hosted Evalbook history.
> - The benefit is repeatable model comparison against an immutable
Runner and eval source revision.

## Linked Issues or Issue Description

Refs #11297
Refs #11634

**What existing behavior does this improve?**

This improves the direct live `paperclip-runner` eval workflow, provider
execution contract, and static Evalbook reporting path.

**Current behavior**

The direct evals do not have one maintained full campaign on current
`master`. OpenCode has no qualified multi-model OpenRouter roster.
Parallel provider bursts can compact committed events before the
transport observes them. Local reports do not have a separate safe S3
history index.

**Proposed behavior**

Run one immutable roster-plus-case matrix. Use the shared paid AWS
runner fleet. Keep raw artifacts access-controlled. Publish a sanitized
canonical Evalbook report under the separate `runner-protocol-evals` S3
prefix. Keep immutable campaign directories plus root history, latest,
and latest-green pointers.

**Reason and benefit**

Maintainers can compare native Codex, native OpenCode, ACPX, Claude
Managed, and AWS AgentCore behavior over time. They can inspect failures
without mixing this direct protocol layer with browser full-stack E2E.

**Breaking changes**

None. The new workflow and S3 prefix are additive. The existing Runner
full-stack E2E workflow and report remain separate.

## What Changed

- Added a trusted two-shard direct live workflow for up to 393
roster-plus-case cells.
- Reused the numeric actor allowlist, protected paid environment, and
RunsOn fleet controls from Runner full-stack E2E.
- Added immutable Runner and eval revision resolution, exact credential
boundaries, bounded retries, and cost ceilings.
- Added a public report projection that removes sessions, transcripts,
tool payloads, state, traces, raw failures, remote profile identities,
and credential-shaped values.
- Added additive S3 history under `runner-protocol-evals`, with
immutable campaigns and mutable root index pointers.
- Added native OpenCode model injection and current OpenRouter pricing
contracts.
- Fixed direct eval completion, workflow execution, semantic discovery,
warm-attach state reset, executable binding, and event-burst handling.
- Kept Runner browser full-stack E2E behavior and publication separate.
- Documented local and hosted direct eval operation.

## Verification

- `pnpm --filter @paperclipai/paperclip-runner
test:runner-protocol-eval-publish` — 15 passed.
- `pnpm --filter @paperclipai/paperclip-runner build:typescript` —
passed.
- `actionlint .github/workflows/runner-protocol-live-evals.yml
.github/workflows/runner-full-stack-e2e.yml` — passed.
- Local current matrix at the revision in
[paperclip-evals#17](https://github.com/paperclipai/paperclip-evals/pull/17)
— 323 cells across 10 enabled configurations completed.
- Final local current matrix — 269 passed, 11 behavior failures, and 43
expected macOS-only ACPX platform failures.
- Targeted Runner checks — 13/13 eval-session tests, 15/15
publisher/security tests, and package typecheck passed; complete PR CI
is green, including all browser E2E shards.

## Risks

- Paid live campaigns can consume provider budget. Actor authorization,
exact per-cell ceilings, protected environments, and explicit schedule
enablement bound this risk.
- Public reports can leak provider data. The workflow publishes only a
separately projected report and validates every file before upload.
- The new workflow cannot publish until it is present on the default
branch. This pull request does not change the existing
`runner-full-stack-e2e` publication path.
- The campaign is large. It uses two GitHub matrices and caps combined
concurrency at the shared fleet limit.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex on GPT-5. The exact deployment ID and context-window size
are not exposed. The model used reasoning, code editing, browser
inspection, repository tools, and live provider execution.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-09-05 20:18:11 -05:00

353 lines
11 KiB
JavaScript

import { createHash } from "node:crypto";
import { spawn } from "node:child_process";
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
const EVAL_PROGRAM_RELATIVE_PATH =
"evals/paperclip-runner/tools/eval_program.py";
function json(value) {
return `${JSON.stringify(value, null, 2)}\n`;
}
function sha256(value) {
return createHash("sha256").update(value).digest("hex");
}
function safeSegment(value) {
const segment = String(value)
.trim()
.replaceAll(/[^0-9A-Za-z._-]+/g, "-")
.replaceAll(/^-+|-+$/g, "");
if (!segment) throw new Error("Evalbook attempt identity is empty");
return segment;
}
function candidateDescriptor(report, candidateId) {
const descriptor =
report.bundle.providerVersions?.[candidateId] ?? candidateId;
const separator = descriptor.indexOf(":");
return separator < 0
? { driver: "unknown driver", model: descriptor }
: {
driver: descriptor.slice(0, separator),
model: descriptor.slice(separator + 1),
};
}
function scoreChecks(result) {
const dimensionChecks = Object.values(result.scorecard.dimensions).map(
(dimension) => ({
id: dimension.dimension,
kind: "workflow_dimension",
passed: dimension.passed === true,
detail:
dimension.score === null
? dimension.reasons.join("; ") || "not scored"
: `score ${dimension.score}${
dimension.reasons.length === 0
? ""
: `; ${dimension.reasons.join("; ")}`
}`,
evidenceRefs: [],
}),
);
const observationChecks = [
["lifecycle", result.observation.lifecycle?.checks ?? []],
["continuation", result.observation.continuation?.checks ?? []],
["presentation", result.observation.presentation?.checks ?? []],
].flatMap(([group, checks]) =>
checks.map((check) => ({
id: `${group}.${check.id}`,
kind: `${group}_check`,
passed: check.passed === true,
detail: check.reason ?? (check.passed ? "passed" : "failed"),
evidenceRefs: [],
})),
);
return [...dimensionChecks, ...observationChecks];
}
function disposition(result) {
if (result.scorecard.overall.passed === true) return "passed";
if (
result.observation.classification === "infrastructure_failure" ||
result.observation.classification === "skipped"
) {
return "infrastructure_failure";
}
return "behavior_failure";
}
function infrastructureErrors(result) {
if (disposition(result) !== "infrastructure_failure") return [];
return [
result.observation.failure?.message ??
`workflow execution was ${result.observation.classification}`,
];
}
export function runnerWorkflowEvalbookAttempt({
report,
result,
caseDefinition,
}) {
const { driver, model } = candidateDescriptor(report, result.candidateId);
const identity = {
generatedAt: report.generatedAt,
bundleId: report.bundle.id,
caseId: result.scenarioId,
candidateId: result.candidateId,
};
const timestamp = safeSegment(report.generatedAt);
const attemptId = `${timestamp}-${safeSegment(result.scenarioId)}-${safeSegment(
result.candidateId,
)}-${sha256(JSON.stringify(identity)).slice(0, 10)}`;
const checks = scoreChecks(result);
const costUsd = result.observation.metrics.costUsd;
const infrastructure =
disposition(result) === "infrastructure_failure"
? result.observation.failure
: undefined;
const artifact = {
schema: "paperclip-runner/workflow-eval-artifact/v1",
attemptId,
createdAt: report.generatedAt,
requestedModel: model,
provider: result.observation.provider,
driver,
providerVersion:
report.bundle.runnerBuild ?? report.bundle.runnerVersion ?? "unknown",
providerSessionId: result.observation.base.trace.sessionId,
retainedSession: false,
retainedSessionStatus: "not retained by safe workflow eval projection",
usage: {
agentTurns: result.observation.metrics.attempts,
inputTokens: result.observation.metrics.totalTokens,
cachedInputTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
...(costUsd === undefined
? {}
: { estimatedCostNanodollars: Math.round(costUsd * 1_000_000_000) }),
},
turn: {
status:
result.observation.classification === "completed"
? "completed"
: "failed",
},
snapshot: {
createdAt: report.generatedAt,
providerModel: {
id: model,
provider: result.observation.provider,
},
transcript: [],
evidence: [],
},
devtools: { revisions: [] },
...(infrastructure === undefined
? {}
: {
infrastructureFailure: {
class: infrastructure.code,
category: infrastructure.category,
retryable: infrastructure.retryable,
},
}),
workflow: {
bundle: report.bundle,
observation: result.observation,
scorecard: result.scorecard,
},
};
const score = {
schema: "paperclip-runner/eval-score/v1",
attemptId,
caseId: result.scenarioId,
checks,
disposition: disposition(result),
infrastructureErrors: infrastructureErrors(result),
passed: result.scorecard.overall.passed === true,
digest: `sha256:${sha256(JSON.stringify({ identity, checks }))}`,
};
const evalCase = {
schema: "paperclip-runner/workflow-eval-case/v1",
id: result.scenarioId,
title: caseDefinition?.title ?? result.scenarioId,
description: caseDefinition
? `Runner workflow case. Tags: ${caseDefinition.tags.join(", ")}.`
: "Runner workflow case.",
prompt:
"Redacted by the safe Runner workflow eval projection; inspect the authored workflow case for orchestration steps.",
fixture: "runner-workflow-live-harness",
authority: {
controlPlaneOwned: result.observation.base.controlPlaneOwned,
},
checks: Object.entries(caseDefinition?.assertions ?? {}).map(
([id, expected]) => ({
id,
kind: "workflow_assertion",
expected,
}),
),
...(caseDefinition === undefined
? {}
: { workflowDefinition: caseDefinition }),
};
const config = {
schema: "paperclip-runner/workflow-eval-config/v1",
id: result.candidateId,
model,
provider: result.observation.provider,
driver,
runnerVersion: report.bundle.runnerVersion,
runnerBuild: report.bundle.runnerBuild,
promptPolicyId: report.bundle.promptPolicyId,
};
return { attemptId, artifact, score, case: evalCase, config };
}
async function writeImmutable(path, value) {
const content = json(value);
try {
const existing = await readFile(path, "utf8");
if (existing !== content) {
throw new Error(`Immutable Evalbook record changed: ${path}`);
}
} catch (error) {
if (error?.code !== "ENOENT") throw error;
await writeFile(path, content, { flag: "wx", mode: 0o600 });
}
}
export async function writeRunnerWorkflowEvalbookAttempts({
report,
runsRoot,
caseForId,
}) {
await mkdir(runsRoot, { recursive: true });
const attempts = [];
for (const result of report.results) {
const attempt = runnerWorkflowEvalbookAttempt({
report,
result,
caseDefinition: caseForId?.(result.scenarioId),
});
const directory = resolve(runsRoot, attempt.attemptId);
await mkdir(directory, { recursive: true, mode: 0o700 });
await Promise.all([
writeImmutable(resolve(directory, "artifact.json"), attempt.artifact),
writeImmutable(resolve(directory, "score.json"), attempt.score),
writeImmutable(resolve(directory, "case.json"), attempt.case),
writeImmutable(resolve(directory, "config.json"), attempt.config),
]);
attempts.push(attempt.attemptId);
}
return attempts;
}
async function existingPath(paths) {
for (const path of paths.filter(Boolean)) {
try {
await access(path);
return resolve(path);
} catch {
// Continue through the explicit and conventional checkout locations.
}
}
return null;
}
export async function resolveCanonicalEvalProgram(packageRoot, environment) {
const fromRoot = environment.PAPERCLIP_EVALS_ROOT
? resolve(environment.PAPERCLIP_EVALS_ROOT, EVAL_PROGRAM_RELATIVE_PATH)
: null;
const program = await existingPath([
environment.PAPERCLIP_EVALBOOK_PROGRAM,
fromRoot,
resolve(packageRoot, "../../.paperclip-evals", EVAL_PROGRAM_RELATIVE_PATH),
resolve(
packageRoot,
"../../../paperclip-evals",
EVAL_PROGRAM_RELATIVE_PATH,
),
resolve(
packageRoot,
"../../../../paperclip-evals",
EVAL_PROGRAM_RELATIVE_PATH,
),
]);
if (program !== null) return program;
throw new Error(
`Canonical Evalbook generator not found. Set PAPERCLIP_EVALBOOK_PROGRAM to ${EVAL_PROGRAM_RELATIVE_PATH} in a paperclip-evals checkout.`,
);
}
async function run(command, args) {
await new Promise((accept, reject) => {
const child = spawn(command, args, { stdio: "inherit" });
child.once("error", reject);
child.once("exit", (code, signal) => {
if (code === 0) accept();
else
reject(
new Error(
`${command} exited ${code ?? `for signal ${signal ?? "unknown"}`}`,
),
);
});
});
}
export async function renderRunnerWorkflowWithCanonicalEvalbook({
packageRoot,
outputDirectory,
report,
caseForId,
environment = process.env,
}) {
const program = await resolveCanonicalEvalProgram(packageRoot, environment);
const runsRoot = resolve(outputDirectory, "evalbook-runs");
await rm(runsRoot, { recursive: true, force: true });
const attempts = await writeRunnerWorkflowEvalbookAttempts({
report,
runsRoot,
caseForId,
});
await Promise.all([
rm(resolve(outputDirectory, "attempts"), { recursive: true, force: true }),
rm(resolve(outputDirectory, "tests"), { recursive: true, force: true }),
rm(resolve(outputDirectory, "index.html"), { force: true }),
rm(resolve(outputDirectory, "latest.html"), { force: true }),
rm(resolve(outputDirectory, "live-report.html"), { force: true }),
rm(resolve(outputDirectory, "deterministic-report.html"), { force: true }),
]);
await run(environment.PYTHON ?? "python3", [
program,
"report",
"--runs-root",
runsRoot,
"--output",
outputDirectory,
]);
const programBytes = await readFile(program);
const manifest = {
schema: "paperclip.runner.workflow-evalbook-render.v1",
generatedAt: report.generatedAt,
generator: {
path: program,
sha256: `sha256:${sha256(programBytes)}`,
},
sourceReport: "live-report.json",
attempts,
index: resolve(outputDirectory, "index.html"),
};
await writeFile(
resolve(outputDirectory, "evalbook-manifest.json"),
json(manifest),
);
return manifest;
}