From fb6eaab87cdb5ed0b4e667854a2a833730a1ce3b Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Sun, 29 Nov 2026 23:06:02 +0000 Subject: [PATCH 1/3] feat(evals): add approved evaluation workflow and TLA model --- .github/workflows/agent-evals.yml | 89 ++++++++ .github/workflows/code-qa.yml | 2 + .../tla/EvalWorkflow.NoApproval.cfg | 9 + .../tla/EvalWorkflow.NoCandidate.cfg | 9 + docs/architecture/tla/EvalWorkflow.NoHead.cfg | 9 + .../tla/EvalWorkflow.NoReport.cfg | 9 + .../tla/EvalWorkflow.NoTrigger.cfg | 9 + docs/architecture/tla/EvalWorkflow.cfg | 9 + docs/architecture/tla/EvalWorkflow.tla | 90 ++++++++ docs/architecture/tla/EvalWorkflowMC.tla | 14 ++ scripts/agent-evals-summary.sh | 53 +++++ scripts/agent-evals-workflow.test.mjs | 202 ++++++++++++++++++ scripts/agent-evals/README.md | 53 +++++ 13 files changed, 557 insertions(+) create mode 100644 .github/workflows/agent-evals.yml create mode 100644 docs/architecture/tla/EvalWorkflow.NoApproval.cfg create mode 100644 docs/architecture/tla/EvalWorkflow.NoCandidate.cfg create mode 100644 docs/architecture/tla/EvalWorkflow.NoHead.cfg create mode 100644 docs/architecture/tla/EvalWorkflow.NoReport.cfg create mode 100644 docs/architecture/tla/EvalWorkflow.NoTrigger.cfg create mode 100644 docs/architecture/tla/EvalWorkflow.cfg create mode 100644 docs/architecture/tla/EvalWorkflow.tla create mode 100644 docs/architecture/tla/EvalWorkflowMC.tla create mode 100644 scripts/agent-evals-summary.sh create mode 100644 scripts/agent-evals-workflow.test.mjs diff --git a/.github/workflows/agent-evals.yml b/.github/workflows/agent-evals.yml new file mode 100644 index 00000000000..ad6e623d0ab --- /dev/null +++ b/.github/workflows/agent-evals.yml @@ -0,0 +1,89 @@ +name: Coding task evaluations + +# First stage of #2085. Candidate results only. No baseline promotion or publishing. +# Trust boundaries: docs/architecture/tla/EvalWorkflow.tla. +on: + workflow_dispatch: + # Temporary live validation before merge. Remove this trigger before merging. + push: + branches: [issue/2085] + +permissions: + contents: read + +concurrency: + group: agent-evals + cancel-in-progress: false + +jobs: + evaluate: + # Remove the branch exception after the approved validation run. + if: (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || (github.event_name == 'push' && github.ref == 'refs/heads/issue/2085') + runs-on: ubuntu-24.04 + timeout-minutes: 120 + environment: final-vscode-review-smoke + steps: + - name: Checkout exact approved revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Setup Node.js and pnpm + uses: ./.github/actions/setup-node-pnpm + with: + install-args: "--frozen-lockfile" + + - name: Install display dependencies + timeout-minutes: 5 + run: sudo apt-get update && sudo apt-get install -y xvfb libasound2t64 + + - name: Prepare trust policy + env: + CANDIDATE_SHA: ${{ github.sha }} + TRUST_FILE: ${{ runner.temp }}/agent-evals-trust.json + run: | + set -euo pipefail + docker info > /dev/null + node --import tsx --input-type=module -e ' + import { safeWriteJson } from "./src/utils/safeWriteJson.ts"; + const sha = process.env.CANDIDATE_SHA; + if (!/^[0-9a-f]{40}$/.test(sha ?? "")) throw new Error("Invalid candidate SHA"); + await safeWriteJson(process.env.TRUST_FILE, { version: 1, approvedCommits: [sha] }); + ' + + # The side builds its own isolated worktree. Do not build a second copy here. + - name: Evaluate candidate + id: candidate + timeout-minutes: 105 + env: + SOLHEIM_API_KEY: ${{ secrets.FINAL_SMOKE_OPENAI_API_KEY }} + CODING_EVALS_SIDE: candidate + CANDIDATE_SHA: ${{ github.sha }} + TRUST_FILE: ${{ runner.temp }}/agent-evals-trust.json + EVAL_OUT: ${{ runner.temp }}/agent-evals + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain --untracked-files=all)" + xvfb-run -a -s "-screen 0 1280x720x24 -nolisten tcp" \ + pnpm coding-evals:side --reps 3 --trust-file "$TRUST_FILE" --out "$EVAL_OUT" + + - name: Write candidate summary + if: ${{ !cancelled() && (steps.candidate.outcome == 'success' || steps.candidate.outcome == 'failure') }} + env: + CANDIDATE_SHA: ${{ github.sha }} + EVAL_OUT: ${{ runner.temp }}/agent-evals + run: bash scripts/agent-evals-summary.sh + + - name: Upload candidate results and traces + if: ${{ !cancelled() && (steps.candidate.outcome == 'success' || steps.candidate.outcome == 'failure') }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: agent-evals-${{ github.sha }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + ${{ runner.temp }}/agent-evals/side-results.json + ${{ runner.temp }}/agent-evals/candidate-report.md + ${{ runner.temp }}/agent-evals/artifacts + if-no-files-found: error + retention-days: 90 diff --git a/.github/workflows/code-qa.yml b/.github/workflows/code-qa.yml index a18ddd15e42..1a7eaf385ec 100644 --- a/.github/workflows/code-qa.yml +++ b/.github/workflows/code-qa.yml @@ -126,6 +126,8 @@ jobs: run: pnpm solheim-smoke:check-types - name: Test agent evals units run: pnpm test:agent-evals:unit + - name: Validate coding evaluation workflow + run: node --test scripts/agent-evals-workflow.test.mjs - name: Check agent evals types run: pnpm agent-evals:check-types - name: Model-check task lifecycle protocols diff --git a/docs/architecture/tla/EvalWorkflow.NoApproval.cfg b/docs/architecture/tla/EvalWorkflow.NoApproval.cfg new file mode 100644 index 00000000000..7008f7b7807 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoApproval.cfg @@ -0,0 +1,9 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Disabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg b/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg new file mode 100644 index 00000000000..d8055ab1f45 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg @@ -0,0 +1,9 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Disabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoHead.cfg b/docs/architecture/tla/EvalWorkflow.NoHead.cfg new file mode 100644 index 00000000000..a56a12813e3 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoHead.cfg @@ -0,0 +1,9 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Disabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoReport.cfg b/docs/architecture/tla/EvalWorkflow.NoReport.cfg new file mode 100644 index 00000000000..b78e0514682 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoReport.cfg @@ -0,0 +1,9 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Disabled +CONSTANT CheckHead <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg b/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg new file mode 100644 index 00000000000..e66082e0ace --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg @@ -0,0 +1,9 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Disabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.cfg b/docs/architecture/tla/EvalWorkflow.cfg new file mode 100644 index 00000000000..542b04408f1 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.cfg @@ -0,0 +1,9 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.tla b/docs/architecture/tla/EvalWorkflow.tla new file mode 100644 index 00000000000..fa48817597c --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.tla @@ -0,0 +1,90 @@ +---- MODULE EvalWorkflow ---- +\* Source: agent-evals.yml dispatch, evaluate.if, and environment approval. +\* Sink: Evaluate candidate starts coding-evals:side with the provider key. +\* Source: side-results.json and checkout HEAD after the candidate run. +\* Sink: agent-evals-summary.sh publishes candidate-report.md and the summary. +\* Failure: an unapproved event or ref can reach the provider job. +\* Failure: provider execution starts with a different commit or dirty tree. +\* Failure: incomplete or foreign results become an accepted summary. +\* Invariants: SecretsAuthorized, ExecutionTrusted, and SummaryBound. +\* Expect: current guards hold. Each removed guard violates an invariant. +\* Stance: implementation was read before these first invariants were written. +\* Scope: GitHub environment approval and side output validation are oracles. +\* Scope: payload kinds stand for valid JSON inputs and a missing result file. +\* Scope: artifact retention, cancellation, and hosted scheduling are outside the model. +\* Assumption: the named environment requires approval for main and issue/2085. +\* Limit: this model cannot inspect repository environment settings. +\* Limit: no local actor changes the tree between a shell guard and execution. +\* The isolated side runner checks its own worktree outside this model. +\* Property tests: scripts/agent-evals-workflow.test.mjs. +\* Review ratchet: 0 covered, 0 added, 0 gap. No review findings received. +\* Result: EvalWorkflow.cfg passes in 1760 distinct states. No new bug was found. +\* Controls: NoTrigger and NoApproval violate SecretsAuthorized. +\* Controls: NoCandidate violates ExecutionTrusted. NoHead and NoReport violate SummaryBound. +\* Replay: temporary workflow and shell guard removal fails the corresponding code tests. +\* Replay: NoApproval removes the environment declaration, not a hosted reviewer setting. +\* No live credential was used. No false alarm was found in the bounded code tests. +\* Gate before simplification: all six TLC configs and 23 code tests give the expected results. +\* Cost: about 8 agent minutes. Each TLC config completes in under 2 seconds. +\* Run: TLA_JAR= docs/architecture/tla/check.sh EvalWorkflow. +\* Run code tests: node --test scripts/agent-evals-workflow.test.mjs. +\* A model check covers this model. It does not prove the workflow correct. +\* Change: remove duplicate preparation checks. Keep the guard at provider execution. +\* Change: allow approved push runs on issue/2085 until live validation finishes. +\* Failure: another branch, main push, or a pull request reaches the provider job. +\* Expect: SecretsAuthorized covers the explicit branch exception. No new bug is expected. +\* Scope: one commit SHA is approved per run. Later branch pushes need new approval. +\* Remove the temporary trigger, branch rule, and model exception before merging. +\* Result after simplification: base passes in 2752 states. All five controls still fail. +\* Replay: each removed guard still fails the real workflow or summary code tests. +\* Gate: all 24 workflow tests and the evaluation type check pass. No new bug was found. +\* Gate: all 419 offline evaluation tests pass outside the child-process sandbox. +\* Cost: about 6 more agent minutes, including branch setup and model replay. +EXTENDS Naturals + +CONSTANTS Inputs, CheckTrigger, CheckApproval, CheckCandidate, CheckReport, CheckHead +VARIABLES input, stage +vars == <> + +AllowedTrigger == (input.event = "workflow_dispatch" /\ input.ref = "main") + \/ (input.event = "push" /\ input.ref = "issue/2085") +CandidateMatches == input.startMatches /\ input.clean +PayloadComplete == input.payload = "complete" + +Init == /\ input \in Inputs + /\ stage = "dispatch" + +Dispatch == /\ stage = "dispatch" + /\ stage' = IF ~CheckTrigger \/ AllowedTrigger THEN "waiting" ELSE "skipped" + /\ UNCHANGED input + +\* The GitHub environment is external. Denied approval never starts the job. +Authorize == /\ stage = "waiting" + /\ stage' = IF ~CheckApproval \/ input.approved THEN "ready" ELSE "denied" + /\ UNCHANGED input + +\* The shell gets the credential before it checks HEAD and the working tree. +Execute == /\ stage = "ready" + /\ stage' = IF ~CheckCandidate \/ CandidateMatches THEN "running" ELSE "guardRejected" + /\ UNCHANGED input + +\* Completion can leave no marker, invalid results, or a complete candidate. +Finish == /\ stage = "running" + /\ stage' = "result" + /\ UNCHANGED input + +Summarize == /\ stage = "result" + /\ stage' = IF (~CheckHead \/ input.endMatches) /\ (~CheckReport \/ PayloadComplete) + THEN "accepted" ELSE "summaryRejected" + /\ UNCHANGED input + +Next == Dispatch \/ Authorize \/ Execute \/ Finish \/ Summarize +Spec == Init /\ [][Next]_vars + +\* An invalid candidate can receive the step environment, but cannot execute. +SecretsAvailable == stage \in {"ready", "guardRejected", "running", "result", "accepted", "summaryRejected"} +ExecutionStarted == stage \in {"running", "result", "accepted", "summaryRejected"} +SecretsAuthorized == SecretsAvailable => (AllowedTrigger /\ input.approved) +ExecutionTrusted == ExecutionStarted => CandidateMatches +SummaryBound == stage = "accepted" => (PayloadComplete /\ input.endMatches) +==== diff --git a/docs/architecture/tla/EvalWorkflowMC.tla b/docs/architecture/tla/EvalWorkflowMC.tla new file mode 100644 index 00000000000..685cf2a7400 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflowMC.tla @@ -0,0 +1,14 @@ +---- MODULE EvalWorkflowMC ---- +\* One run covers trigger, approval, checkout changes, and result publication. +EXTENDS EvalWorkflow +Enabled == TRUE +Disabled == FALSE +MCInputs == [event : {"workflow_dispatch", "pull_request", "push"}, + ref : {"main", "issue/2085", "other"}, + approved : BOOLEAN, + startMatches : BOOLEAN, + clean : BOOLEAN, + endMatches : BOOLEAN, + payload : {"complete", "missing", "wrongCommit", "wrongSide", "wrongSuite", + "missingKeys", "duplicateKeys", "unknownOutcome"}] +==== diff --git a/scripts/agent-evals-summary.sh b/scripts/agent-evals-summary.sh new file mode 100644 index 00000000000..8f86e8a3a9d --- /dev/null +++ b/scripts/agent-evals-summary.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +set -euo pipefail + +: "${CANDIDATE_SHA:?}" +: "${EVAL_OUT:?}" +: "${GITHUB_STEP_SUMMARY:?}" + +# A side publishes this completion marker only after its full run finishes. +# Do not turn partial traces into a valid report. +# Source and sink model: docs/architecture/tla/EvalWorkflow.tla, SummaryBound. +report="$EVAL_OUT/side-results.json" +if ! test -f "$report"; then + echo 'Evaluation failed before it published complete results. Check the logs and available traces.' >> "$GITHUB_STEP_SUMMARY" + exit 1 +fi + +test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" +jq -e --arg sha "$CANDIDATE_SHA" ' + .pins.commit == $sha and .pins.side == "candidate" and + .pins.suiteId == "coding-basic-v1" and + (.runs | length == 15) and + ([.runs[].fixtureName] | unique | sort) == + ["clamp-range", "deep-get", "format-bytes", "parse-csv-line", "slugify-text"] and + ([.runs | group_by(.fixtureName)[] | ([.[].repIndex] | sort) == [0, 1, 2]] | all) and + ([.runs[].outcome.outcome | + . == "correct" or . == "incorrect" or . == "timed-out" or + . == "grading-failure" or . == "infrastructure-failure"] | all) +' "$report" > /dev/null + +# Only fixed fixture names, numeric values, and known outcomes enter Markdown. +# Arbitrary model output and failure messages stay out of the workflow summary. +summary="$EVAL_OUT/candidate-report.md" +{ + printf '# Coding task evaluation\n\nCandidate commit: `%s`\n\n' "$CANDIDATE_SHA" + printf 'Candidate results only. No approved baseline comparison is available.\n\n' + printf 'Results are advisory. This workflow does not publish a release or promote a baseline.\n\n' + printf '| Fixture | Correct | Incorrect | Timed out | Grading failure | Infrastructure failure |\n' + printf '| --- | --- | --- | --- | --- | --- |\n' + jq -r ' + .runs | group_by(.fixtureName)[] | + [.[0].fixtureName, + ([.[] | select(.outcome.outcome == "correct")] | length), + ([.[] | select(.outcome.outcome == "incorrect")] | length), + ([.[] | select(.outcome.outcome == "timed-out")] | length), + ([.[] | select(.outcome.outcome == "grading-failure")] | length), + ([.[] | select(.outcome.outcome == "infrastructure-failure")] | length)] | + "| " + (map(tostring) | join(" | ")) + " |" + ' "$report" + printf '\nEach fixture has three attempts. Small samples do not establish statistical significance.\n' + printf '\nToken use, tool calls, duration, accounting status, and cost availability are in side-results.json.\n' + printf '\nCost estimates remain unavailable until the price table contains maintained rates.\n' +} > "$summary" +cat "$summary" >> "$GITHUB_STEP_SUMMARY" diff --git a/scripts/agent-evals-workflow.test.mjs b/scripts/agent-evals-workflow.test.mjs new file mode 100644 index 00000000000..498b2eac519 --- /dev/null +++ b/scripts/agent-evals-workflow.test.mjs @@ -0,0 +1,202 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { spawnSync } from "node:child_process" +import { describe, it } from "node:test" +import { runInNewContext } from "node:vm" +import { parse } from "yaml" + +const workflow = parse(fs.readFileSync(new URL("../.github/workflows/agent-evals.yml", import.meta.url), "utf8")) +const job = workflow.jobs.evaluate +const candidate = job.steps.find((step) => step.id === "candidate") + +describe("coding evaluation workflow", () => { + // EvalWorkflow.SecretsAuthorized: only main dispatch or the temporary branch push can receive secrets. + it("accepts only the approved event and ref pairs in the bounded trigger domain", () => { + for (const event of ["workflow_dispatch", "pull_request", "pull_request_target", "push"]) { + for (const ref of ["refs/heads/main", "refs/heads/issue/2085", "refs/heads/feature", "refs/tags/v1.0.0"]) { + const allowed = runInNewContext(job.if, { github: { event_name: event, ref } }, { timeout: 1000 }) + const expected = + (event === "workflow_dispatch" && ref === "refs/heads/main") || + (event === "push" && ref === "refs/heads/issue/2085") + assert.equal(allowed, expected, `${event}: ${ref}`) + } + } + }) + + it("requires environment approval and read-only permissions for main and temporary branch runs", () => { + assert.deepEqual(workflow.on, { workflow_dispatch: null, push: { branches: ["issue/2085"] } }) + assert.deepEqual(Object.keys(workflow.jobs), ["evaluate"]) + assert.equal(job.environment, "final-vscode-review-smoke") + assert.deepEqual(workflow.permissions, { contents: "read" }) + assert.equal(job.permissions, undefined) + assert.equal(workflow.env, undefined) + assert.equal(job.env, undefined) + assert.equal(workflow.concurrency["cancel-in-progress"], false) + }) + + it("keeps preparation free of provider secrets and checks the checkout once before execution", () => { + const prepare = job.steps.find((step) => step.name === "Prepare trust policy") + assert.ok(prepare) + assert.ok(job.steps.indexOf(prepare) < job.steps.indexOf(candidate)) + assert.doesNotMatch(JSON.stringify(prepare), /secrets\.|SOLHEIM_API_KEY/) + assert.doesNotMatch(prepare.run, /git rev-parse|git status/) + assert.equal((candidate.run.match(/git rev-parse HEAD/g) ?? []).length, 1) + assert.equal((candidate.run.match(/git status/g) ?? []).length, 1) + }) + + it("pins checkout and actions, and restricts the secret to the bounded candidate step", () => { + const checkout = job.steps.find((step) => step.uses?.startsWith("actions/checkout@")) + assert.deepEqual(checkout.with, { ref: "${{ github.sha }}", "persist-credentials": false }) + for (const step of job.steps.filter((step) => step.uses && !step.uses.startsWith("./"))) { + assert.match(step.uses.split("@")[1], /^[0-9a-f]{40}$/) + } + const secrets = job.steps.filter((step) => JSON.stringify(step).includes("secrets.")) + assert.deepEqual(secrets, [candidate]) + assert.equal(candidate.env.SOLHEIM_API_KEY, "${{ secrets.FINAL_SMOKE_OPENAI_API_KEY }}") + assert.equal(candidate.env.CODING_EVALS_SIDE, "candidate") + assert.equal(candidate.env.CANDIDATE_SHA, "${{ github.sha }}") + assert.ok(candidate["timeout-minutes"] < job["timeout-minutes"]) + assert.match(candidate.run, /coding-evals:side --reps 3/) + assert.doesNotMatch(candidate.run, /coding-evals:compare/) + }) + + it("keeps reports and traces for 90 days, including after a failed candidate", () => { + const upload = job.steps.find((step) => step.uses?.startsWith("actions/upload-artifact@")) + assert.equal(upload.with["retention-days"], 90) + assert.match(upload.with.path, /side-results\.json/) + assert.match(upload.with.path, /candidate-report\.md/) + assert.match(upload.with.path, /\/artifacts/) + assert.equal( + upload.if, + "${{ !cancelled() && (steps.candidate.outcome == 'success' || steps.candidate.outcome == 'failure') }}", + ) + }) +}) + +function scenario(run) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-evals-workflow-")) + try { + const git = (...args) => { + const result = spawnSync("git", args, { cwd: dir, encoding: "utf8" }) + assert.equal(result.status, 0, result.stderr) + return result.stdout.trim() + } + git("init", "--quiet") + git( + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "-c", + "commit.gpgsign=false", + "commit", + "--quiet", + "--allow-empty", + "-m", + "initial", + ) + const sha = git("rev-parse", "HEAD") + const out = path.join(dir, "results") + const summary = path.join(dir, "summary.md") + fs.mkdirSync(out) + const result = { + pins: { side: "candidate", commit: sha, suiteId: "coding-basic-v1" }, + runs: ["clamp-range", "slugify-text", "parse-csv-line", "format-bytes", "deep-get"].flatMap((fixtureName) => + [0, 1, 2].map((repIndex) => ({ fixtureName, repIndex, outcome: { outcome: "correct" } })), + ), + } + const env = { ...process.env, CANDIDATE_SHA: sha, EVAL_OUT: out, GITHUB_STEP_SUMMARY: summary } + run({ dir, out, summary, result, env }) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +describe("candidate execution guard", () => { + // EvalWorkflow.ExecutionTrusted: provider execution needs the exact, clean tree. + for (const state of ["clean", "wrong commit", "modified tree", "wrong commit and modified tree"]) { + it(`checks ${state} before starting provider execution`, () => + scenario(({ dir, env }) => { + const bin = path.join(dir, ".git", "test-bin") + const marker = path.join(dir, ".git", "executed") + fs.mkdirSync(bin) + fs.writeFileSync(path.join(bin, "xvfb-run"), `#!/bin/sh\ntouch '${marker}'\n`, { mode: 0o755 }) + if (state.includes("wrong commit")) env.CANDIDATE_SHA = "a".repeat(40) + if (state.includes("modified tree")) fs.writeFileSync(path.join(dir, "unapproved"), "changed") + // Keep output outside the checkout, as runner.temp is in Actions. + fs.rmSync(env.EVAL_OUT, { recursive: true }) + const executed = spawnSync("bash", ["-c", candidate.run], { + cwd: dir, + env: { ...env, TRUST_FILE: "/unused", PATH: `${bin}:${env.PATH}` }, + encoding: "utf8", + }) + assert.equal(executed.status === 0, state === "clean", executed.stderr) + assert.equal(fs.existsSync(marker), state === "clean") + })) + } +}) + +describe("candidate summary", () => { + const script = new URL("./agent-evals-summary.sh", import.meta.url) + // EvalWorkflow.SummaryBound: accept only a complete candidate for unchanged HEAD. + for (const state of [ + "complete", + "missing", + "wrong commit", + "missing repetition", + "duplicate repetition", + "unknown outcome", + "wrong side", + "wrong suite", + "unknown fixture", + "head moved", + ]) { + it(`handles ${state} results`, () => + scenario(({ dir, out, summary, result, env }) => { + if (state === "wrong commit") result.pins.commit = "b".repeat(40) + if (state === "missing repetition") result.runs.pop() + if (state === "duplicate repetition") result.runs[0].repIndex = 1 + if (state === "unknown outcome") result.runs[0].outcome.outcome = "unknown" + if (state === "wrong side") result.pins.side = "baseline" + if (state === "wrong suite") result.pins.suiteId = "other-suite" + if (state === "unknown fixture") result.runs[0].fixtureName = "unregistered" + if (state === "head moved") { + env.CANDIDATE_SHA = "c".repeat(40) + result.pins.commit = env.CANDIDATE_SHA + } + if (state !== "missing") fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) + const rendered = spawnSync("bash", [script.pathname], { cwd: dir, env, encoding: "utf8" }) + assert.equal(rendered.status === 0, state === "complete", rendered.stderr) + if (state === "complete") { + const markdown = fs.readFileSync(summary, "utf8") + assert.match(markdown, /Candidate results only/) + assert.match(markdown, /\| clamp-range \| 3 \| 0 \| 0 \| 0 \| 0 \|/) + assert.equal(markdown, fs.readFileSync(path.join(out, "candidate-report.md"), "utf8")) + } else { + assert.equal(fs.existsSync(path.join(out, "candidate-report.md")), false) + } + })) + } + + for (const outcome of ["correct", "incorrect", "timed-out", "grading-failure", "infrastructure-failure"]) { + it(`accepts complete results with ${outcome} outcomes`, () => + scenario(({ dir, out, summary, result, env }) => { + for (const run of result.runs) run.outcome.outcome = outcome + fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) + const rendered = spawnSync("bash", [script.pathname], { cwd: dir, env, encoding: "utf8" }) + assert.equal(rendered.status, 0, rendered.stderr) + const column = [ + "correct", + "incorrect", + "timed-out", + "grading-failure", + "infrastructure-failure", + ].indexOf(outcome) + const cells = [0, 0, 0, 0, 0] + cells[column] = 3 + assert.ok(fs.readFileSync(summary, "utf8").includes(`| clamp-range | ${cells.join(" | ")} |`)) + })) + } +}) diff --git a/scripts/agent-evals/README.md b/scripts/agent-evals/README.md index 3b6e4998402..53219017d8c 100644 --- a/scripts/agent-evals/README.md +++ b/scripts/agent-evals/README.md @@ -196,6 +196,59 @@ pnpm coding-evals:side --reps 3 --out /tmp/side-out --trust-file trust-policy.js pnpm coding-evals:compare --baseline --candidate --trust-file trust-policy.json --reps 3 --out /tmp/compare-out ``` +### Manual GitHub Actions run + +The `Coding task evaluations` workflow is the first stage of issue #2085. +It runs the candidate only. It does not compare or promote approved baselines. +The report is advisory. It does not block or publish releases. + +Before the first run, check the `final-vscode-review-smoke` environment in repository settings. +Require reviewer approval and restrict deployment branches to `main` only. +Set its `FINAL_SMOKE_OPENAI_API_KEY` secret to the provider key used by the coding fixtures. +These settings are required. Workflow YAML cannot enforce environment reviewer settings. + +For temporary validation before merge, also permit the exact branch `issue/2085` in that environment. +Keep required reviewer approval enabled. Push the workflow commit to `issue/2085` to create the pending run. +Review the run SHA and approve that run in Actions. Each later push creates a separate approval request. +The temporary push trigger is needed because a new manual workflow must first exist on the default branch. +See [GitHub manual workflow requirements](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). +No pull request event can start the provider job. + +After validation, remove the push trigger and branch exception before merging. +Update the workflow tests and `EvalWorkflow` model to require manual `main` runs again. +Remove `issue/2085` from the environment branch rules. Keep the `main` rule and required approval. + +After this workflow is merged, open Actions, select `Coding task evaluations`, and select `Run workflow` on `main`. +Review the exact commit SHA before you approve access to the environment. +The workflow runs five fixtures three times. Each run uses the real provider and can incur charges. +The side runner builds an isolated worktree and grades in Docker. + +Read the candidate summary and download the artifact for detailed metrics and traces. +Artifacts expire after 90 days. They are not durable approved baselines. +An incomplete side fails the summary step. Its available traces remain available for diagnosis. +Incorrect solutions appear in the advisory report. They do not fail a complete workflow run. +Cost estimates remain unavailable until maintainers add real rates to the price table. + +The live broken-candidate acceptance check from #2084 still requires a separate local comparison. +This workflow has no arbitrary commit input. Only the temporary `issue/2085` exception permits branch validation. + +Remaining #2085 work includes durable baseline storage, integrity checks, comparison, explicit promotion, and release documentation. +Resolve the release order before connecting this workflow to publishing. +The issue assumes a merge before publication. The current kickoff instructions publish before the release branch merges. + +The [workflow model](../../docs/architecture/tla/EvalWorkflow.tla) specifies provider execution and summary acceptance. +It treats GitHub environment approval and side output validation as external inputs. +It does not verify the environment settings on GitHub. +Run the model gate and the code properties after changes to these boundaries: + +```sh +TLA_JAR=/path/to/tla2tools.jar docs/architecture/tla/check.sh EvalWorkflow +node --test scripts/agent-evals-workflow.test.mjs +``` + +The base model must pass. Each guard-removal variant must fail its invariant. +The code tests cover allowed inputs and rejected inputs at the same boundaries. + ### Follow-up milestones 1. Release integration: trigger runs, store baselines, and promote them. See issue #2085. From c572646bd4ea3cc62caea992d608f4f41e280613 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Mon, 30 Nov 2026 02:05:17 +0000 Subject: [PATCH 2/3] fix(evals): build extension before evaluation and share result validation --- .github/workflows/agent-evals.yml | 8 +- .../EvalHostPreparation.NoCheckOutputs.cfg | 5 + docs/architecture/tla/EvalHostPreparation.cfg | 5 + docs/architecture/tla/EvalHostPreparation.tla | 48 ++++++++++ .../tla/EvalHostPreparationMC.tla | 7 ++ .../tla/EvalWorkflow.NoApproval.cfg | 3 +- .../tla/EvalWorkflow.NoCandidate.cfg | 3 +- docs/architecture/tla/EvalWorkflow.NoHead.cfg | 3 +- .../tla/EvalWorkflow.NoInfrastructure.cfg | 10 ++ .../tla/EvalWorkflow.NoReport.cfg | 3 +- .../tla/EvalWorkflow.NoTrigger.cfg | 3 +- docs/architecture/tla/EvalWorkflow.cfg | 3 +- docs/architecture/tla/EvalWorkflow.tla | 62 +++++++++++-- docs/architecture/tla/EvalWorkflowMC.tla | 3 +- scripts/agent-evals-summary.sh | 53 ----------- scripts/agent-evals-workflow.test.mjs | 90 ++++++++++++++++-- scripts/agent-evals/README.md | 34 +++++-- scripts/agent-evals/coding-side.mts | 45 +++++---- scripts/agent-evals/coding-side.test.ts | 77 +++++++++++++-- scripts/agent-evals/coding-summary.mts | 93 +++++++++++++++++++ scripts/agent-evals/host-build.test.ts | 59 ++++++++++++ scripts/agent-evals/host-build.ts | 31 +++++++ 22 files changed, 532 insertions(+), 116 deletions(-) create mode 100644 docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg create mode 100644 docs/architecture/tla/EvalHostPreparation.cfg create mode 100644 docs/architecture/tla/EvalHostPreparation.tla create mode 100644 docs/architecture/tla/EvalHostPreparationMC.tla create mode 100644 docs/architecture/tla/EvalWorkflow.NoInfrastructure.cfg delete mode 100644 scripts/agent-evals-summary.sh create mode 100644 scripts/agent-evals/coding-summary.mts create mode 100644 scripts/agent-evals/host-build.test.ts create mode 100644 scripts/agent-evals/host-build.ts diff --git a/.github/workflows/agent-evals.yml b/.github/workflows/agent-evals.yml index ad6e623d0ab..d2c8ffc4aaa 100644 --- a/.github/workflows/agent-evals.yml +++ b/.github/workflows/agent-evals.yml @@ -4,7 +4,7 @@ name: Coding task evaluations # Trust boundaries: docs/architecture/tla/EvalWorkflow.tla. on: workflow_dispatch: - # Temporary live validation before merge. Remove this trigger before merging. + # Keep until the fixed workflow passes its full 15-attempt CI run. push: branches: [issue/2085] @@ -17,7 +17,7 @@ concurrency: jobs: evaluate: - # Remove the branch exception after the approved validation run. + # Remove the branch exception after CI validation and before merge. if: (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || (github.event_name == 'push' && github.ref == 'refs/heads/issue/2085') runs-on: ubuntu-24.04 timeout-minutes: 120 @@ -67,14 +67,14 @@ jobs: test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" test -z "$(git status --porcelain --untracked-files=all)" xvfb-run -a -s "-screen 0 1280x720x24 -nolisten tcp" \ - pnpm coding-evals:side --reps 3 --trust-file "$TRUST_FILE" --out "$EVAL_OUT" + pnpm coding-evals:side --trust-file "$TRUST_FILE" --out "$EVAL_OUT" - name: Write candidate summary if: ${{ !cancelled() && (steps.candidate.outcome == 'success' || steps.candidate.outcome == 'failure') }} env: CANDIDATE_SHA: ${{ github.sha }} EVAL_OUT: ${{ runner.temp }}/agent-evals - run: bash scripts/agent-evals-summary.sh + run: node --import tsx scripts/agent-evals/coding-summary.mts - name: Upload candidate results and traces if: ${{ !cancelled() && (steps.candidate.outcome == 'success' || steps.candidate.outcome == 'failure') }} diff --git a/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg b/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg new file mode 100644 index 00000000000..06c744f8efe --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg @@ -0,0 +1,5 @@ +CONSTANT Outputs <- MCOutputs +CONSTANT CheckOutputs <- Disabled +SPECIFICATION Spec +INVARIANT LaunchRequiresBuildOutputs +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalHostPreparation.cfg b/docs/architecture/tla/EvalHostPreparation.cfg new file mode 100644 index 00000000000..7ecf3240130 --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.cfg @@ -0,0 +1,5 @@ +CONSTANT Outputs <- MCOutputs +CONSTANT CheckOutputs <- Enabled +SPECIFICATION Spec +INVARIANT LaunchRequiresBuildOutputs +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalHostPreparation.tla b/docs/architecture/tla/EvalHostPreparation.tla new file mode 100644 index 00000000000..c43f882afa4 --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.tla @@ -0,0 +1,48 @@ +---- MODULE EvalHostPreparation ---- +\* Source: coding-side.mts preparation loop and verifyHostBuildOutputs file checks. +\* Sink: the first createHostRuntime launch in the prepared worktree. +\* Failure: a successful workspace build can leave the extension entry missing. +\* Invariant: LaunchRequiresBuildOutputs forbids launch with incomplete outputs. +\* Expect: the old flow and NoCheckOutputs fail. A preflight guard holds. +\* Stance: the missing bundle command was found before this invariant was written. +\* Scope: build success and filesystem inspection are oracles, not build implementations. +\* Inputs name the availability of the extension, webview script, and webview styles. +\* Property tests: host-build.test.ts and coding-side.test.ts. +\* Review: 0 covered, 0 added, 0 gap. No review findings received. +\* Result: the guarded model passes in 17 states. NoCheckOutputs violates the invariant. +\* Replay: the old CLI fails locally because src/dist/extension.js is missing after pnpm build. +\* Replay: removing the output guard or restoring the old build command fails the code tests. +\* Property: all 64 file-kind combinations accept only three nonempty regular outputs. +\* Property: the CLI rejects incomplete builds and retains fixed readiness diagnostics. +\* Findings: the model reproduces the known build fault. No additional bug or false alarm was found. +\* Gate: 423 evaluation tests, the evaluation type check, and applicable lint checks pass. +\* Live replay: the fixed CLI grades all five fixtures correct in containers, one attempt each. +\* The local replay evaluates the approved extension commit with the updated runner. +\* This is not the default 15-attempt CI run or evidence of statistical significance. +\* Cost: about 16 agent minutes shared with EvalWorkflow, including both live runs. +\* Run: TLA_JAR= docs/architecture/tla/check.sh EvalHostPreparation. +\* A model check covers this model. It does not prove the implementation correct. +\* Refactor: one ordered preparation loop retains separate bounded child processes. +\* Expect: LaunchRequiresBuildOutputs and its removed-guard control keep their results. +\* Command ordering and child environments remain code properties outside this output model. +\* Refactor result: the base still passes in 17 states. NoCheckOutputs still fails its invariant. +\* Code tests retain command order, preparation isolation, interruption, and incomplete-build checks. +\* Replay: skipping output verification in the preparation loop fails the incomplete-build CLI tests. +\* Findings: no new model defect was found. Cost is shared with the EvalWorkflow refactor. +EXTENDS Naturals +CONSTANTS Outputs, CheckOutputs +VARIABLES outputs, stage +vars == <> +Complete == outputs.extension /\ outputs.webviewScript /\ outputs.webviewStyles +Init == /\ outputs \in Outputs + /\ stage = "built" +Verify == /\ stage = "built" + /\ stage' = IF ~CheckOutputs \/ Complete THEN "ready" ELSE "rejected" + /\ UNCHANGED outputs +Launch == /\ stage = "ready" + /\ stage' = "launched" + /\ UNCHANGED outputs +Next == Verify \/ Launch +Spec == Init /\ [][Next]_vars +LaunchRequiresBuildOutputs == stage = "launched" => Complete +==== diff --git a/docs/architecture/tla/EvalHostPreparationMC.tla b/docs/architecture/tla/EvalHostPreparationMC.tla new file mode 100644 index 00000000000..0a7b74502c5 --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparationMC.tla @@ -0,0 +1,7 @@ +---- MODULE EvalHostPreparationMC ---- +\* One prepared tree has three required build outputs. +EXTENDS EvalHostPreparation +Enabled == TRUE +Disabled == FALSE +MCOutputs == [extension : BOOLEAN, webviewScript : BOOLEAN, webviewStyles : BOOLEAN] +==== diff --git a/docs/architecture/tla/EvalWorkflow.NoApproval.cfg b/docs/architecture/tla/EvalWorkflow.NoApproval.cfg index 7008f7b7807..8c4d3d8faab 100644 --- a/docs/architecture/tla/EvalWorkflow.NoApproval.cfg +++ b/docs/architecture/tla/EvalWorkflow.NoApproval.cfg @@ -4,6 +4,7 @@ CONSTANT CheckApproval <- Disabled CONSTANT CheckCandidate <- Enabled CONSTANT CheckReport <- Enabled CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled SPECIFICATION Spec -INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg b/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg index d8055ab1f45..8f6128efb57 100644 --- a/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg +++ b/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg @@ -4,6 +4,7 @@ CONSTANT CheckApproval <- Enabled CONSTANT CheckCandidate <- Disabled CONSTANT CheckReport <- Enabled CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled SPECIFICATION Spec -INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoHead.cfg b/docs/architecture/tla/EvalWorkflow.NoHead.cfg index a56a12813e3..cb366e6cb84 100644 --- a/docs/architecture/tla/EvalWorkflow.NoHead.cfg +++ b/docs/architecture/tla/EvalWorkflow.NoHead.cfg @@ -4,6 +4,7 @@ CONSTANT CheckApproval <- Enabled CONSTANT CheckCandidate <- Enabled CONSTANT CheckReport <- Enabled CONSTANT CheckHead <- Disabled +CONSTANT CheckInfrastructure <- Enabled SPECIFICATION Spec -INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoInfrastructure.cfg b/docs/architecture/tla/EvalWorkflow.NoInfrastructure.cfg new file mode 100644 index 00000000000..e4a4a8147ac --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoInfrastructure.cfg @@ -0,0 +1,10 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Disabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoReport.cfg b/docs/architecture/tla/EvalWorkflow.NoReport.cfg index b78e0514682..abbe0bcb96d 100644 --- a/docs/architecture/tla/EvalWorkflow.NoReport.cfg +++ b/docs/architecture/tla/EvalWorkflow.NoReport.cfg @@ -4,6 +4,7 @@ CONSTANT CheckApproval <- Enabled CONSTANT CheckCandidate <- Enabled CONSTANT CheckReport <- Disabled CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled SPECIFICATION Spec -INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg b/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg index e66082e0ace..341156d1aa3 100644 --- a/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg +++ b/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg @@ -4,6 +4,7 @@ CONSTANT CheckApproval <- Enabled CONSTANT CheckCandidate <- Enabled CONSTANT CheckReport <- Enabled CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled SPECIFICATION Spec -INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.cfg b/docs/architecture/tla/EvalWorkflow.cfg index 542b04408f1..31ba2bfb2c7 100644 --- a/docs/architecture/tla/EvalWorkflow.cfg +++ b/docs/architecture/tla/EvalWorkflow.cfg @@ -4,6 +4,7 @@ CONSTANT CheckApproval <- Enabled CONSTANT CheckCandidate <- Enabled CONSTANT CheckReport <- Enabled CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled SPECIFICATION Spec -INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.tla b/docs/architecture/tla/EvalWorkflow.tla index fa48817597c..ff232fc3dcf 100644 --- a/docs/architecture/tla/EvalWorkflow.tla +++ b/docs/architecture/tla/EvalWorkflow.tla @@ -2,7 +2,7 @@ \* Source: agent-evals.yml dispatch, evaluate.if, and environment approval. \* Sink: Evaluate candidate starts coding-evals:side with the provider key. \* Source: side-results.json and checkout HEAD after the candidate run. -\* Sink: agent-evals-summary.sh publishes candidate-report.md and the summary. +\* Sink: coding-summary.mts publishes candidate-report.md and the summary. \* Failure: an unapproved event or ref can reach the provider job. \* Failure: provider execution starts with a different commit or dirty tree. \* Failure: incomplete or foreign results become an accepted summary. @@ -12,12 +12,12 @@ \* Scope: GitHub environment approval and side output validation are oracles. \* Scope: payload kinds stand for valid JSON inputs and a missing result file. \* Scope: artifact retention, cancellation, and hosted scheduling are outside the model. -\* Assumption: the named environment requires approval for main and issue/2085. +\* Assumption: the environment requires approval for main and the temporary issue/2085 branch. \* Limit: this model cannot inspect repository environment settings. \* Limit: no local actor changes the tree between a shell guard and execution. \* The isolated side runner checks its own worktree outside this model. \* Property tests: scripts/agent-evals-workflow.test.mjs. -\* Review ratchet: 0 covered, 0 added, 0 gap. No review findings received. +\* Review ratchet: 0 covered, 2 added, 0 gap. Both findings strengthen the trigger input rule. \* Result: EvalWorkflow.cfg passes in 1760 distinct states. No new bug was found. \* Controls: NoTrigger and NoApproval violate SecretsAuthorized. \* Controls: NoCandidate violates ExecutionTrusted. NoHead and NoReport violate SummaryBound. @@ -40,9 +40,47 @@ \* Gate: all 24 workflow tests and the evaluation type check pass. No new bug was found. \* Gate: all 419 offline evaluation tests pass outside the child-process sandbox. \* Cost: about 6 more agent minutes, including branch setup and model replay. +\* Runtime finding: PR 2781 job 141531999567 reported success with 15 infrastructure failures. +\* Failure: infrastructure or grader faults appear as a successful evaluation. +\* Invariant: WorkflowHealthy requires fault-free infrastructure before the job succeeds. +\* Expect: NoInfrastructure reproduces the green failed evaluation. Other guards remain necessary. +\* Source: coding-summary.mts fault count. Sink: summary step exit status after report publication. +\* Result: the updated base passes in 5508 states. All six removed-guard controls fail. +\* Replay: removing the health guard fails complete-failure and mixed-failure code tests. +\* Replay: the original CI artifact now exits with failure and preserves its Markdown report. +\* Gate: 26 workflow tests pass. Incorrect and timed-out tasks remain advisory. +\* Findings: the model reproduces the known status fault. No additional bug or false alarm was found. +\* Cost: shared with EvalHostPreparation. GitHub reviewer settings remain outside this model. +\* Review: remove the temporary branch exception from the workflow and its model. +\* PR 2781: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2781#discussion_r4733706220 +\* PR 2781: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2781#discussion_r4733706224 +\* Change: AllowedTrigger accepts manual main runs only after local validation passed. +\* Keep push and issue/2085 in MCInputs to check their rejection. +\* Expect: the base still holds. A restored branch exception fails the code trigger property. +\* Result after review: base passes in 5058 states. All six removed-guard controls fail. +\* Replay: restoring the branch disjunct fails the code trigger property. Restored code passes all 26 tests. +\* Findings: both review items use the stronger trigger rule. No additional bug or false alarm was found. +\* Environment audit: the temporary branch rule was removed. Main and required reviewers remain. +\* Cost: about 3 additional agent minutes for review, replay, and environment cleanup. +\* Refactor: coding-summary.mts uses validateSideResultFile. Summary and side CLI use one repetition default. +\* Failure: malformed metrics or disagreeing record outcomes become an accepted summary. +\* Expect: SummaryBound still holds with those input classes. No new bug is expected. +\* Preserve report publication before the infrastructure exit status is selected. +\* Refactor result: base passes in 6322 states. The larger domain adds malformed-metric input classes. +\* All six removed-guard controls fail. The code replays detect removed validation, commit binding, and failure status. +\* The real failed CI artifact still fails after report publication. No new model defect was found. +\* Gate: 32 workflow tests, 424 evaluation tests, both type checks, and applicable lint checks pass. +\* Cost: about 8 agent minutes shared with EvalHostPreparation. No live provider calls were made. +\* Correction: local five-attempt validation does not replace the full 15-attempt CI run. +\* Restore the branch exception until the fixed workflow passes that CI run. +\* Both review cleanup items remain deferred until CI passes, then must finish before merge. +\* Expect: the existing guards hold with the restored, explicitly approved trigger pair. +\* Result: the temporary-validation model passes in 6884 states. All six controls still fail. +\* Gate: all 32 workflow tests pass. The environment again permits issue/2085 with reviewer approval. +\* Cost: about 3 additional agent minutes for the correction and environment restoration. EXTENDS Naturals -CONSTANTS Inputs, CheckTrigger, CheckApproval, CheckCandidate, CheckReport, CheckHead +CONSTANTS Inputs, CheckTrigger, CheckApproval, CheckCandidate, CheckReport, CheckHead, CheckInfrastructure VARIABLES input, stage vars == <> @@ -75,16 +113,22 @@ Finish == /\ stage = "running" Summarize == /\ stage = "result" /\ stage' = IF (~CheckHead \/ input.endMatches) /\ (~CheckReport \/ PayloadComplete) - THEN "accepted" ELSE "summaryRejected" + THEN "reported" ELSE "summaryRejected" /\ UNCHANGED input -Next == Dispatch \/ Authorize \/ Execute \/ Finish \/ Summarize +\* Preserve the report, then fail the job for infrastructure or grader faults. +CheckHealth == /\ stage = "reported" + /\ stage' = IF ~CheckInfrastructure \/ input.healthy THEN "accepted" ELSE "infrastructureFailed" + /\ UNCHANGED input + +Next == Dispatch \/ Authorize \/ Execute \/ Finish \/ Summarize \/ CheckHealth Spec == Init /\ [][Next]_vars \* An invalid candidate can receive the step environment, but cannot execute. -SecretsAvailable == stage \in {"ready", "guardRejected", "running", "result", "accepted", "summaryRejected"} -ExecutionStarted == stage \in {"running", "result", "accepted", "summaryRejected"} +SecretsAvailable == stage \in {"ready", "guardRejected", "running", "result", "reported", "accepted", "summaryRejected", "infrastructureFailed"} +ExecutionStarted == stage \in {"running", "result", "reported", "accepted", "summaryRejected", "infrastructureFailed"} SecretsAuthorized == SecretsAvailable => (AllowedTrigger /\ input.approved) ExecutionTrusted == ExecutionStarted => CandidateMatches -SummaryBound == stage = "accepted" => (PayloadComplete /\ input.endMatches) +SummaryBound == stage \in {"reported", "accepted", "infrastructureFailed"} => (PayloadComplete /\ input.endMatches) +WorkflowHealthy == stage = "accepted" => input.healthy ==== diff --git a/docs/architecture/tla/EvalWorkflowMC.tla b/docs/architecture/tla/EvalWorkflowMC.tla index 685cf2a7400..bac61cba48a 100644 --- a/docs/architecture/tla/EvalWorkflowMC.tla +++ b/docs/architecture/tla/EvalWorkflowMC.tla @@ -9,6 +9,7 @@ MCInputs == [event : {"workflow_dispatch", "pull_request", "push"}, startMatches : BOOLEAN, clean : BOOLEAN, endMatches : BOOLEAN, + healthy : BOOLEAN, payload : {"complete", "missing", "wrongCommit", "wrongSide", "wrongSuite", - "missingKeys", "duplicateKeys", "unknownOutcome"}] + "missingKeys", "duplicateKeys", "unknownOutcome", "invalidMetrics", "mismatchedOutcome"}] ==== diff --git a/scripts/agent-evals-summary.sh b/scripts/agent-evals-summary.sh deleted file mode 100644 index 8f86e8a3a9d..00000000000 --- a/scripts/agent-evals-summary.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/usr/bin/env bash -set -euo pipefail - -: "${CANDIDATE_SHA:?}" -: "${EVAL_OUT:?}" -: "${GITHUB_STEP_SUMMARY:?}" - -# A side publishes this completion marker only after its full run finishes. -# Do not turn partial traces into a valid report. -# Source and sink model: docs/architecture/tla/EvalWorkflow.tla, SummaryBound. -report="$EVAL_OUT/side-results.json" -if ! test -f "$report"; then - echo 'Evaluation failed before it published complete results. Check the logs and available traces.' >> "$GITHUB_STEP_SUMMARY" - exit 1 -fi - -test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" -jq -e --arg sha "$CANDIDATE_SHA" ' - .pins.commit == $sha and .pins.side == "candidate" and - .pins.suiteId == "coding-basic-v1" and - (.runs | length == 15) and - ([.runs[].fixtureName] | unique | sort) == - ["clamp-range", "deep-get", "format-bytes", "parse-csv-line", "slugify-text"] and - ([.runs | group_by(.fixtureName)[] | ([.[].repIndex] | sort) == [0, 1, 2]] | all) and - ([.runs[].outcome.outcome | - . == "correct" or . == "incorrect" or . == "timed-out" or - . == "grading-failure" or . == "infrastructure-failure"] | all) -' "$report" > /dev/null - -# Only fixed fixture names, numeric values, and known outcomes enter Markdown. -# Arbitrary model output and failure messages stay out of the workflow summary. -summary="$EVAL_OUT/candidate-report.md" -{ - printf '# Coding task evaluation\n\nCandidate commit: `%s`\n\n' "$CANDIDATE_SHA" - printf 'Candidate results only. No approved baseline comparison is available.\n\n' - printf 'Results are advisory. This workflow does not publish a release or promote a baseline.\n\n' - printf '| Fixture | Correct | Incorrect | Timed out | Grading failure | Infrastructure failure |\n' - printf '| --- | --- | --- | --- | --- | --- |\n' - jq -r ' - .runs | group_by(.fixtureName)[] | - [.[0].fixtureName, - ([.[] | select(.outcome.outcome == "correct")] | length), - ([.[] | select(.outcome.outcome == "incorrect")] | length), - ([.[] | select(.outcome.outcome == "timed-out")] | length), - ([.[] | select(.outcome.outcome == "grading-failure")] | length), - ([.[] | select(.outcome.outcome == "infrastructure-failure")] | length)] | - "| " + (map(tostring) | join(" | ")) + " |" - ' "$report" - printf '\nEach fixture has three attempts. Small samples do not establish statistical significance.\n' - printf '\nToken use, tool calls, duration, accounting status, and cost availability are in side-results.json.\n' - printf '\nCost estimates remain unavailable until the price table contains maintained rates.\n' -} > "$summary" -cat "$summary" >> "$GITHUB_STEP_SUMMARY" diff --git a/scripts/agent-evals-workflow.test.mjs b/scripts/agent-evals-workflow.test.mjs index 498b2eac519..834a75f83fe 100644 --- a/scripts/agent-evals-workflow.test.mjs +++ b/scripts/agent-evals-workflow.test.mjs @@ -5,14 +5,23 @@ import path from "node:path" import { spawnSync } from "node:child_process" import { describe, it } from "node:test" import { runInNewContext } from "node:vm" +import { createRequire } from "node:module" import { parse } from "yaml" const workflow = parse(fs.readFileSync(new URL("../.github/workflows/agent-evals.yml", import.meta.url), "utf8")) const job = workflow.jobs.evaluate const candidate = job.steps.find((step) => step.id === "candidate") +const tsxLoader = createRequire(import.meta.url).resolve("tsx") +const summaryScript = new URL("./agent-evals/coding-summary.mts", import.meta.url) +const runSummary = (cwd, env) => + spawnSync(process.execPath, ["--import", tsxLoader, summaryScript.pathname], { cwd, env, encoding: "utf8" }) +const setOutcome = (run, outcome) => { + run.outcome = { outcome, reason: "test" } + run.metrics.outcome = { ...run.outcome } +} describe("coding evaluation workflow", () => { - // EvalWorkflow.SecretsAuthorized: only main dispatch or the temporary branch push can receive secrets. + // EvalWorkflow.SecretsAuthorized: main dispatch and temporary branch push require approval. it("accepts only the approved event and ref pairs in the bounded trigger domain", () => { for (const event of ["workflow_dispatch", "pull_request", "pull_request_target", "push"]) { for (const ref of ["refs/heads/main", "refs/heads/issue/2085", "refs/heads/feature", "refs/tags/v1.0.0"]) { @@ -58,7 +67,7 @@ describe("coding evaluation workflow", () => { assert.equal(candidate.env.CODING_EVALS_SIDE, "candidate") assert.equal(candidate.env.CANDIDATE_SHA, "${{ github.sha }}") assert.ok(candidate["timeout-minutes"] < job["timeout-minutes"]) - assert.match(candidate.run, /coding-evals:side --reps 3/) + assert.match(candidate.run, /coding-evals:side --trust-file/) assert.doesNotMatch(candidate.run, /coding-evals:compare/) }) @@ -73,6 +82,12 @@ describe("coding evaluation workflow", () => { "${{ !cancelled() && (steps.candidate.outcome == 'success' || steps.candidate.outcome == 'failure') }}", ) }) + + it("uses the shared TypeScript summary command without provider credentials", () => { + const summary = job.steps.find((step) => step.name === "Write candidate summary") + assert.equal(summary.run, "node --import tsx scripts/agent-evals/coding-summary.mts") + assert.doesNotMatch(JSON.stringify(summary), /secrets\./) + }) }) function scenario(run) { @@ -102,9 +117,30 @@ function scenario(run) { const summary = path.join(dir, "summary.md") fs.mkdirSync(out) const result = { - pins: { side: "candidate", commit: sha, suiteId: "coding-basic-v1" }, + pins: { + side: "candidate", + commit: sha, + suiteId: "coding-basic-v1", + suiteDigest: "suite-digest", + settingsDigest: "settings-digest", + modelIdentifier: "test-model", + graderVersion: "test-grader", + graderImageDigest: "test-image", + runnerEnvironment: { os: "linux", nodeVersion: "v22.23.4", vscodeTarget: "1.100.0" }, + }, runs: ["clamp-range", "slugify-text", "parse-csv-line", "format-bytes", "deep-get"].flatMap((fixtureName) => - [0, 1, 2].map((repIndex) => ({ fixtureName, repIndex, outcome: { outcome: "correct" } })), + [0, 1, 2].map((repIndex) => ({ + fixtureName, + repIndex, + outcome: { outcome: "correct", reason: "test" }, + metrics: { + fixtureName, + repIndex, + outcome: { outcome: "correct", reason: "test" }, + durationMs: 1000, + cost: { accountingComplete: false, estimated: { available: false, reason: "notConfigured" } }, + }, + })), ), } const env = { ...process.env, CANDIDATE_SHA: sha, EVAL_OUT: out, GITHUB_STEP_SUMMARY: summary } @@ -139,7 +175,17 @@ describe("candidate execution guard", () => { }) describe("candidate summary", () => { - const script = new URL("./agent-evals-summary.sh", import.meta.url) + it("keeps untrusted result values out of failure diagnostics", () => + scenario(({ dir, out, summary, result, env }) => { + const privateValue = "private-input-value\n::error::untrusted" + result.pins.side = privateValue + fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) + const rendered = runSummary(dir, env) + assert.equal(rendered.status, 1, rendered.stderr) + assert.ok(!`${rendered.stdout}${rendered.stderr}${fs.readFileSync(summary, "utf8")}`.includes(privateValue)) + assert.equal(fs.existsSync(path.join(out, "candidate-report.md")), false) + })) + // EvalWorkflow.SummaryBound: accept only a complete candidate for unchanged HEAD. for (const state of [ "complete", @@ -152,6 +198,10 @@ describe("candidate summary", () => { "wrong suite", "unknown fixture", "head moved", + "invalid metrics", + "mismatched outcome", + "missing pin", + "mismatched metrics key", ]) { it(`handles ${state} results`, () => scenario(({ dir, out, summary, result, env }) => { @@ -159,6 +209,10 @@ describe("candidate summary", () => { if (state === "missing repetition") result.runs.pop() if (state === "duplicate repetition") result.runs[0].repIndex = 1 if (state === "unknown outcome") result.runs[0].outcome.outcome = "unknown" + if (state === "mismatched outcome") result.runs[0].outcome.outcome = "infrastructure-failure" + if (state === "invalid metrics") result.runs[0].metrics.durationMs = null + if (state === "missing pin") delete result.pins.settingsDigest + if (state === "mismatched metrics key") result.runs[0].metrics.fixtureName = "deep-get" if (state === "wrong side") result.pins.side = "baseline" if (state === "wrong suite") result.pins.suiteId = "other-suite" if (state === "unknown fixture") result.runs[0].fixtureName = "unregistered" @@ -167,7 +221,7 @@ describe("candidate summary", () => { result.pins.commit = env.CANDIDATE_SHA } if (state !== "missing") fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) - const rendered = spawnSync("bash", [script.pathname], { cwd: dir, env, encoding: "utf8" }) + const rendered = runSummary(dir, env) assert.equal(rendered.status === 0, state === "complete", rendered.stderr) if (state === "complete") { const markdown = fs.readFileSync(summary, "utf8") @@ -181,12 +235,14 @@ describe("candidate summary", () => { } for (const outcome of ["correct", "incorrect", "timed-out", "grading-failure", "infrastructure-failure"]) { - it(`accepts complete results with ${outcome} outcomes`, () => + it(`reports complete results with ${outcome} outcomes and checks infrastructure health`, () => scenario(({ dir, out, summary, result, env }) => { - for (const run of result.runs) run.outcome.outcome = outcome + for (const run of result.runs) setOutcome(run, outcome) fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) - const rendered = spawnSync("bash", [script.pathname], { cwd: dir, env, encoding: "utf8" }) - assert.equal(rendered.status, 0, rendered.stderr) + const rendered = runSummary(dir, env) + const infrastructureFailure = outcome === "infrastructure-failure" || outcome === "grading-failure" + assert.equal(rendered.status, infrastructureFailure ? 1 : 0, rendered.stderr) + assert.equal(fs.readFileSync(summary, "utf8").includes("**Evaluation failed:**"), infrastructureFailure) const column = [ "correct", "incorrect", @@ -199,4 +255,18 @@ describe("candidate summary", () => { assert.ok(fs.readFileSync(summary, "utf8").includes(`| clamp-range | ${cells.join(" | ")} |`)) })) } + + for (const outcome of ["grading-failure", "infrastructure-failure"]) { + it(`fails a mixed report with one ${outcome} and preserves the report`, () => + scenario(({ dir, out, summary, result, env }) => { + setOutcome(result.runs[0], outcome) + fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) + const rendered = runSummary(dir, env) + assert.equal(rendered.status, 1, rendered.stderr) + assert.match(rendered.stdout, /::error::/) + const report = fs.readFileSync(path.join(out, "candidate-report.md"), "utf8") + assert.equal(report, fs.readFileSync(summary, "utf8")) + assert.match(report, /failed in 1 of 15 attempts/) + })) + } }) diff --git a/scripts/agent-evals/README.md b/scripts/agent-evals/README.md index 53219017d8c..bec2303b065 100644 --- a/scripts/agent-evals/README.md +++ b/scripts/agent-evals/README.md @@ -122,6 +122,8 @@ release process: a maintainer runs it locally or on demand. | `coding-report.ts` | The self-contained JSON report and the Markdown renderer. | | `coding-compare.ts` | The comparison orchestration and the side result shape. | | `coding-side.mts` | One comparison side: rebuilds the evaluated tree, then all fixtures times N repetitions on it, graded, with pinned inputs. | +| `coding-summary.mts` | Validates candidate results through the shared side-result validator and writes the Actions summary. | +| `host-build.ts` | Verifies the extension entry and webview assets before launch. Writes fixed preparation diagnostics. | | `coding-compare.mts` | Two-commit comparison driver. Writes `comparison-report.json` and `comparison-report.md`. | | `coding-trust.ts` | The comparison trust policy: approved full commit SHAs, resolution, the approval gate, and the side environment allowlist. | | `fs-atomic.ts` | Atomic file publication through same-directory temp files and renames. | @@ -207,26 +209,38 @@ Require reviewer approval and restrict deployment branches to `main` only. Set its `FINAL_SMOKE_OPENAI_API_KEY` secret to the provider key used by the coding fixtures. These settings are required. Workflow YAML cannot enforce environment reviewer settings. -For temporary validation before merge, also permit the exact branch `issue/2085` in that environment. -Keep required reviewer approval enabled. Push the workflow commit to `issue/2085` to create the pending run. -Review the run SHA and approve that run in Actions. Each later push creates a separate approval request. -The temporary push trigger is needed because a new manual workflow must first exist on the default branch. -See [GitHub manual workflow requirements](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). -No pull request event can start the provider job. +Before merge, the workflow also permits push runs on the exact branch `issue/2085` for live CI validation. +Permit that branch in the environment rules and keep required reviewer approval enabled. +Commit and push the fixes, then approve the exact run SHA in Actions. +Local validation with one attempt per fixture does not replace this full 15-attempt CI check. +Pull request events and pushes to other branches cannot start the provider job. + +After the fixed workflow passes the full CI run, remove the branch trigger and guard exception before merging. +Update the workflow tests and model to require manual `main` runs only. +Remove `issue/2085` from the environment branch rules. Keep `main` and required approval. -After validation, remove the push trigger and branch exception before merging. -Update the workflow tests and `EvalWorkflow` model to require manual `main` runs again. -Remove `issue/2085` from the environment branch rules. Keep the `main` rule and required approval. +A new manual workflow must first exist on the default branch. +See [GitHub manual workflow requirements](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). After this workflow is merged, open Actions, select `Coding task evaluations`, and select `Run workflow` on `main`. Review the exact commit SHA before you approve access to the environment. The workflow runs five fixtures three times. Each run uses the real provider and can incur charges. The side runner builds an isolated worktree and grades in Docker. +It runs `pnpm -w bundle` and the webview build in that worktree. +The generic workspace `pnpm build` command does not create the extension entry. +Before launch, the runner requires a nonempty extension entry, webview script, and webview stylesheet. +It writes their readiness to `artifacts/preparation-diagnostics.txt`, then stops if an output is missing or invalid. +This report contains fixed readiness labels. It contains no host logs, settings, or credentials. Read the candidate summary and download the artifact for detailed metrics and traces. Artifacts expire after 90 days. They are not durable approved baselines. An incomplete side fails the summary step. Its available traces remain available for diagnosis. Incorrect solutions appear in the advisory report. They do not fail a complete workflow run. +Infrastructure and grading failures fail the workflow after the summary is written. +The report and available traces are still uploaded for diagnosis. +The TypeScript summary command uses `validateSideResultFile` and the shared repetition default. +The side CLI uses that default too. The workflow does not repeat the value in its command. +It also checks the current suite and agreement between run outcomes and metric outcomes. Cost estimates remain unavailable until maintainers add real rates to the price table. The live broken-candidate acceptance check from #2084 still requires a separate local comparison. @@ -242,7 +256,7 @@ It does not verify the environment settings on GitHub. Run the model gate and the code properties after changes to these boundaries: ```sh -TLA_JAR=/path/to/tla2tools.jar docs/architecture/tla/check.sh EvalWorkflow +TLA_JAR=/path/to/tla2tools.jar docs/architecture/tla/check.sh EvalWorkflow EvalHostPreparation node --test scripts/agent-evals-workflow.test.mjs ``` diff --git a/scripts/agent-evals/coding-side.mts b/scripts/agent-evals/coding-side.mts index 35564ca6cff..e2cf9a4fe59 100644 --- a/scripts/agent-evals/coding-side.mts +++ b/scripts/agent-evals/coding-side.mts @@ -19,12 +19,14 @@ import path from "node:path" import { fileURLToPath } from "node:url" import { promisify } from "node:util" import { createHostRuntime } from "./launcher.ts" +import { verifyHostBuildOutputs } from "./host-build.ts" import { createPrivateVSCodeDownloader } from "./vscode-cache.ts" import { createContainerGradingRuntime } from "./container-runtime.ts" import { runCodingFixtureOnce, type CodingRunRecord } from "./coding-run.ts" import { CODING_FIXTURE_BUNDLES } from "./coding-fixtures.ts" import { CODING_SUITE_ID, codingSuiteDigest, ensureCodingSuiteRegistered } from "./coding-suite.ts" import { GRADER_VERSION } from "./coding-grader.ts" +import { DEFAULT_REPETITIONS } from "./coding-stats.ts" import { digestValue } from "./coding-digest.ts" import { sideGraderImageDigest, type SidePins } from "./coding-pins.ts" import { prepareIsolatedWorktree, runBoundedPreparation } from "./coding-compare.ts" @@ -82,7 +84,7 @@ const readArgs = (): { // could forward an unrelated parent secret to the evaluated extension. assertCredentialEnvAllowed(credentialEnv) return { - reps: Number(read("reps") ?? "3"), + reps: Number(read("reps") ?? DEFAULT_REPETITIONS), out: path.resolve(out), credentialEnv, // Repository whose HEAD commit this side evaluates. The trusted @@ -263,28 +265,37 @@ await executeSideGeneration({ // the host loads is always this side's own product of the approved // commit. The preparation children receive only the allowlisted // environment, so the credential never reaches them. - await runBoundedPreparation( - prepGuard, - isSideInterrupted, - "pnpm", - ["install", "--frozen-lockfile"], - evaluatedWorktree, - INSTALL_TIMEOUT_MS, - ) - await runBoundedPreparation( - prepGuard, - isSideInterrupted, - "pnpm", - ["build"], - evaluatedWorktree, - BUILD_TIMEOUT_MS, - ) + for (const step of [ + { + label: "installing dependencies in the approved worktree", + args: ["install", "--frozen-lockfile"], + timeoutMs: INSTALL_TIMEOUT_MS, + }, + { label: "building the extension bundle", args: ["-w", "bundle"], timeoutMs: BUILD_TIMEOUT_MS }, + { + label: "building the webview", + args: ["--filter", "@roo-code/vscode-webview", "build"], + timeoutMs: BUILD_TIMEOUT_MS, + }, + ]) { + console.log(`coding-evals: ${step.label}`) + await runBoundedPreparation( + prepGuard, + isSideInterrupted, + "pnpm", + step.args, + evaluatedWorktree, + step.timeoutMs, + ) + } + await verifyHostBuildOutputs(evaluatedWorktree, path.join(out, "artifacts", "preparation-diagnostics.txt")) const { runs, completed } = await executeSideFlow({ repetitions, out, isInterrupted: isSideInterrupted, runRepetition: async ({ fixtureName, repIndex }) => { + console.log(`coding-evals: running ${fixtureName} repetition ${repIndex}`) const artifactsDir = path.join(out, "artifacts", `${fixtureName}-rep${repIndex}`) await fs.mkdir(artifactsDir, { recursive: true }) return runCodingFixtureOnce({ diff --git a/scripts/agent-evals/coding-side.test.ts b/scripts/agent-evals/coding-side.test.ts index 9b3a7cd38d6..25a6ffe5242 100644 --- a/scripts/agent-evals/coding-side.test.ts +++ b/scripts/agent-evals/coding-side.test.ts @@ -230,7 +230,11 @@ type InstallBehavior = "succeed" | "fail" | "hang" | "ignore-term" // environment, so a test can prove the side prepared and built a fresh tree // without the credential. The build step writes the benign entry the real // toolchain would produce, relative to the tree it actually ran in. -const writePnpmShim = async (dir: string, install: InstallBehavior): Promise => { +const writePnpmShim = async ( + dir: string, + install: InstallBehavior, + build: "complete" | "missing-extension" | "missing-webview" = "complete", +): Promise => { const shimDir = path.join(dir, "bin") await fs.mkdir(shimDir) const log = (name: string): string => shellQuote(path.join(dir, name)) @@ -260,11 +264,20 @@ const writePnpmShim = async (dir: string, install: InstallBehavior): Promise ${log("pnpm-build-cwd.log")}`, ` git rev-parse HEAD > ${log("pnpm-build-head.log")}`, " mkdir -p src/dist", - " printf 'benign extension entry\\n' > src/dist/extension.js", + build === "missing-extension" ? " :" : " printf 'benign extension entry\\n' > src/dist/extension.js", + " exit 0", + " ;;", + " --filter)", + ' test "$2" = @roo-code/vscode-webview && test "$3" = build || exit 1', + ` pwd > ${log("pnpm-webview-cwd.log")}`, + " mkdir -p src/webview-ui/build/assets", + build === "missing-webview" ? " :" : " printf 'webview script\\n' > src/webview-ui/build/assets/index.js", + " printf 'webview styles\\n' > src/webview-ui/build/assets/index.css", " exit 0", " ;;", "esac", @@ -323,14 +336,19 @@ const assertSingleWorktree = async (repo: string): Promise => { // the caller can prove its removal. const assertPreparationRanInFreshTree = async (dir: string, repo: string, commit: string): Promise => { const args = (await fs.readFile(path.join(dir, "pnpm-args.log"), "utf8")).trim().split("\n") - assert.deepEqual(args, ["install --frozen-lockfile", "build"]) + assert.deepEqual(args, ["install --frozen-lockfile", "-w bundle", "--filter @roo-code/vscode-webview build"]) const installCwd = (await fs.readFile(path.join(dir, "pnpm-install-cwd.log"), "utf8")).trim() const buildCwd = (await fs.readFile(path.join(dir, "pnpm-build-cwd.log"), "utf8")).trim() const buildHead = (await fs.readFile(path.join(dir, "pnpm-build-head.log"), "utf8")).trim() assert.equal(installCwd, buildCwd) + assert.equal((await fs.readFile(path.join(dir, "pnpm-webview-cwd.log"), "utf8")).trim(), buildCwd) assert.notEqual(installCwd, repo) assert.ok(path.basename(path.dirname(installCwd)).startsWith("coding-evals-side-")) assert.equal(buildHead, commit) + assert.equal( + await fs.readFile(path.join(dir, "out/artifacts/preparation-diagnostics.txt"), "utf8"), + "extensionEntry: ready\nwebviewScript: ready\nwebviewStyles: ready\n", + ) return installCwd } @@ -339,8 +357,8 @@ interface SideResultsFile { runs: { fixtureName: string; repIndex: number; outcome: { outcome: string } }[] } -// The launch fails deterministically because the fixture has no host entry, -// so every repetition is a non-correct record and the side still publishes. +// The fixture has no VS Code package metadata, so launch fails before a +// download. Every repetition is a non-correct record and the side publishes. const assertPublishedFailedRuns = async (dir: string, commit: string, reps = 1): Promise => { const results = JSON.parse(await fs.readFile(path.join(dir, "out", "side-results.json"), "utf8")) as SideResultsFile assert.equal(results.pins.commit, commit) @@ -354,6 +372,53 @@ const assertPublishedFailedRuns = async (dir: string, commit: string, reps = 1): } describe("coding side evaluated tree preparation", () => { + it( + "uses three repetitions per fixture when the operator does not override the shared default", + { timeout: 240_000 }, + async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "coding-side-default-")) + try { + const { repo, commit } = await makeFixtureCommit(dir) + const trustFile = await writePolicy(dir, [commit]) + const shimDir = await writePnpmShim(dir, "succeed") + const outcome = await runSideScript( + preparedArgs(dir, repo, trustFile).slice(2), + preparedEnv(dir, shimDir), + ) + assert.equal(outcome.code, 0, outcome.stderr) + await assertPublishedFailedRuns(dir, commit, 3) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }, + ) + + for (const build of ["missing-extension", "missing-webview"] as const) { + it(`rejects a successful build with ${build} before any host launch`, { timeout: 240_000 }, async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "coding-side-build-")) + try { + const { repo, commit } = await makeFixtureCommit(dir) + const trustFile = await writePolicy(dir, [commit]) + const shimDir = await writePnpmShim(dir, "succeed", build) + const outcome = await runSideScript(preparedArgs(dir, repo, trustFile), preparedEnv(dir, shimDir)) + assert.notEqual(outcome.code, 0) + assert.match(outcome.stderr, /prepared host build outputs are missing or invalid/) + assert.ok(!outcome.stdout.includes("coding-evals: running")) + const report = await fs.readFile(path.join(dir, "out/artifacts/preparation-diagnostics.txt"), "utf8") + assert.match( + report, + new RegExp( + `${build === "missing-extension" ? "extensionEntry" : "webviewScript"}: missing-or-invalid`, + ), + ) + await assert.rejects(fs.access(path.join(dir, "out/side-results.json"))) + const preparedTree = (await fs.readFile(path.join(dir, "pnpm-build-cwd.log"), "utf8")).trim() + await assert.rejects(fs.access(preparedTree)) + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) + } it( "builds a fresh detached worktree of the approved commit and never loads the caller tree", { timeout: 240_000 }, diff --git a/scripts/agent-evals/coding-summary.mts b/scripts/agent-evals/coding-summary.mts new file mode 100644 index 00000000000..4a886c172ed --- /dev/null +++ b/scripts/agent-evals/coding-summary.mts @@ -0,0 +1,93 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { validateSideResultFile } from "./coding-compare.ts" +import { CODING_SUITE_ID } from "./coding-suite.ts" +import { DEFAULT_REPETITIONS } from "./coding-stats.ts" +import { resolveCommit } from "./coding-trust.ts" +import { writeFileAtomic } from "./fs-atomic.ts" +import type { CodingRunOutcome } from "./coding-outcomes.ts" + +const columns: readonly CodingRunOutcome[] = [ + "correct", + "incorrect", + "timed-out", + "grading-failure", + "infrastructure-failure", +] + +async function main(): Promise { + const sha = process.env.CANDIDATE_SHA + const out = process.env.EVAL_OUT + const workflowSummary = process.env.GITHUB_STEP_SUMMARY + if (!sha || !out || !workflowSummary) throw new Error("Missing summary configuration") + if ((await resolveCommit("HEAD", process.cwd())) !== sha) throw new Error("Candidate checkout changed") + + // EvalWorkflow.SummaryBound: the shared validator owns pins, repetition + // keys, and metric validation. This consumer also requires the current suite. + const parsed: unknown = JSON.parse(await fs.readFile(path.join(out, "side-results.json"), "utf8")) + const result = validateSideResultFile(parsed, "candidate", sha) + if ( + result.pins.suiteId !== CODING_SUITE_ID || + result.runs.some((run) => run.outcome?.outcome !== run.metrics.outcome.outcome) + ) { + throw new Error("Candidate suite or outcome records differ") + } + + const names = [...new Set(result.runs.map((run) => run.fixtureName))].sort() + const rows = names.map((name) => { + const runs = result.runs.filter((run) => run.fixtureName === name) + const counts = columns.map((outcome) => runs.filter((run) => run.metrics.outcome.outcome === outcome).length) + return `| ${name} | ${counts.join(" | ")} |` + }) + const faults = result.runs.filter((run) => + ["infrastructure-failure", "grading-failure"].includes(run.metrics.outcome.outcome), + ).length + // Only validated fixture names, the exact commit, and numeric counts + // enter Markdown. Provider output and failure messages stay out. + const lines = [ + "# Coding task evaluation", + "", + `Candidate commit: \`${sha}\``, + "", + "Candidate results only. No approved baseline comparison is available.", + "", + "Results are advisory. This workflow does not publish a release or promote a baseline.", + "", + "| Fixture | Correct | Incorrect | Timed out | Grading failure | Infrastructure failure |", + "| --- | --- | --- | --- | --- | --- |", + ...rows, + "", + `Each fixture has ${DEFAULT_REPETITIONS} attempts. Small samples do not establish statistical significance.`, + "", + "Token use, tool calls, duration, accounting status, and cost availability are in side-results.json.", + "", + "Cost estimates remain unavailable until the price table contains maintained rates.", + "", + ] + if (faults > 0) + lines.push( + `**Evaluation failed:** infrastructure or grading failed in ${faults} of ${result.runs.length} attempts.`, + "", + ) + const markdown = lines.join("\n") + await writeFileAtomic(path.join(out, "candidate-report.md"), markdown) + await fs.appendFile(workflowSummary, markdown) + // EvalWorkflow.WorkflowHealthy: retain the report before failing the job. + if (faults > 0) + console.log( + `::error::Evaluation infrastructure or grading failed in ${faults} of ${result.runs.length} attempts.`, + ) + return faults > 0 ? 1 : 0 +} + +try { + process.exitCode = await main() +} catch { + // Result files and thrown errors can contain arbitrary text. Publish a + // fixed message, with no host paths, settings, or provider diagnostics. + const message = + "Evaluation results are missing or invalid, or summary publication failed. Check the logs and available traces.\n" + if (process.env.GITHUB_STEP_SUMMARY) await fs.appendFile(process.env.GITHUB_STEP_SUMMARY, message).catch(() => {}) + console.error("::error::Evaluation summary failed. Check the result artifact and candidate SHA.") + process.exitCode = 1 +} diff --git a/scripts/agent-evals/host-build.test.ts b/scripts/agent-evals/host-build.test.ts new file mode 100644 index 00000000000..10d0f84cb70 --- /dev/null +++ b/scripts/agent-evals/host-build.test.ts @@ -0,0 +1,59 @@ +import assert from "node:assert/strict" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { it } from "node:test" +import { verifyHostBuildOutputs } from "./host-build.ts" + +// These are the real extension entry and webview assets. Keep the oracle +// independent of the implementation's required-output list. +const files = ["src/dist/extension.js", "src/webview-ui/build/assets/index.js", "src/webview-ui/build/assets/index.css"] +const kinds = ["missing", "empty", "directory", "file"] as const + +it("launch readiness requires all three nonempty regular build outputs", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "host-build-property-")) + try { + for (const extension of kinds) + for (const script of kinds) + for (const styles of kinds) { + const inputs = [extension, script, styles] + const root = path.join(dir, inputs.join("-")) + for (const [index, kind] of inputs.entries()) { + const relative = files[index] + assert.ok(relative) + const target = path.join(root, relative) + if (kind === "missing") continue + await fs.mkdir(path.dirname(target), { recursive: true }) + if (kind === "directory") await fs.mkdir(target) + else await fs.writeFile(target, kind === "empty" ? "" : "build output") + } + const diagnostic = path.join(root, "artifacts", "preparation-diagnostics.txt") + const check = verifyHostBuildOutputs(root, diagnostic) + if (inputs.every((kind) => kind === "file")) await check + else await assert.rejects(check, /prepared host build outputs are missing or invalid/) + const report = await fs.readFile(diagnostic, "utf8") + const expected = ["extensionEntry", "webviewScript", "webviewStyles"] + .map((name, index) => `${name}: ${inputs[index] === "file" ? "ready" : "missing-or-invalid"}\n`) + .join("") + assert.equal(report, expected, inputs.join("/")) + } + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } +}) + +it("rejects a symlink instead of accepting a file outside the build", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "host-build-link-")) + try { + for (const file of files) { + await fs.mkdir(path.dirname(path.join(root, file)), { recursive: true }) + await fs.writeFile(path.join(root, file), "build output") + } + const target = path.join(root, "src/dist/extension.js") + await fs.rename(target, path.join(root, "outside.js")) + await fs.symlink(path.join(root, "outside.js"), target) + await assert.rejects(verifyHostBuildOutputs(root, path.join(root, "diagnostics.txt")), /extensionEntry/) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } +}) diff --git a/scripts/agent-evals/host-build.ts b/scripts/agent-evals/host-build.ts new file mode 100644 index 00000000000..f97cfe169c0 --- /dev/null +++ b/scripts/agent-evals/host-build.ts @@ -0,0 +1,31 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { writeFileAtomic } from "./fs-atomic.ts" + +const REQUIRED_OUTPUTS = { + extensionEntry: "src/dist/extension.js", + webviewScript: "src/webview-ui/build/assets/index.js", + webviewStyles: "src/webview-ui/build/assets/index.css", +} as const + +// EvalHostPreparation.LaunchRequiresBuildOutputs: build exit status alone +// does not prove that VS Code has an extension entry and a working webview. +export async function verifyHostBuildOutputs(root: string, diagnosticsPath: string): Promise { + const checks = await Promise.all( + Object.entries(REQUIRED_OUTPUTS).map(async ([name, relative]) => { + const stat = await fs.lstat(path.join(root, relative)).catch((error: unknown) => { + if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined + throw error + }) + return { name, ready: stat?.isFile() === true && stat.size > 0 } + }), + ) + // Fixed readiness labels only. Never publish host logs, settings, or keys. + await fs.mkdir(path.dirname(diagnosticsPath), { recursive: true }) + await writeFileAtomic( + diagnosticsPath, + checks.map((check) => `${check.name}: ${check.ready ? "ready" : "missing-or-invalid"}\n`).join(""), + ) + const missing = checks.filter((check) => !check.ready).map((check) => check.name) + if (missing.length > 0) throw new Error(`prepared host build outputs are missing or invalid: ${missing.join(", ")}`) +} From 32d039838801f09fd2c3fe0d57ef253f2178b3f3 Mon Sep 17 00:00:00 2001 From: Elliott de Launay Date: Mon, 30 Nov 2026 05:02:05 +0000 Subject: [PATCH 3/3] refactor(evals): centralize outcome validation and simplify TLA specs --- .github/workflows/agent-evals.yml | 6 +- .../tla/EvalComparisonInputs.NoCheckKeys.cfg | 2 + .../EvalComparisonInputs.NoCheckOutcomes.cfg | 11 ++ .../tla/EvalComparisonInputs.NoCheckTimer.cfg | 2 + .../EvalComparisonInputs.NoCheckValues.cfg | 2 + .../architecture/tla/EvalComparisonInputs.cfg | 2 + .../architecture/tla/EvalComparisonInputs.tla | 80 ++++++------- .../tla/EvalHostPreparation.ExtraBuild.cfg | 7 ++ .../EvalHostPreparation.NoCheckOutputs.cfg | 2 + docs/architecture/tla/EvalHostPreparation.cfg | 2 + docs/architecture/tla/EvalHostPreparation.tla | 56 +++++---- .../tla/EvalScriptPath.NoDecode.cfg | 5 + docs/architecture/tla/EvalScriptPath.cfg | 5 + docs/architecture/tla/EvalScriptPath.tla | 29 +++++ docs/architecture/tla/EvalScriptPathMC.tla | 8 ++ docs/architecture/tla/EvalWorkflow.tla | 109 +++++------------- scripts/agent-evals-workflow.test.mjs | 33 ++++-- scripts/agent-evals/README.md | 15 +-- scripts/agent-evals/coding-compare.ts | 12 +- scripts/agent-evals/coding-report.test.ts | 37 +++++- scripts/agent-evals/coding-side.mts | 5 - scripts/agent-evals/coding-side.test.ts | 8 +- scripts/agent-evals/coding-summary.mts | 7 +- 23 files changed, 244 insertions(+), 201 deletions(-) create mode 100644 docs/architecture/tla/EvalComparisonInputs.NoCheckOutcomes.cfg create mode 100644 docs/architecture/tla/EvalHostPreparation.ExtraBuild.cfg create mode 100644 docs/architecture/tla/EvalScriptPath.NoDecode.cfg create mode 100644 docs/architecture/tla/EvalScriptPath.cfg create mode 100644 docs/architecture/tla/EvalScriptPath.tla create mode 100644 docs/architecture/tla/EvalScriptPathMC.tla diff --git a/.github/workflows/agent-evals.yml b/.github/workflows/agent-evals.yml index d2c8ffc4aaa..8e5a6ce6538 100644 --- a/.github/workflows/agent-evals.yml +++ b/.github/workflows/agent-evals.yml @@ -4,9 +4,6 @@ name: Coding task evaluations # Trust boundaries: docs/architecture/tla/EvalWorkflow.tla. on: workflow_dispatch: - # Keep until the fixed workflow passes its full 15-attempt CI run. - push: - branches: [issue/2085] permissions: contents: read @@ -17,8 +14,7 @@ concurrency: jobs: evaluate: - # Remove the branch exception after CI validation and before merge. - if: (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main') || (github.event_name == 'push' && github.ref == 'refs/heads/issue/2085') + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' runs-on: ubuntu-24.04 timeout-minutes: 120 environment: final-vscode-review-smoke diff --git a/docs/architecture/tla/EvalComparisonInputs.NoCheckKeys.cfg b/docs/architecture/tla/EvalComparisonInputs.NoCheckKeys.cfg index 067e843524d..6064eea8fe6 100644 --- a/docs/architecture/tla/EvalComparisonInputs.NoCheckKeys.cfg +++ b/docs/architecture/tla/EvalComparisonInputs.NoCheckKeys.cfg @@ -7,3 +7,5 @@ CONSTANT ExpectedKeys <- Keys SPECIFICATION Spec INVARIANTS KeysComplete TimerSafe ValuesSafe CHECK_DEADLOCK FALSE +CONSTANT CheckOutcomes <- Enabled +INVARIANT OutcomesAgree diff --git a/docs/architecture/tla/EvalComparisonInputs.NoCheckOutcomes.cfg b/docs/architecture/tla/EvalComparisonInputs.NoCheckOutcomes.cfg new file mode 100644 index 00000000000..223a30eed7b --- /dev/null +++ b/docs/architecture/tla/EvalComparisonInputs.NoCheckOutcomes.cfg @@ -0,0 +1,11 @@ +CONSTANT CheckKeys <- Enabled +CONSTANT CheckTimer <- Enabled +CONSTANT CheckValues <- Enabled +CONSTANT Inputs <- MCInputs +CONSTANT Minutes <- MCMinutes +CONSTANT ExpectedKeys <- Keys +SPECIFICATION Spec +INVARIANTS KeysComplete TimerSafe ValuesSafe +CHECK_DEADLOCK FALSE +CONSTANT CheckOutcomes <- Disabled +INVARIANT OutcomesAgree diff --git a/docs/architecture/tla/EvalComparisonInputs.NoCheckTimer.cfg b/docs/architecture/tla/EvalComparisonInputs.NoCheckTimer.cfg index b2da539f695..6d9e8399aee 100644 --- a/docs/architecture/tla/EvalComparisonInputs.NoCheckTimer.cfg +++ b/docs/architecture/tla/EvalComparisonInputs.NoCheckTimer.cfg @@ -7,3 +7,5 @@ CONSTANT ExpectedKeys <- Keys SPECIFICATION Spec INVARIANTS KeysComplete TimerSafe ValuesSafe CHECK_DEADLOCK FALSE +CONSTANT CheckOutcomes <- Enabled +INVARIANT OutcomesAgree diff --git a/docs/architecture/tla/EvalComparisonInputs.NoCheckValues.cfg b/docs/architecture/tla/EvalComparisonInputs.NoCheckValues.cfg index d1327ce24ee..1703561ad2c 100644 --- a/docs/architecture/tla/EvalComparisonInputs.NoCheckValues.cfg +++ b/docs/architecture/tla/EvalComparisonInputs.NoCheckValues.cfg @@ -7,3 +7,5 @@ CONSTANT ExpectedKeys <- Keys SPECIFICATION Spec INVARIANTS KeysComplete TimerSafe ValuesSafe CHECK_DEADLOCK FALSE +CONSTANT CheckOutcomes <- Enabled +INVARIANT OutcomesAgree diff --git a/docs/architecture/tla/EvalComparisonInputs.cfg b/docs/architecture/tla/EvalComparisonInputs.cfg index 0c0d8fd0cbf..5fd6f13d9e1 100644 --- a/docs/architecture/tla/EvalComparisonInputs.cfg +++ b/docs/architecture/tla/EvalComparisonInputs.cfg @@ -7,3 +7,5 @@ CONSTANT ExpectedKeys <- Keys SPECIFICATION Spec INVARIANTS KeysComplete TimerSafe ValuesSafe CHECK_DEADLOCK FALSE +CONSTANT CheckOutcomes <- Enabled +INVARIANT OutcomesAgree diff --git a/docs/architecture/tla/EvalComparisonInputs.tla b/docs/architecture/tla/EvalComparisonInputs.tla index 985bbff1e8a..3b2512179b1 100644 --- a/docs/architecture/tla/EvalComparisonInputs.tla +++ b/docs/architecture/tla/EvalComparisonInputs.tla @@ -1,53 +1,39 @@ ---- MODULE EvalComparisonInputs ---- -\* Source: codingRepetitionPlan supplies execution and validation keys. -\* Source: CLI minutes and side-results.json. Sink: timer and positional pairs. -\* Failures: a large timer runs at 1 ms; partial keys shift positional pairs. -\* Invariants: TimerSafe and KeysComplete forbid these failures. -\* Expect: old guards fail both checks. These invariants follow the review. -\* PR 2154 threads: discussion_r4624089802 and discussion_r4624089824. -\* Review: 0 covered, 2 added, 0 gap. Parsing and metric content are oracles. -\* Scope: each integer key stands for one fixture and repetition pair. -\* Property: coding-report.test.ts and coding-compare-script.test.ts. -\* Result: fixed passes in 640 states. No new code bug was found. -\* Control: NoCheckKeys fails KeysComplete; NoCheckTimer fails TimerSafe. -\* Replay: Missing keys and 35792 minutes fail on HEAD and pass with the fixes. -\* Cost: this review took about 12 agent minutes total. Each TLC run took under 1 second. -\* Gate: 401 eval tests, eval type check, and shared ESLint pass. -\* Run each EvalComparisonInputs config with EvalComparisonInputsMC on each fix commit. -\* Refactor: one code plan replaces two copies. Expect no new model failure. -\* Result: all input checks keep their prior results. No new code bug was found. -\* Property: coding-fixtures.test.ts checks literal names, versions, order, and fresh entries. -\* Sabotage: omit one fixture from the shared plan. The independent code test fails. -\* Restored plan passes. The plan builder is outside the input model. -\* Cost: the simplification took about 3 agent minutes across these models. -\* Source: side-results.json metrics. Sink: paired deltas, cost and outcome rows. -\* Failure: a null duration reads as zero and shows as a speedup. -\* Invariant: ValuesSafe accepts only well-formed values. It follows review. -\* PR 2154 discussion_r4719753641. Review: 0 covered, 1 added, 0 gap. -\* Expect: the old validator fails ValuesSafe. No new bug is expected. -\* Result: fixed passes in 696 states. NoCheckValues accepts a null duration. -\* Replay: the null duration test fails on the old validator and passes now. -\* Findings: no new code bug was found by TLC. No false alarm was found. -\* Property: coding-report.test.ts checks bad kinds for each report metric. -\* Gate: 408 eval tests, eval type check, and shared ESLint pass. -\* Lint: src ESLint excludes scripts. Suppression counts did not change. -\* Cost: about 10 agent minutes for both fixes. Each TLC run took under 1 second. -\* PR 2154 discussion_r4725130159: the test helper kept an absent duration. -\* Review: 0 covered, 0 added, 1 gap. This model cannot check test fixture creation. -\* Source: coding-report.test.ts check helper. Sink: validateSideResultFile. -\* Expect: no model change. ValueOk already permits an absent duration. -\* Property: serialize the whole fixture, then assert that durationMs is absent. -\* Sabotage: the old helper fails the absence assertion. The fixed helper passes. -\* Result: fixed passes in 696 states. All three controls fail their invariants. -\* Findings: no new code bug or false alarm was found. No model state was added. -\* Gate: 410 eval tests, eval and extension type checks, and shared ESLint pass. -\* Cost: shared with the EvalComparisonRelease review, about 10 agent minutes. +\* Source: codingRepetitionPlan, CLI minutes, and side-results.json. +\* Sink: timers, paired report values, and candidate summary outcomes. +\* Failures: timer overflow, incomplete keys, invalid metric values, or inconsistent outcomes. +\* Invariants: TimerSafe, KeysComplete, ValuesSafe, and OutcomesAgree. +\* Scope: parsing and metric content are oracles. Integer keys stand for fixture/repetition pairs. +\* Expect: shared validation holds; removing each check violates its invariant. +\* Stance: review findings preceded their invariants. Outcome agreement follows the simplification request. +\* Review total: 0 covered, 3 added, 1 gap. +\* PR 2154: discussion_r4624089802, discussion_r4624089824, and discussion_r4719753641 added checks. +\* PR 2154: discussion_r4725130159 is a gap; this model cannot check test fixture construction. +\* Replay: incomplete keys, 35792 minutes, and null duration fail with the fixed validator. +\* Replay: the corrected JSON fixture helper preserves absent duration; the old helper fails its assertion. +\* Property: coding-report.test.ts checks input kinds, key sets, and baseline/candidate outcome agreement. +\* Property: coding-compare-script.test.ts checks CLI timer bounds. +\* Property: coding-fixtures.test.ts checks literal plan entries independently of the builder. +\* Refactor: move outcome agreement from coding-summary.mts to validateSideResultFile. +\* Summary behavior stays the same. Comparison now rejects inconsistent record and metric outcomes. +\* Expect: NoCheckOutcomes fails; valid outcomes remain accepted for both side labels. +\* Prior result: base passed in 696 states. All three original controls failed their invariants. +\* Prior findings: no additional code bug or false alarm was found by TLC. +\* Prior gate: 410 evaluation tests, both type checks, and applicable lint passed. +\* Prior cost: about 35 agent minutes, including shared review work. +\* Run: TLA_JAR= docs/architecture/tla/check.sh EvalComparisonInputs. +\* This model does not prove the implementation correct. +\* Result: base passes in 708 states. All four negative controls fail their invariants. +\* Replay: both side-label tests fail on the old validator and pass with shared outcome validation. +\* Findings: the old comparison accepted inconsistent outcomes. No additional model defect was found. +\* Gate: 426 evaluation tests, 33 workflow tests, both type checks, and applicable lint pass. +\* Cost: about 9 additional agent minutes shared across this simplification. EXTENDS Naturals, Sequences, FiniteSets -CONSTANTS Inputs, Minutes, ExpectedKeys, CheckKeys, CheckTimer, CheckValues +CONSTANTS Inputs, Minutes, ExpectedKeys, CheckKeys, CheckTimer, CheckValues, CheckOutcomes VARIABLES keys, agrees, minutes, metric, result vars == <> \* A metric is one field that the report reads, and the kind of its JSON value. -Metrics == {"duration", "usd", "outcome"} \X {"valid", "absent", "null", "wrongType", "outOfRange"} +Metrics == {"duration", "usd", "outcome"} \X {"valid", "absent", "null", "wrongType", "outOfRange", "mismatched"} ValueOk == metric[2] = "valid" \/ metric = <<"duration", "absent">> KeySet == {keys[i] : i \in DOMAIN keys} Complete == KeySet = ExpectedKeys /\ Len(keys) = Cardinality(ExpectedKeys) /\ agrees @@ -58,7 +44,8 @@ Init == /\ keys \in Inputs /\ agrees \in BOOLEAN /\ minutes \in Minutes /\ result = "pending" Validate == /\ result = "pending" /\ result' = IF (~CheckKeys \/ Complete) /\ (~CheckTimer \/ minutes <= 35791) - /\ (~CheckValues \/ ValueOk) + /\ (~CheckValues \/ ValueOk \/ metric = <<"outcome", "mismatched">>) + /\ (~CheckOutcomes \/ metric # <<"outcome", "mismatched">>) THEN "accepted" ELSE "rejected" /\ UNCHANGED <> Next == Validate @@ -66,4 +53,5 @@ Spec == Init /\ [][Next]_vars KeysComplete == result = "accepted" => Complete ValuesSafe == result = "accepted" => ValueOk TimerSafe == result = "accepted" => minutes <= 2147483647 \div 60000 +OutcomesAgree == result = "accepted" => metric # <<"outcome", "mismatched">> ==== diff --git a/docs/architecture/tla/EvalHostPreparation.ExtraBuild.cfg b/docs/architecture/tla/EvalHostPreparation.ExtraBuild.cfg new file mode 100644 index 00000000000..03ead0824a1 --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.ExtraBuild.cfg @@ -0,0 +1,7 @@ +CONSTANT Outputs <- MCOutputs +CONSTANT CheckOutputs <- Enabled +SPECIFICATION Spec +INVARIANT LaunchRequiresBuildOutputs +CHECK_DEADLOCK FALSE +CONSTANT ExtraWebviewBuild <- Enabled +INVARIANT WebviewBuiltOnce diff --git a/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg b/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg index 06c744f8efe..e6d55162c35 100644 --- a/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg +++ b/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg @@ -3,3 +3,5 @@ CONSTANT CheckOutputs <- Disabled SPECIFICATION Spec INVARIANT LaunchRequiresBuildOutputs CHECK_DEADLOCK FALSE +CONSTANT ExtraWebviewBuild <- Disabled +INVARIANT WebviewBuiltOnce diff --git a/docs/architecture/tla/EvalHostPreparation.cfg b/docs/architecture/tla/EvalHostPreparation.cfg index 7ecf3240130..3e703341888 100644 --- a/docs/architecture/tla/EvalHostPreparation.cfg +++ b/docs/architecture/tla/EvalHostPreparation.cfg @@ -3,3 +3,5 @@ CONSTANT CheckOutputs <- Enabled SPECIFICATION Spec INVARIANT LaunchRequiresBuildOutputs CHECK_DEADLOCK FALSE +CONSTANT ExtraWebviewBuild <- Disabled +INVARIANT WebviewBuiltOnce diff --git a/docs/architecture/tla/EvalHostPreparation.tla b/docs/architecture/tla/EvalHostPreparation.tla index c43f882afa4..479e0253cc1 100644 --- a/docs/architecture/tla/EvalHostPreparation.tla +++ b/docs/architecture/tla/EvalHostPreparation.tla @@ -1,36 +1,32 @@ ---- MODULE EvalHostPreparation ---- -\* Source: coding-side.mts preparation loop and verifyHostBuildOutputs file checks. +\* Source: coding-side.mts preparation loop, Turbo bundle dependency, and verifyHostBuildOutputs. \* Sink: the first createHostRuntime launch in the prepared worktree. -\* Failure: a successful workspace build can leave the extension entry missing. -\* Invariant: LaunchRequiresBuildOutputs forbids launch with incomplete outputs. -\* Expect: the old flow and NoCheckOutputs fail. A preflight guard holds. -\* Stance: the missing bundle command was found before this invariant was written. -\* Scope: build success and filesystem inspection are oracles, not build implementations. -\* Inputs name the availability of the extension, webview script, and webview styles. -\* Property tests: host-build.test.ts and coding-side.test.ts. -\* Review: 0 covered, 0 added, 0 gap. No review findings received. -\* Result: the guarded model passes in 17 states. NoCheckOutputs violates the invariant. -\* Replay: the old CLI fails locally because src/dist/extension.js is missing after pnpm build. -\* Replay: removing the output guard or restoring the old build command fails the code tests. -\* Property: all 64 file-kind combinations accept only three nonempty regular outputs. -\* Property: the CLI rejects incomplete builds and retains fixed readiness diagnostics. -\* Findings: the model reproduces the known build fault. No additional bug or false alarm was found. -\* Gate: 423 evaluation tests, the evaluation type check, and applicable lint checks pass. -\* Live replay: the fixed CLI grades all five fixtures correct in containers, one attempt each. -\* The local replay evaluates the approved extension commit with the updated runner. -\* This is not the default 15-attempt CI run or evidence of statistical significance. -\* Cost: about 16 agent minutes shared with EvalWorkflow, including both live runs. +\* Failures: launch with incomplete outputs, or build the webview twice per side. +\* Invariants: LaunchRequiresBuildOutputs and WebviewBuiltOnce. +\* Scope: build success and file inspection are oracles. Output kinds are bounded in code tests. +\* Expect: output guards and one bundle hold. Removed output checks and an extra build fail. +\* Stance: the missing bundle fault and review finding preceded their invariants. +\* Review: 0 covered, 1 added, 0 gap. PR 2781 discussion_r4734380494. +\* Replay: the old workspace build misses extension.js; removing preflight fails the CLI tests. +\* Replay: restoring the standalone webview build fails the preparation CLI test. +\* Property: host-build.test.ts checks 64 file-kind combinations and symlink rejection. +\* Property: coding-side.test.ts checks command order, isolation, interruption, and preflight. +\* Live: the fixed runner passed five local attempts and the full 15-attempt CI run. +\* Refactor: derive WebviewBuilds from ExtraWebviewBuild instead of storing duplicate state. +\* Expect: the same 17 states and both negative controls remain sufficient. +\* Prior result: base passes in 17 states. NoCheckOutputs and ExtraBuild fail. +\* Findings: TLC reproduced known faults. No additional code bug or false alarm was found. +\* Prior gate: 424 evaluation tests, 33 workflow tests, both type checks, and applicable lint passed. +\* Prior cost: about 34 agent minutes, shared with the workflow and path changes. \* Run: TLA_JAR= docs/architecture/tla/check.sh EvalHostPreparation. -\* A model check covers this model. It does not prove the implementation correct. -\* Refactor: one ordered preparation loop retains separate bounded child processes. -\* Expect: LaunchRequiresBuildOutputs and its removed-guard control keep their results. -\* Command ordering and child environments remain code properties outside this output model. -\* Refactor result: the base still passes in 17 states. NoCheckOutputs still fails its invariant. -\* Code tests retain command order, preparation isolation, interruption, and incomplete-build checks. -\* Replay: skipping output verification in the preparation loop fails the incomplete-build CLI tests. -\* Findings: no new model defect was found. Cost is shared with the EvalWorkflow refactor. +\* This model does not prove the implementation correct. +\* Result: base still passes in 17 states. Both negative controls fail. +\* Finding: a constant invariant prevented state exploration in ExtraBuild. +\* Refinement: check the derived build count at host launch; ExtraBuild now has a state counterexample. +\* Gate: 426 evaluation tests, 33 workflow tests, both type checks, and applicable lint pass. +\* Cost: about 9 additional agent minutes shared across this simplification. EXTENDS Naturals -CONSTANTS Outputs, CheckOutputs +CONSTANTS Outputs, CheckOutputs, ExtraWebviewBuild VARIABLES outputs, stage vars == <> Complete == outputs.extension /\ outputs.webviewScript /\ outputs.webviewStyles @@ -45,4 +41,6 @@ Launch == /\ stage = "ready" Next == Verify \/ Launch Spec == Init /\ [][Next]_vars LaunchRequiresBuildOutputs == stage = "launched" => Complete +WebviewBuilds == IF ExtraWebviewBuild THEN 2 ELSE 1 +WebviewBuiltOnce == stage = "launched" => WebviewBuilds = 1 ==== diff --git a/docs/architecture/tla/EvalScriptPath.NoDecode.cfg b/docs/architecture/tla/EvalScriptPath.NoDecode.cfg new file mode 100644 index 00000000000..68767a85b28 --- /dev/null +++ b/docs/architecture/tla/EvalScriptPath.NoDecode.cfg @@ -0,0 +1,5 @@ +CONSTANT Paths <- MCPaths +CONSTANT Decode <- Disabled +SPECIFICATION Spec +INVARIANT ScriptPathPreserved +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalScriptPath.cfg b/docs/architecture/tla/EvalScriptPath.cfg new file mode 100644 index 00000000000..ceed2a09e9b --- /dev/null +++ b/docs/architecture/tla/EvalScriptPath.cfg @@ -0,0 +1,5 @@ +CONSTANT Paths <- MCPaths +CONSTANT Decode <- Enabled +SPECIFICATION Spec +INVARIANT ScriptPathPreserved +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalScriptPath.tla b/docs/architecture/tla/EvalScriptPath.tla new file mode 100644 index 00000000000..1d14ca1ca66 --- /dev/null +++ b/docs/architecture/tla/EvalScriptPath.tla @@ -0,0 +1,29 @@ +---- MODULE EvalScriptPath ---- +\* Source: runSummary file URL. Sink: Node script argument. +\* Failure: URL encoding changes the filesystem path sent to Node. +\* Invariant: ScriptPathPreserved requires the original path. +\* Scope: encoding and decoding are bounded oracles, not a copy of Node URL parsing. +\* Expect: pathname fails for encoded characters; fileURLToPath preserves the path. +\* Stance: the review finding preceded this invariant. +\* Review: 0 covered, 1 added, 0 gap. PR 2781 discussion_r4734380488. +\* Result: base passes in 3 states. NoDecode violates ScriptPathPreserved. +\* Replay: pathname fails the real path-domain test. fileURLToPath passes all four paths. +\* Property: workflow tests launch scripts from plain, space, percent, and Unicode paths. +\* Findings: no additional code bug or false alarm was found. +\* Prior gate: 424 evaluation tests, 33 workflow tests, both type checks, and applicable lint passed. +\* Prior cost: about 10 agent minutes, shared with the workflow and host review changes. +\* Change: consolidate header evidence. Expect no model or code behavior change. +\* Run: TLA_JAR= docs/architecture/tla/check.sh EvalScriptPath. +\* This model does not prove Node or the implementation correct. +\* Result: base still passes in 3 states. NoDecode still fails. No behavior changed. +\* Gate: 426 evaluation tests, 33 workflow tests, both type checks, and applicable lint pass. +\* Cost: about 9 additional agent minutes shared across this simplification. +EXTENDS Naturals +CONSTANTS Paths, Decode +VARIABLE input +vars == <> +Init == input \in Paths +Spec == Init /\ [][UNCHANGED input]_vars +Argument == IF Decode THEN input.original ELSE input.encoded +ScriptPathPreserved == Argument = input.original +==== diff --git a/docs/architecture/tla/EvalScriptPathMC.tla b/docs/architecture/tla/EvalScriptPathMC.tla new file mode 100644 index 00000000000..4e0f4a31177 --- /dev/null +++ b/docs/architecture/tla/EvalScriptPathMC.tla @@ -0,0 +1,8 @@ +---- MODULE EvalScriptPathMC ---- +EXTENDS EvalScriptPath +Enabled == TRUE +Disabled == FALSE +MCPaths == { [original |-> "/tmp/Zoo/code.mjs", encoded |-> "/tmp/Zoo/code.mjs"], + [original |-> "/tmp/Zoo Code/code.mjs", encoded |-> "/tmp/Zoo%20Code/code.mjs"], + [original |-> "/tmp/Zoo%Code/code.mjs", encoded |-> "/tmp/Zoo%25Code/code.mjs"] } +==== diff --git a/docs/architecture/tla/EvalWorkflow.tla b/docs/architecture/tla/EvalWorkflow.tla index ff232fc3dcf..711f2dedd6a 100644 --- a/docs/architecture/tla/EvalWorkflow.tla +++ b/docs/architecture/tla/EvalWorkflow.tla @@ -1,91 +1,40 @@ ---- MODULE EvalWorkflow ---- -\* Source: agent-evals.yml dispatch, evaluate.if, and environment approval. -\* Sink: Evaluate candidate starts coding-evals:side with the provider key. -\* Source: side-results.json and checkout HEAD after the candidate run. -\* Sink: coding-summary.mts publishes candidate-report.md and the summary. -\* Failure: an unapproved event or ref can reach the provider job. -\* Failure: provider execution starts with a different commit or dirty tree. -\* Failure: incomplete or foreign results become an accepted summary. -\* Invariants: SecretsAuthorized, ExecutionTrusted, and SummaryBound. -\* Expect: current guards hold. Each removed guard violates an invariant. -\* Stance: implementation was read before these first invariants were written. -\* Scope: GitHub environment approval and side output validation are oracles. -\* Scope: payload kinds stand for valid JSON inputs and a missing result file. -\* Scope: artifact retention, cancellation, and hosted scheduling are outside the model. -\* Assumption: the environment requires approval for main and the temporary issue/2085 branch. -\* Limit: this model cannot inspect repository environment settings. -\* Limit: no local actor changes the tree between a shell guard and execution. -\* The isolated side runner checks its own worktree outside this model. -\* Property tests: scripts/agent-evals-workflow.test.mjs. -\* Review ratchet: 0 covered, 2 added, 0 gap. Both findings strengthen the trigger input rule. -\* Result: EvalWorkflow.cfg passes in 1760 distinct states. No new bug was found. -\* Controls: NoTrigger and NoApproval violate SecretsAuthorized. -\* Controls: NoCandidate violates ExecutionTrusted. NoHead and NoReport violate SummaryBound. -\* Replay: temporary workflow and shell guard removal fails the corresponding code tests. -\* Replay: NoApproval removes the environment declaration, not a hosted reviewer setting. -\* No live credential was used. No false alarm was found in the bounded code tests. -\* Gate before simplification: all six TLC configs and 23 code tests give the expected results. -\* Cost: about 8 agent minutes. Each TLC config completes in under 2 seconds. +\* Source: agent-evals.yml event, ref, environment approval, and checkout guards. +\* Source: side-results.json through validateSideResultFile and coding-summary.mts. +\* Sink: provider execution, candidate-report.md, and workflow exit status. +\* Failures: unauthorized execution, changed checkout, invalid reports, or hidden infrastructure faults. +\* Invariants: SecretsAuthorized, ExecutionTrusted, SummaryBound, and WorkflowHealthy. +\* Policy: only manual main runs can receive approved environment credentials. +\* Scope: approval and validation are oracles. Hosted scheduling and retention are outside the model. +\* Limit: the model cannot inspect GitHub reviewer settings or prove implementation correctness. +\* Assumption: no local actor changes the checkout between its guard and execution. +\* Expect: the final guards hold. Each removed guard violates its invariant. +\* Stance: implementation and review findings preceded their corresponding invariant extensions. +\* Review: 0 covered, 2 added, 0 gap. Both findings require the final main-only trigger rule. +\* PR 2781: discussion_r4733706220 and discussion_r4733706224. +\* Runtime finding: job 141531999567 was green despite 15 infrastructure failures. +\* Replay: the original failed artifact now fails after its report is published. +\* Replay: removed trigger, approval declaration, checkout, report, and health guards fail code tests. +\* Live: run 46338736128 passed all 15 attempts before temporary branch access was removed. +\* Environment audit: main remains allowed with required reviewers; issue/2085 was removed. +\* Refactor: outcome agreement belongs to the shared validator. Current-suite selection stays in the summary. +\* Expect: moving that rule preserves summary acceptance and rejection. No new model defect is expected. +\* Result before this refactor: base passes in 6322 states; all six negative controls fail. +\* Property: scripts/agent-evals-workflow.test.mjs checks triggers, guards, inputs, and fault publication. +\* Prior gate: 424 evaluation tests, 33 workflow tests, both type checks, and applicable lint passed. +\* Prior cost: about 54 agent minutes across implementation, review, validation, and corrections. \* Run: TLA_JAR= docs/architecture/tla/check.sh EvalWorkflow. -\* Run code tests: node --test scripts/agent-evals-workflow.test.mjs. -\* A model check covers this model. It does not prove the workflow correct. -\* Change: remove duplicate preparation checks. Keep the guard at provider execution. -\* Change: allow approved push runs on issue/2085 until live validation finishes. -\* Failure: another branch, main push, or a pull request reaches the provider job. -\* Expect: SecretsAuthorized covers the explicit branch exception. No new bug is expected. -\* Scope: one commit SHA is approved per run. Later branch pushes need new approval. -\* Remove the temporary trigger, branch rule, and model exception before merging. -\* Result after simplification: base passes in 2752 states. All five controls still fail. -\* Replay: each removed guard still fails the real workflow or summary code tests. -\* Gate: all 24 workflow tests and the evaluation type check pass. No new bug was found. -\* Gate: all 419 offline evaluation tests pass outside the child-process sandbox. -\* Cost: about 6 more agent minutes, including branch setup and model replay. -\* Runtime finding: PR 2781 job 141531999567 reported success with 15 infrastructure failures. -\* Failure: infrastructure or grader faults appear as a successful evaluation. -\* Invariant: WorkflowHealthy requires fault-free infrastructure before the job succeeds. -\* Expect: NoInfrastructure reproduces the green failed evaluation. Other guards remain necessary. -\* Source: coding-summary.mts fault count. Sink: summary step exit status after report publication. -\* Result: the updated base passes in 5508 states. All six removed-guard controls fail. -\* Replay: removing the health guard fails complete-failure and mixed-failure code tests. -\* Replay: the original CI artifact now exits with failure and preserves its Markdown report. -\* Gate: 26 workflow tests pass. Incorrect and timed-out tasks remain advisory. -\* Findings: the model reproduces the known status fault. No additional bug or false alarm was found. -\* Cost: shared with EvalHostPreparation. GitHub reviewer settings remain outside this model. -\* Review: remove the temporary branch exception from the workflow and its model. -\* PR 2781: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2781#discussion_r4733706220 -\* PR 2781: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2781#discussion_r4733706224 -\* Change: AllowedTrigger accepts manual main runs only after local validation passed. -\* Keep push and issue/2085 in MCInputs to check their rejection. -\* Expect: the base still holds. A restored branch exception fails the code trigger property. -\* Result after review: base passes in 5058 states. All six removed-guard controls fail. -\* Replay: restoring the branch disjunct fails the code trigger property. Restored code passes all 26 tests. -\* Findings: both review items use the stronger trigger rule. No additional bug or false alarm was found. -\* Environment audit: the temporary branch rule was removed. Main and required reviewers remain. -\* Cost: about 3 additional agent minutes for review, replay, and environment cleanup. -\* Refactor: coding-summary.mts uses validateSideResultFile. Summary and side CLI use one repetition default. -\* Failure: malformed metrics or disagreeing record outcomes become an accepted summary. -\* Expect: SummaryBound still holds with those input classes. No new bug is expected. -\* Preserve report publication before the infrastructure exit status is selected. -\* Refactor result: base passes in 6322 states. The larger domain adds malformed-metric input classes. -\* All six removed-guard controls fail. The code replays detect removed validation, commit binding, and failure status. -\* The real failed CI artifact still fails after report publication. No new model defect was found. -\* Gate: 32 workflow tests, 424 evaluation tests, both type checks, and applicable lint checks pass. -\* Cost: about 8 agent minutes shared with EvalHostPreparation. No live provider calls were made. -\* Correction: local five-attempt validation does not replace the full 15-attempt CI run. -\* Restore the branch exception until the fixed workflow passes that CI run. -\* Both review cleanup items remain deferred until CI passes, then must finish before merge. -\* Expect: the existing guards hold with the restored, explicitly approved trigger pair. -\* Result: the temporary-validation model passes in 6884 states. All six controls still fail. -\* Gate: all 32 workflow tests pass. The environment again permits issue/2085 with reviewer approval. -\* Cost: about 3 additional agent minutes for the correction and environment restoration. +\* Result: base still passes in 6322 states. All six negative controls still fail. +\* Summary tests preserve accepted inputs, rejected inputs, and report-before-failure behavior. +\* Gate: 426 evaluation tests, 33 workflow tests, both type checks, and applicable lint pass. +\* Cost: about 9 additional agent minutes shared across this simplification. EXTENDS Naturals CONSTANTS Inputs, CheckTrigger, CheckApproval, CheckCandidate, CheckReport, CheckHead, CheckInfrastructure VARIABLES input, stage vars == <> -AllowedTrigger == (input.event = "workflow_dispatch" /\ input.ref = "main") - \/ (input.event = "push" /\ input.ref = "issue/2085") +AllowedTrigger == input.event = "workflow_dispatch" /\ input.ref = "main" CandidateMatches == input.startMatches /\ input.clean PayloadComplete == input.payload = "complete" diff --git a/scripts/agent-evals-workflow.test.mjs b/scripts/agent-evals-workflow.test.mjs index 834a75f83fe..08af8473456 100644 --- a/scripts/agent-evals-workflow.test.mjs +++ b/scripts/agent-evals-workflow.test.mjs @@ -7,35 +7,34 @@ import { describe, it } from "node:test" import { runInNewContext } from "node:vm" import { createRequire } from "node:module" import { parse } from "yaml" +import { fileURLToPath, pathToFileURL } from "node:url" const workflow = parse(fs.readFileSync(new URL("../.github/workflows/agent-evals.yml", import.meta.url), "utf8")) const job = workflow.jobs.evaluate const candidate = job.steps.find((step) => step.id === "candidate") const tsxLoader = createRequire(import.meta.url).resolve("tsx") const summaryScript = new URL("./agent-evals/coding-summary.mts", import.meta.url) -const runSummary = (cwd, env) => - spawnSync(process.execPath, ["--import", tsxLoader, summaryScript.pathname], { cwd, env, encoding: "utf8" }) +const runSummary = (cwd, env, script = summaryScript) => + spawnSync(process.execPath, ["--import", tsxLoader, fileURLToPath(script)], { cwd, env, encoding: "utf8" }) const setOutcome = (run, outcome) => { run.outcome = { outcome, reason: "test" } run.metrics.outcome = { ...run.outcome } } describe("coding evaluation workflow", () => { - // EvalWorkflow.SecretsAuthorized: main dispatch and temporary branch push require approval. + // EvalWorkflow.SecretsAuthorized: only manual main runs receive credentials after approval. it("accepts only the approved event and ref pairs in the bounded trigger domain", () => { for (const event of ["workflow_dispatch", "pull_request", "pull_request_target", "push"]) { for (const ref of ["refs/heads/main", "refs/heads/issue/2085", "refs/heads/feature", "refs/tags/v1.0.0"]) { const allowed = runInNewContext(job.if, { github: { event_name: event, ref } }, { timeout: 1000 }) - const expected = - (event === "workflow_dispatch" && ref === "refs/heads/main") || - (event === "push" && ref === "refs/heads/issue/2085") + const expected = event === "workflow_dispatch" && ref === "refs/heads/main" assert.equal(allowed, expected, `${event}: ${ref}`) } } }) - it("requires environment approval and read-only permissions for main and temporary branch runs", () => { - assert.deepEqual(workflow.on, { workflow_dispatch: null, push: { branches: ["issue/2085"] } }) + it("requires environment approval and read-only permissions for manual main runs", () => { + assert.deepEqual(workflow.on, { workflow_dispatch: null }) assert.deepEqual(Object.keys(workflow.jobs), ["evaluate"]) assert.equal(job.environment, "final-vscode-review-smoke") assert.deepEqual(workflow.permissions, { contents: "read" }) @@ -270,3 +269,21 @@ describe("candidate summary", () => { })) } }) + +// EvalScriptPath.ScriptPathPreserved: Node receives the original script path. +it("launches file URLs from each supported checkout path", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "eval-path-")) + try { + for (const name of ["Zoo", "Zoo Code", "Zoo%Code", "Zoo-é"]) { + const directory = path.join(root, name) + fs.mkdirSync(directory) + const script = path.join(directory, "summary.mjs") + fs.writeFileSync(script, 'console.log("path-ready")') + const result = runSummary(root, process.env, pathToFileURL(script)) + assert.equal(result.status, 0, result.stderr) + assert.equal(result.stdout.trim(), "path-ready") + } + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/scripts/agent-evals/README.md b/scripts/agent-evals/README.md index bec2303b065..5538d071c92 100644 --- a/scripts/agent-evals/README.md +++ b/scripts/agent-evals/README.md @@ -209,15 +209,8 @@ Require reviewer approval and restrict deployment branches to `main` only. Set its `FINAL_SMOKE_OPENAI_API_KEY` secret to the provider key used by the coding fixtures. These settings are required. Workflow YAML cannot enforce environment reviewer settings. -Before merge, the workflow also permits push runs on the exact branch `issue/2085` for live CI validation. -Permit that branch in the environment rules and keep required reviewer approval enabled. -Commit and push the fixes, then approve the exact run SHA in Actions. -Local validation with one attempt per fixture does not replace this full 15-attempt CI check. -Pull request events and pushes to other branches cannot start the provider job. - -After the fixed workflow passes the full CI run, remove the branch trigger and guard exception before merging. -Update the workflow tests and model to require manual `main` runs only. -Remove `issue/2085` from the environment branch rules. Keep `main` and required approval. +The pre-merge CI validation passed all 15 attempts in run `46338736128`. +The temporary branch trigger and guard exception have been removed. A new manual workflow must first exist on the default branch. See [GitHub manual workflow requirements](https://docs.github.com/en/actions/how-tos/manage-workflow-runs/manually-run-a-workflow). @@ -226,7 +219,7 @@ After this workflow is merged, open Actions, select `Coding task evaluations`, a Review the exact commit SHA before you approve access to the environment. The workflow runs five fixtures three times. Each run uses the real provider and can incur charges. The side runner builds an isolated worktree and grades in Docker. -It runs `pnpm -w bundle` and the webview build in that worktree. +It runs `pnpm -w bundle` in that worktree. Turbo builds the webview as a bundle dependency. The generic workspace `pnpm build` command does not create the extension entry. Before launch, the runner requires a nonempty extension entry, webview script, and webview stylesheet. It writes their readiness to `artifacts/preparation-diagnostics.txt`, then stops if an output is missing or invalid. @@ -244,7 +237,7 @@ It also checks the current suite and agreement between run outcomes and metric o Cost estimates remain unavailable until maintainers add real rates to the price table. The live broken-candidate acceptance check from #2084 still requires a separate local comparison. -This workflow has no arbitrary commit input. Only the temporary `issue/2085` exception permits branch validation. +This workflow has no arbitrary commit input. It accepts manual runs on `main` only. Remaining #2085 work includes durable baseline storage, integrity checks, comparison, explicit promotion, and release documentation. Resolve the release order before connecting this workflow to publishing. diff --git a/scripts/agent-evals/coding-compare.ts b/scripts/agent-evals/coding-compare.ts index 40ee61c867c..8bf91fbed06 100644 --- a/scripts/agent-evals/coding-compare.ts +++ b/scripts/agent-evals/coding-compare.ts @@ -472,7 +472,9 @@ const OUTCOMES: Record = { // JSON writes NaN as null, and arithmetic reads null as zero. Only an absent // duration means "not measured". Complete cost accounting needs an estimate. -function assertReportMetrics(metrics: Record): void { +function assertReportMetrics( + metrics: Record, +): asserts metrics is Record & { outcome: { outcome: CodingRunOutcome; reason: string } } { const { durationMs, cost, outcome } = metrics if (durationMs !== undefined && !isAmount(durationMs)) throw new Error("side result run has invalid durationMs") const estimated = isObject(cost) ? cost["estimated"] : undefined @@ -533,7 +535,7 @@ export function validateSideResultFile( for (const run of runs) { if (typeof run !== "object" || run === null) throw new Error("side result run is not an object") const metrics = (run as Record)["metrics"] - if (typeof metrics !== "object" || metrics === null) throw new Error("side result run lacks metrics") + if (!isObject(metrics)) throw new Error("side result run lacks metrics") const key = JSON.stringify([run.fixtureName, run.repIndex]) if (!expected.delete(key)) throw new Error("side result has an unexpected or duplicate repetition key") if ( @@ -542,7 +544,11 @@ export function validateSideResultFile( ) { throw new Error("side result run and metrics keys differ") } - assertReportMetrics(metrics as Record) + assertReportMetrics(metrics) + // EvalComparisonInputs.OutcomesAgree: summary and comparison share this rule. + if (!isObject(run.outcome) || run.outcome["outcome"] !== metrics.outcome.outcome) { + throw new Error("side result run and metric outcomes differ") + } } if (expected.size) throw new Error("side result is missing expected repetitions") return parsed as SideResultFile diff --git a/scripts/agent-evals/coding-report.test.ts b/scripts/agent-evals/coding-report.test.ts index d267dad67ab..5687c4dfdcb 100644 --- a/scripts/agent-evals/coding-report.test.ts +++ b/scripts/agent-evals/coding-report.test.ts @@ -257,6 +257,7 @@ describe("side result validation", () => { Array.from({ length: 3 }, (_, repIndex) => ({ fixtureName: fixture.identity.name, repIndex, + outcome: { outcome: "correct", reason: "correct" }, metrics: metrics(fixture.identity.name, repIndex, "correct", 0.1), })), ), @@ -271,7 +272,12 @@ describe("side result validation", () => { }) it("accepts a well-formed run with object metrics and keeps it", () => { - const run = { fixtureName: "clamp-range", repIndex: 0, metrics: metrics("clamp-range", 0, "correct", 0.1) } + const run = { + fixtureName: "clamp-range", + repIndex: 0, + outcome: { outcome: "correct", reason: "correct" }, + metrics: metrics("clamp-range", 0, "correct", 0.1), + } const validated = validateSideResultFile(validatedFile("baseline", "a".repeat(40)), "baseline", "a".repeat(40)) assert.equal(validated.runs.length, CODING_FIXTURE_BUNDLES.length * 3) assert.deepEqual(validated.runs[0], run) @@ -694,6 +700,7 @@ it("checks bounded repetition sets and metrics key agreement", () => { Array.from({ length: repetitions }, (_, repIndex) => ({ fixtureName: fixture.identity.name, repIndex, + outcome: { outcome: "correct", reason: "correct" }, metrics: metrics(fixture.identity.name, repIndex, "correct", 0.1), })), ) @@ -874,3 +881,31 @@ it("retains complete run records in published JSON after source cleanup", async await fs.rm(root, { recursive: true, force: true }) } }) + +// EvalComparisonInputs.OutcomesAgree: each consumer accepts only matching outcomes. +for (const side of ["baseline", "candidate"] as const) { + it(`requires matching record and metric outcomes for ${side}`, () => { + const outcomes = ["correct", "incorrect", "timed-out", "grading-failure", "infrastructure-failure"] as const + for (const outcome of outcomes) { + const file = sideResult( + side, + "a".repeat(40), + CODING_FIXTURE_BUNDLES.map(({ fixture }) => metrics(fixture.identity.name, 0, outcome, 0.1)), + ) + assert.doesNotThrow(() => validateSideResultFile(file, side, "a".repeat(40), 1)) + for (const value of [ + undefined, + null, + "correct", + {}, + ...outcomes.filter((other) => other !== outcome).map((other) => ({ outcome: other, reason: other })), + ]) { + const changed = { + ...file, + runs: file.runs.map((run, index) => (index === 0 ? { ...run, outcome: value } : run)), + } + assert.throws(() => validateSideResultFile(changed, side, "a".repeat(40), 1), /outcomes differ/) + } + } + }) +} diff --git a/scripts/agent-evals/coding-side.mts b/scripts/agent-evals/coding-side.mts index e2cf9a4fe59..8ccf91563a1 100644 --- a/scripts/agent-evals/coding-side.mts +++ b/scripts/agent-evals/coding-side.mts @@ -272,11 +272,6 @@ await executeSideGeneration({ timeoutMs: INSTALL_TIMEOUT_MS, }, { label: "building the extension bundle", args: ["-w", "bundle"], timeoutMs: BUILD_TIMEOUT_MS }, - { - label: "building the webview", - args: ["--filter", "@roo-code/vscode-webview", "build"], - timeoutMs: BUILD_TIMEOUT_MS, - }, ]) { console.log(`coding-evals: ${step.label}`) await runBoundedPreparation( diff --git a/scripts/agent-evals/coding-side.test.ts b/scripts/agent-evals/coding-side.test.ts index 25a6ffe5242..8da9485052d 100644 --- a/scripts/agent-evals/coding-side.test.ts +++ b/scripts/agent-evals/coding-side.test.ts @@ -270,11 +270,6 @@ const writePnpmShim = async ( ` git rev-parse HEAD > ${log("pnpm-build-head.log")}`, " mkdir -p src/dist", build === "missing-extension" ? " :" : " printf 'benign extension entry\\n' > src/dist/extension.js", - " exit 0", - " ;;", - " --filter)", - ' test "$2" = @roo-code/vscode-webview && test "$3" = build || exit 1', - ` pwd > ${log("pnpm-webview-cwd.log")}`, " mkdir -p src/webview-ui/build/assets", build === "missing-webview" ? " :" : " printf 'webview script\\n' > src/webview-ui/build/assets/index.js", " printf 'webview styles\\n' > src/webview-ui/build/assets/index.css", @@ -336,12 +331,11 @@ const assertSingleWorktree = async (repo: string): Promise => { // the caller can prove its removal. const assertPreparationRanInFreshTree = async (dir: string, repo: string, commit: string): Promise => { const args = (await fs.readFile(path.join(dir, "pnpm-args.log"), "utf8")).trim().split("\n") - assert.deepEqual(args, ["install --frozen-lockfile", "-w bundle", "--filter @roo-code/vscode-webview build"]) + assert.deepEqual(args, ["install --frozen-lockfile", "-w bundle"]) const installCwd = (await fs.readFile(path.join(dir, "pnpm-install-cwd.log"), "utf8")).trim() const buildCwd = (await fs.readFile(path.join(dir, "pnpm-build-cwd.log"), "utf8")).trim() const buildHead = (await fs.readFile(path.join(dir, "pnpm-build-head.log"), "utf8")).trim() assert.equal(installCwd, buildCwd) - assert.equal((await fs.readFile(path.join(dir, "pnpm-webview-cwd.log"), "utf8")).trim(), buildCwd) assert.notEqual(installCwd, repo) assert.ok(path.basename(path.dirname(installCwd)).startsWith("coding-evals-side-")) assert.equal(buildHead, commit) diff --git a/scripts/agent-evals/coding-summary.mts b/scripts/agent-evals/coding-summary.mts index 4a886c172ed..af3543887f2 100644 --- a/scripts/agent-evals/coding-summary.mts +++ b/scripts/agent-evals/coding-summary.mts @@ -26,12 +26,7 @@ async function main(): Promise { // keys, and metric validation. This consumer also requires the current suite. const parsed: unknown = JSON.parse(await fs.readFile(path.join(out, "side-results.json"), "utf8")) const result = validateSideResultFile(parsed, "candidate", sha) - if ( - result.pins.suiteId !== CODING_SUITE_ID || - result.runs.some((run) => run.outcome?.outcome !== run.metrics.outcome.outcome) - ) { - throw new Error("Candidate suite or outcome records differ") - } + if (result.pins.suiteId !== CODING_SUITE_ID) throw new Error("Candidate suite differs") const names = [...new Set(result.runs.map((run) => run.fixtureName))].sort() const rows = names.map((name) => {