diff --git a/.github/workflows/agent-evals.yml b/.github/workflows/agent-evals.yml new file mode 100644 index 0000000000..8e5a6ce653 --- /dev/null +++ b/.github/workflows/agent-evals.yml @@ -0,0 +1,85 @@ +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: + +permissions: + contents: read + +concurrency: + group: agent-evals + cancel-in-progress: false + +jobs: + evaluate: + if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' + 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 --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: 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') }} + 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 a18ddd15e4..1a7eaf385e 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/EvalComparisonInputs.NoCheckKeys.cfg b/docs/architecture/tla/EvalComparisonInputs.NoCheckKeys.cfg index 067e843524..6064eea8fe 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 0000000000..223a30eed7 --- /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 b2da539f69..6d9e8399ae 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 d1327ce24e..1703561ad2 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 0c0d8fd0cb..5fd6f13d9e 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 985bbff1e8..3b2512179b 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 0000000000..03ead0824a --- /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 new file mode 100644 index 0000000000..e6d55162c3 --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.NoCheckOutputs.cfg @@ -0,0 +1,7 @@ +CONSTANT Outputs <- MCOutputs +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 new file mode 100644 index 0000000000..3e70334188 --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.cfg @@ -0,0 +1,7 @@ +CONSTANT Outputs <- MCOutputs +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 new file mode 100644 index 0000000000..479e0253cc --- /dev/null +++ b/docs/architecture/tla/EvalHostPreparation.tla @@ -0,0 +1,46 @@ +---- MODULE EvalHostPreparation ---- +\* Source: coding-side.mts preparation loop, Turbo bundle dependency, and verifyHostBuildOutputs. +\* Sink: the first createHostRuntime launch in the prepared worktree. +\* 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. +\* 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, ExtraWebviewBuild +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 +WebviewBuilds == IF ExtraWebviewBuild THEN 2 ELSE 1 +WebviewBuiltOnce == stage = "launched" => WebviewBuilds = 1 +==== diff --git a/docs/architecture/tla/EvalHostPreparationMC.tla b/docs/architecture/tla/EvalHostPreparationMC.tla new file mode 100644 index 0000000000..0a7b74502c --- /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/EvalScriptPath.NoDecode.cfg b/docs/architecture/tla/EvalScriptPath.NoDecode.cfg new file mode 100644 index 0000000000..68767a85b2 --- /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 0000000000..ceed2a09e9 --- /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 0000000000..1d14ca1ca6 --- /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 0000000000..4e0f4a3117 --- /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.NoApproval.cfg b/docs/architecture/tla/EvalWorkflow.NoApproval.cfg new file mode 100644 index 0000000000..8c4d3d8faa --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoApproval.cfg @@ -0,0 +1,10 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Disabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg b/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg new file mode 100644 index 0000000000..8f6128efb5 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoCandidate.cfg @@ -0,0 +1,10 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Disabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoHead.cfg b/docs/architecture/tla/EvalWorkflow.NoHead.cfg new file mode 100644 index 0000000000..cb366e6cb8 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoHead.cfg @@ -0,0 +1,10 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Disabled +CONSTANT CheckInfrastructure <- Enabled +SPECIFICATION Spec +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 0000000000..e4a4a8147a --- /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 new file mode 100644 index 0000000000..abbe0bcb96 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoReport.cfg @@ -0,0 +1,10 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Enabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Disabled +CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg b/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg new file mode 100644 index 0000000000..341156d1aa --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.NoTrigger.cfg @@ -0,0 +1,10 @@ +CONSTANT Inputs <- MCInputs +CONSTANT CheckTrigger <- Disabled +CONSTANT CheckApproval <- Enabled +CONSTANT CheckCandidate <- Enabled +CONSTANT CheckReport <- Enabled +CONSTANT CheckHead <- Enabled +CONSTANT CheckInfrastructure <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.cfg b/docs/architecture/tla/EvalWorkflow.cfg new file mode 100644 index 0000000000..31ba2bfb2c --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.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 <- Enabled +SPECIFICATION Spec +INVARIANTS SecretsAuthorized ExecutionTrusted SummaryBound WorkflowHealthy +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/EvalWorkflow.tla b/docs/architecture/tla/EvalWorkflow.tla new file mode 100644 index 0000000000..711f2dedd6 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflow.tla @@ -0,0 +1,83 @@ +---- MODULE EvalWorkflow ---- +\* 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. +\* 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" +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 "reported" ELSE "summaryRejected" + /\ UNCHANGED input + +\* 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", "reported", "accepted", "summaryRejected", "infrastructureFailed"} +ExecutionStarted == stage \in {"running", "result", "reported", "accepted", "summaryRejected", "infrastructureFailed"} +SecretsAuthorized == SecretsAvailable => (AllowedTrigger /\ input.approved) +ExecutionTrusted == ExecutionStarted => CandidateMatches +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 new file mode 100644 index 0000000000..bac61cba48 --- /dev/null +++ b/docs/architecture/tla/EvalWorkflowMC.tla @@ -0,0 +1,15 @@ +---- 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, + healthy : BOOLEAN, + payload : {"complete", "missing", "wrongCommit", "wrongSide", "wrongSuite", + "missingKeys", "duplicateKeys", "unknownOutcome", "invalidMetrics", "mismatchedOutcome"}] +==== diff --git a/scripts/agent-evals-workflow.test.mjs b/scripts/agent-evals-workflow.test.mjs new file mode 100644 index 0000000000..08af847345 --- /dev/null +++ b/scripts/agent-evals-workflow.test.mjs @@ -0,0 +1,289 @@ +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 { 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, 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: 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" + assert.equal(allowed, expected, `${event}: ${ref}`) + } + } + }) + + 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" }) + 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 --trust-file/) + 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') }}", + ) + }) + + 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) { + 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", + 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", 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 } + 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", () => { + 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", + "missing", + "wrong commit", + "missing repetition", + "duplicate repetition", + "unknown outcome", + "wrong side", + "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 }) => { + 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 === "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" + 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 = runSummary(dir, env) + 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(`reports complete results with ${outcome} outcomes and checks infrastructure health`, () => + scenario(({ dir, out, summary, result, env }) => { + for (const run of result.runs) setOutcome(run, outcome) + fs.writeFileSync(path.join(out, "side-results.json"), JSON.stringify(result)) + 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", + "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(" | ")} |`)) + })) + } + + 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/) + })) + } +}) + +// 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 3b6e499840..5538d071c9 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. | @@ -196,6 +198,64 @@ 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. + +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). + +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` 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. +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. +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. +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 EvalHostPreparation +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. diff --git a/scripts/agent-evals/coding-compare.ts b/scripts/agent-evals/coding-compare.ts index 40ee61c867..8bf91fbed0 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 d267dad67a..5687c4dfdc 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 35564ca6cf..8ccf91563a 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,32 @@ 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 }, + ]) { + 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 9b3a7cd38d..8da9485052 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,15 @@ 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", + " 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,7 +331,7 @@ 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"]) 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() @@ -331,6 +339,10 @@ const assertPreparationRanInFreshTree = async (dir: string, repo: string, commit 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 +351,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 +366,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 0000000000..af3543887f --- /dev/null +++ b/scripts/agent-evals/coding-summary.mts @@ -0,0 +1,88 @@ +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) throw new Error("Candidate suite differs") + + 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 0000000000..10d0f84cb7 --- /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 0000000000..f97cfe169c --- /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(", ")}`) +}