diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index b0bdcd439b0..677afff69b7 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -533,6 +533,23 @@ jobs: - name: Prepare E2E workspace uses: NVIDIA/NemoClaw/.github/actions/prepare-e2e@50281ee84c4a6fc759da95ea28fc0b7d9c378a28 + - name: Initialize runner comparison evidence + if: ${{ matrix.agent == 'hermes' || matrix.agent == 'deepagents' }} + continue-on-error: true + shell: bash + run: | + set -euo pipefail + mkdir -p "$E2E_ARTIFACT_DIR" + snapshots_file="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + summary_file="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + export E2E_RESOURCE_SNAPSHOTS_FILE="$snapshots_file" + export E2E_RESOURCE_SUMMARY_FILE="$summary_file" + npx tsx tools/e2e/runner-pressure.mts initialize-measurement + { + printf 'E2E_RESOURCE_SNAPSHOTS_FILE=%s\n' "$snapshots_file" + printf 'E2E_RESOURCE_SUMMARY_FILE=%s\n' "$summary_file" + } >> "$GITHUB_ENV" + - name: Install and verify cloudflared prerequisite # Update posture: maintainers review upstream cloudflared releases and # update the version and reviewed SHA256 together in both explicit MCP @@ -603,6 +620,16 @@ jobs: --silent=false --reporter=default --reporter=test/e2e/risk-signal-reporter.ts fi + - name: Summarize runner comparison evidence + if: ${{ always() && (matrix.agent == 'hermes' || matrix.agent == 'deepagents') }} + continue-on-error: true + shell: bash + run: | + set -euo pipefail + export E2E_RESOURCE_SNAPSHOTS_FILE="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + export E2E_RESOURCE_SUMMARY_FILE="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + npx tsx tools/e2e/runner-pressure.mts summarize-measurement + - id: mcp_artifact_secret_scan name: Scan MCP artifacts for fixture credentials if: always() @@ -2083,6 +2110,22 @@ jobs: - name: Prepare E2E workspace uses: NVIDIA/NemoClaw/.github/actions/prepare-e2e@50281ee84c4a6fc759da95ea28fc0b7d9c378a28 + - name: Initialize runner comparison evidence + continue-on-error: true + shell: bash + run: | + set -euo pipefail + mkdir -p "$E2E_ARTIFACT_DIR" + snapshots_file="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + summary_file="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + export E2E_RESOURCE_SNAPSHOTS_FILE="$snapshots_file" + export E2E_RESOURCE_SUMMARY_FILE="$summary_file" + npx tsx tools/e2e/runner-pressure.mts initialize-measurement + { + printf 'E2E_RESOURCE_SNAPSHOTS_FILE=%s\n' "$snapshots_file" + printf 'E2E_RESOURCE_SUMMARY_FILE=%s\n' "$summary_file" + } >> "$GITHUB_ENV" + - name: Install OpenShell # Direct Vitest execution uses bin/nemoclaw.js instead of install.sh, # so install OpenShell explicitly before onboard and SSH-agent probes. @@ -2116,6 +2159,16 @@ jobs: "$OPENSHELL_BIN" --version npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/common-egress-agent.test.ts + - name: Summarize runner comparison evidence + if: always() + continue-on-error: true + shell: bash + run: | + set -euo pipefail + export E2E_RESOURCE_SNAPSHOTS_FILE="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + export E2E_RESOURCE_SUMMARY_FILE="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + npx tsx tools/e2e/runner-pressure.mts summarize-measurement + - name: Upload common-egress agent artifacts if: always() uses: NVIDIA/NemoClaw/.github/actions/upload-e2e-artifacts@7768e15eb90d3ee2d33432f481dfe8747e4f6d57 @@ -2310,6 +2363,22 @@ jobs: - name: Prepare E2E workspace uses: NVIDIA/NemoClaw/.github/actions/prepare-e2e@50281ee84c4a6fc759da95ea28fc0b7d9c378a28 + - name: Initialize runner comparison evidence + continue-on-error: true + shell: bash + run: | + set -euo pipefail + mkdir -p "$E2E_ARTIFACT_DIR" + snapshots_file="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + summary_file="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + export E2E_RESOURCE_SNAPSHOTS_FILE="$snapshots_file" + export E2E_RESOURCE_SUMMARY_FILE="$summary_file" + npx tsx tools/e2e/runner-pressure.mts initialize-measurement + { + printf 'E2E_RESOURCE_SNAPSHOTS_FILE=%s\n' "$snapshots_file" + printf 'E2E_RESOURCE_SUMMARY_FILE=%s\n' "$summary_file" + } >> "$GITHUB_ENV" + - name: Install OpenShell CLI run: env -u DOCKER_CONFIG -u DOCKERHUB_USERNAME -u DOCKERHUB_TOKEN -u NVIDIA_API_KEY -u NVIDIA_INFERENCE_API_KEY -u GITHUB_TOKEN bash scripts/install-openshell.sh @@ -2344,6 +2413,16 @@ jobs: fi exit "$test_status" + - name: Summarize runner comparison evidence + if: always() + continue-on-error: true + shell: bash + run: | + set -euo pipefail + export E2E_RESOURCE_SNAPSHOTS_FILE="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + export E2E_RESOURCE_SUMMARY_FILE="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + npx tsx tools/e2e/runner-pressure.mts summarize-measurement + - name: Upload Hermes rebuild artifacts if: always() uses: NVIDIA/NemoClaw/.github/actions/upload-e2e-artifacts@7768e15eb90d3ee2d33432f481dfe8747e4f6d57 @@ -2386,6 +2465,22 @@ jobs: - name: Prepare E2E workspace uses: NVIDIA/NemoClaw/.github/actions/prepare-e2e@50281ee84c4a6fc759da95ea28fc0b7d9c378a28 + - name: Initialize runner comparison evidence + continue-on-error: true + shell: bash + run: | + set -euo pipefail + mkdir -p "$E2E_ARTIFACT_DIR" + snapshots_file="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + summary_file="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + export E2E_RESOURCE_SNAPSHOTS_FILE="$snapshots_file" + export E2E_RESOURCE_SUMMARY_FILE="$summary_file" + npx tsx tools/e2e/runner-pressure.mts initialize-measurement + { + printf 'E2E_RESOURCE_SNAPSHOTS_FILE=%s\n' "$snapshots_file" + printf 'E2E_RESOURCE_SUMMARY_FILE=%s\n' "$summary_file" + } >> "$GITHUB_ENV" + - name: Install OpenShell CLI run: env -u DOCKER_CONFIG -u DOCKERHUB_USERNAME -u DOCKERHUB_TOKEN -u NVIDIA_API_KEY -u NVIDIA_INFERENCE_API_KEY -u GITHUB_TOKEN bash scripts/install-openshell.sh @@ -2419,6 +2514,16 @@ jobs: fi exit "$test_status" + - name: Summarize runner comparison evidence + if: always() + continue-on-error: true + shell: bash + run: | + set -euo pipefail + export E2E_RESOURCE_SNAPSHOTS_FILE="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl" + export E2E_RESOURCE_SUMMARY_FILE="$E2E_ARTIFACT_DIR/runner-resource-summary.json" + npx tsx tools/e2e/runner-pressure.mts summarize-measurement + - name: Upload Hermes stale-base rebuild artifacts if: always() uses: NVIDIA/NemoClaw/.github/actions/upload-e2e-artifacts@7768e15eb90d3ee2d33432f481dfe8747e4f6d57 diff --git a/test/e2e/README.md b/test/e2e/README.md index a4df5cea099..5efeda876c0 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -76,12 +76,38 @@ variable, an organization owner must: `NVIDIA/NemoClaw` and workflow access to `NVIDIA/NemoClaw/.github/workflows/e2e.yaml@refs/heads/main`. 3. Record at least five standard-runner samples for each eligible lane, - including queue time, execution time, peak CPU, memory and disk use, - infrastructure failures, and estimated cost. + retaining each lane's `runner-resource-summary.json` artifact together with + its Actions queue time, full job duration, infrastructure result, and + estimated cost. 4. Copy the larger runner's workflow label into the repository variable, then repeat the same measurements for at least five representative executions per migrated lane. +Each eligible job has a best-effort initialization step for +`runner-resource-snapshots.jsonl` immediately after the shared workspace +preparation step. When initialization succeeds, the initial sample, automatic +live-test heartbeats and phase changes, and an `always()`-conditioned +best-effort final sample share that one private ledger. This keeps both +serialized Deep Agents Vitest invocations in one job-level measurement. A +best-effort finalizer writes `runner-resource-summary.json` before artifact +scanning and upload. The summary +contains the measured window, sample and valid CPU-interval counts, logical CPU +capacity, peak sampled host CPU percentage, the highest sampled cgroup +`memory.peak` counter (or a sampled `MemAvailable` fallback), memory capacity, +peak workspace growth, minimum free workspace bytes, and workspace capacity. +The cgroup peak can include activity before the ledger starts because the +kernel counter is cumulative for that cgroup. Resource fields are numeric; the +remaining strings are canonical timestamps and fixed lane or source labels. + +A comparison needs at least two snapshots to form a measured window, and CPU +requires adjacent samples at least one second apart. Treat these values as +sampled evidence rather than exact instantaneous peaks; the heartbeat interval +is one minute. Queue time, full job duration, and the infrastructure result +remain Actions metadata because they sit outside the measured job window; +estimate cost from those records and the configured runner rate. Compare at +least five standard and five larger-runner summaries per eligible lane, and +retain the matching Actions run links with the decision record. + Clearing `E2E_LARGER_RUNNER_LABEL` is the rollback. It sends the eligible lanes back to `ubuntu-latest` without changing selectors, test setup, or test semantics. Do not replace this experiment with a persistent self-hosted runner; diff --git a/test/e2e/fixtures/e2e-test.ts b/test/e2e/fixtures/e2e-test.ts index 03010033a84..7482c094b9d 100644 --- a/test/e2e/fixtures/e2e-test.ts +++ b/test/e2e/fixtures/e2e-test.ts @@ -1,10 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { createHash } from "node:crypto"; + import { test as base, expect } from "vitest"; import { appendResourcePhaseBaseline, + appendResourceSnapshot, collectResourceSnapshot, } from "../../../tools/e2e/runner-pressure.mts"; import { renderSnapshotLine } from "../../../tools/e2e/runner-pressure-core.mts"; @@ -56,7 +59,10 @@ function resourcePhaseLabel(targetId: string, phase: string): string { .toLowerCase() .replace(/[^a-z0-9]+/gu, "-") .replace(/^-|-$/gu, ""); - return `${targetId}.${suffix}`; + const label = `${targetId}.${suffix}`; + if (label.length <= 64) return label; + const digest = createHash("sha256").update(label).digest("hex").slice(0, 8); + return `${label.slice(0, 55)}-${digest}`; } export const test = base.extend({ @@ -79,6 +85,7 @@ export const test = base.extend({ async ({ artifacts, secrets, task }, use) => { const targetId = process.env.E2E_TARGET_ID; const baselinePath = process.env.E2E_RESOURCE_PHASE_BASELINES_FILE; + const snapshotsPath = process.env.E2E_RESOURCE_SNAPSHOTS_FILE; const progress = startTestProgress(task.name, "test body", { logLine: process.env.NEMOCLAW_RUN_LIVE_E2E === "1" @@ -86,12 +93,30 @@ export const test = base.extend({ : () => { // Keep fixture and support tests quiet; live runs need the heartbeat. }, - ...(targetId && baselinePath + ...(targetId && (baselinePath || snapshotsPath) ? { - sampleResourceEvidence: (phase: string) => - renderSnapshotLine(collectResourceSnapshot(resourcePhaseLabel(targetId, phase))), - recordResourceBaseline: (phase: string) => - appendResourcePhaseBaseline(baselinePath, resourcePhaseLabel(targetId, phase)), + sampleResourceEvidence: (phase: string) => { + const snapshot = collectResourceSnapshot(resourcePhaseLabel(targetId, phase), { + includeDiagnostics: Boolean(baselinePath), + }); + if (snapshotsPath) { + try { + appendResourceSnapshot(snapshotsPath, snapshot); + } catch { + // Comparison telemetry must not change the live test result. + } + } + return renderSnapshotLine(snapshot); + }, + ...(baselinePath + ? { + recordResourceBaseline: (phase: string) => + appendResourcePhaseBaseline( + baselinePath, + resourcePhaseLabel(targetId, phase), + ), + } + : {}), } : {}), }); diff --git a/test/e2e/support/e2e-progress-fixture.test.ts b/test/e2e/support/e2e-progress-fixture.test.ts index 9180abf56bd..948711c2f28 100644 --- a/test/e2e/support/e2e-progress-fixture.test.ts +++ b/test/e2e/support/e2e-progress-fixture.test.ts @@ -5,15 +5,26 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterAll, expect, vi } from "vitest"; - +import { afterAll, expect } from "vitest"; +import { parseSnapshotLine } from "../../../tools/e2e/runner-pressure-core.mts"; import { test } from "../fixtures/e2e-test.ts"; import type { ProgressSummary } from "../fixtures/progress.ts"; const artifactRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-progress-fixture-")); +const resourceSnapshots = path.join(artifactRoot, "runner-resource-snapshots.jsonl"); let progressArtifact = ""; -vi.stubEnv("E2E_ARTIFACT_DIR", artifactRoot); +const fixtureEnvironment = { + E2E_ARTIFACT_DIR: artifactRoot, + E2E_TARGET_ID: "fixture-progress-target", + NEMOCLAW_E2E_SHARD: "fixture-progress-shard", + E2E_RESOURCE_SNAPSHOTS_FILE: resourceSnapshots, +} as const; +const previousEnvironment = Object.fromEntries( + Object.keys(fixtureEnvironment).map((key) => [key, process.env[key]]), +) as Record; +Object.assign(process.env, fixtureEnvironment); +fs.writeFileSync(resourceSnapshots, "", { mode: 0o600 }); afterAll(() => { try { @@ -26,9 +37,29 @@ afterAll(() => { }); expect(summary.finishedAtMs).not.toBeNull(); expect(summary.durationMs).not.toBeNull(); - expect(summary.phases.at(-1)?.label).toBe("final fixture phase"); + expect(summary.phases.at(-1)?.label).toBe( + "phase 5 current base built by authoritative rebuild", + ); + const snapshots = fs + .readFileSync(resourceSnapshots, "utf8") + .trim() + .split("\n") + .map(parseSnapshotLine); + expect(snapshots).toHaveLength(4); + expect(snapshots.slice(0, 2).map((snapshot) => snapshot.phase)).toEqual([ + "fixture-progress-target.test-body", + "fixture-progress-target.test-body", + ]); + const longPhaseLabels = snapshots.slice(2).map((snapshot) => snapshot.phase); + expect(longPhaseLabels[0]).toHaveLength(64); + expect(longPhaseLabels[0]).toMatch(/^fixture-progress-target\.[a-z0-9-]+-[0-9a-f]{8}$/u); + expect(longPhaseLabels[1]).toBe(longPhaseLabels[0]); } finally { - vi.unstubAllEnvs(); + for (const [key, value] of Object.entries(previousEnvironment)) { + value === undefined + ? Reflect.deleteProperty(process.env, key) + : Reflect.set(process.env, key, value); + } fs.rmSync(artifactRoot, { force: true, recursive: true }); } }); @@ -38,7 +69,5 @@ test("automatic progress fixture writes completed target and shard evidence", as progress, }) => { progressArtifact = artifacts.pathFor("test-progress.json"); - vi.stubEnv("E2E_TARGET_ID", "fixture-progress-target"); - vi.stubEnv("NEMOCLAW_E2E_SHARD", "fixture-progress-shard"); - progress.phase("final fixture phase"); + progress.phase("phase 5 current base built by authoritative rebuild"); }); diff --git a/test/e2e/support/rebuild-hermes-progress.test.ts b/test/e2e/support/rebuild-hermes-progress.test.ts index 1c11b55db69..c6d7294fb5a 100644 --- a/test/e2e/support/rebuild-hermes-progress.test.ts +++ b/test/e2e/support/rebuild-hermes-progress.test.ts @@ -83,4 +83,18 @@ describe("Hermes rebuild live progress", () => { }).not.toThrow(); expect(state.clearCalls).toBe(1); }); + + it("keeps the live result independent from a failed measurement append", () => { + const { options, state } = progressHarness(); + options.sampleResourceEvidence = () => { + throw new Error("measurement ledger unavailable"); + }; + + expect(() => { + const progress = startTestProgress("rebuild-hermes", "phase 2 old base build", options); + state.timerCallback?.(); + progress.stop(); + }).not.toThrow(); + expect(state.clearCalls).toBe(1); + }); }); diff --git a/test/e2e/support/runner-pressure-workflow-boundary.test.ts b/test/e2e/support/runner-pressure-workflow-boundary.test.ts index 5f2aa7cab48..2d2014ac61c 100644 --- a/test/e2e/support/runner-pressure-workflow-boundary.test.ts +++ b/test/e2e/support/runner-pressure-workflow-boundary.test.ts @@ -6,11 +6,24 @@ import { describe, expect, it } from "vitest"; import { validateRunnerPressureWorkflow } from "../../../tools/e2e/runner-pressure-workflow-boundary.mts"; import { readWorkflow } from "../../helpers/e2e-workflow-contract"; -type WorkflowStep = Record & { if?: string; name?: string; run?: string }; +type WorkflowStep = Record & { + "continue-on-error"?: boolean; + if?: string; + name?: string; + run?: string; +}; type WorkflowJob = { steps: WorkflowStep[] }; type Workflow = { jobs: Record }; const JOBS = ["rebuild-hermes", "rebuild-hermes-stale-base"] as const; +const MEASUREMENT_JOBS = [ + "common-egress-agent", + "rebuild-hermes", + "rebuild-hermes-stale-base", + "mcp-bridge", +] as const; +const INITIALIZE_MEASUREMENT_STEP = "Initialize runner comparison evidence"; +const SUMMARIZE_MEASUREMENT_STEP = "Summarize runner comparison evidence"; function loadWorkflow(): Workflow { return readWorkflow() as Workflow; @@ -20,11 +33,35 @@ function runStep(workflow: Workflow, jobId: (typeof JOBS)[number]): WorkflowStep return workflow.jobs[jobId]!.steps.find((step) => step.name?.startsWith("Run Hermes"))!; } +function namedStep(workflow: Workflow, jobId: string, name: string): WorkflowStep { + return workflow.jobs[jobId]!.steps.find((step) => step.name === name)!; +} + describe("runner-pressure E2E workflow boundary (#7146)", () => { - it("accepts the canonical Hermes heartbeat and terminal-consumer wiring", () => { + it("accepts the canonical pressure classification and runner comparison wiring", () => { expect(validateRunnerPressureWorkflow(loadWorkflow())).toEqual([]); }); + it("limits job-level comparison evidence to the five larger-runner candidates", () => { + const workflow = loadWorkflow(); + for (const jobId of MEASUREMENT_JOBS) { + expect(namedStep(workflow, jobId, INITIALIZE_MEASUREMENT_STEP)).toBeDefined(); + expect(namedStep(workflow, jobId, SUMMARIZE_MEASUREMENT_STEP)).toBeDefined(); + } + expect(namedStep(workflow, "mcp-bridge", INITIALIZE_MEASUREMENT_STEP).if).toBe( + "${{ matrix.agent == 'hermes' || matrix.agent == 'deepagents' }}", + ); + expect(namedStep(workflow, "mcp-bridge", SUMMARIZE_MEASUREMENT_STEP).if).toBe( + "${{ always() && (matrix.agent == 'hermes' || matrix.agent == 'deepagents') }}", + ); + for (const [, job] of Object.entries(workflow.jobs).filter( + ([jobId]) => !(MEASUREMENT_JOBS as readonly string[]).includes(jobId), + )) { + expect(job.steps.some((step) => step.name === INITIALIZE_MEASUREMENT_STEP)).toBe(false); + expect(job.steps.some((step) => step.name === SUMMARIZE_MEASUREMENT_STEP)).toBe(false); + } + }); + it.each([ { label: "snapshot and phase baselines", @@ -96,4 +133,171 @@ describe("runner-pressure E2E workflow boundary (#7146)", () => { JOBS.map((jobId) => `${jobId} must upload runner-pressure evidence after every outcome`), ); }); + + it("rejects a missing initializer in every comparison job", () => { + const workflow = loadWorkflow(); + for (const jobId of MEASUREMENT_JOBS) { + workflow.jobs[jobId]!.steps = workflow.jobs[jobId]!.steps.filter( + (step) => step.name !== INITIALIZE_MEASUREMENT_STEP, + ); + } + + const errors = validateRunnerPressureWorkflow(workflow); + for (const jobId of MEASUREMENT_JOBS) { + expect(errors).toContain( + `${jobId} must initialize one runner comparison ledger after workspace preparation and before execution`, + ); + expect(errors).toContain( + `${jobId} must export the exact private runner comparison paths to later test processes`, + ); + } + }); + + it("rejects mutable or missing comparison artifact paths", () => { + const workflow = loadWorkflow(); + for (const jobId of MEASUREMENT_JOBS) { + const initialize = namedStep(workflow, jobId, INITIALIZE_MEASUREMENT_STEP); + initialize.run = initialize.run!.replaceAll( + "runner-resource-snapshots.jsonl", + "mutable-snapshots.jsonl", + ); + } + + const errors = validateRunnerPressureWorkflow(workflow); + for (const jobId of MEASUREMENT_JOBS) { + expect(errors).toContain( + `${jobId} must export the exact private runner comparison paths to later test processes`, + ); + } + }); + + it("rejects initialization after lane-specific setup has already started", () => { + const workflow = loadWorkflow(); + for (const jobId of MEASUREMENT_JOBS) { + const steps = workflow.jobs[jobId]!.steps; + const initializeIndex = steps.findIndex((step) => step.name === INITIALIZE_MEASUREMENT_STEP); + const [initialize] = steps.splice(initializeIndex, 1); + const runIndex = steps.findIndex((step) => step.name?.startsWith("Run ")); + steps.splice(runIndex, 0, initialize!); + } + + const errors = validateRunnerPressureWorkflow(workflow); + for (const jobId of MEASUREMENT_JOBS) { + expect(errors).toContain( + `${jobId} must initialize one runner comparison ledger after workspace preparation and before execution`, + ); + } + }); + + it("rejects summaries that run after artifact scanning or upload", () => { + const workflow = loadWorkflow(); + const publicationSteps = new Map([ + ["common-egress-agent", "Upload common-egress agent artifacts"], + ["rebuild-hermes", "Upload Hermes rebuild artifacts"], + ["rebuild-hermes-stale-base", "Upload Hermes stale-base rebuild artifacts"], + ["mcp-bridge", "Scan MCP artifacts for fixture credentials"], + ]); + for (const jobId of MEASUREMENT_JOBS) { + const steps = workflow.jobs[jobId]!.steps; + const summaryIndex = steps.findIndex((step) => step.name === SUMMARIZE_MEASUREMENT_STEP); + const [summary] = steps.splice(summaryIndex, 1); + const publicationIndex = steps.findIndex((step) => step.name === publicationSteps.get(jobId)); + steps.splice(publicationIndex + 1, 0, summary!); + } + + const errors = validateRunnerPressureWorkflow(workflow); + for (const jobId of MEASUREMENT_JOBS) { + expect(errors).toContain( + `${jobId} must append a final runner snapshot and summarize before artifact publication`, + ); + } + }); + + it("rejects comparison evidence that can replace live-test outcomes", () => { + const workflow = loadWorkflow(); + for (const jobId of MEASUREMENT_JOBS) { + const initialize = namedStep(workflow, jobId, INITIALIZE_MEASUREMENT_STEP); + const summary = namedStep(workflow, jobId, SUMMARIZE_MEASUREMENT_STEP); + initialize["continue-on-error"] = false; + summary.if = "success()"; + summary["continue-on-error"] = false; + } + + const errors = validateRunnerPressureWorkflow(workflow); + for (const jobId of MEASUREMENT_JOBS.filter((jobId) => jobId !== "mcp-bridge")) { + expect(errors).toContain( + `${jobId} runner comparison evidence must remain best-effort after every outcome`, + ); + } + expect(errors).toContain( + "mcp-bridge runner comparison evidence must be best-effort and limited to Hermes and Deep Agents shards", + ); + }); + + it("rejects comparison wiring in MCP OpenClaw, dev, or unrelated jobs", () => { + const workflow = loadWorkflow(); + namedStep(workflow, "mcp-bridge", INITIALIZE_MEASUREMENT_STEP).if = "always()"; + workflow.jobs["mcp-bridge-dev"]!.steps.push({ + name: INITIALIZE_MEASUREMENT_STEP, + run: "export E2E_RESOURCE_SNAPSHOTS_FILE=unexpected", + }); + workflow.jobs["shields-config"]!.steps.push({ + name: SUMMARIZE_MEASUREMENT_STEP, + run: "npx tsx tools/e2e/runner-pressure.mts summarize-measurement", + }); + + const errors = validateRunnerPressureWorkflow(workflow); + expect(errors).toContain( + "mcp-bridge runner comparison evidence must be best-effort and limited to Hermes and Deep Agents shards", + ); + expect(errors).toContain( + "runner comparison evidence must not be wired to out-of-scope job mcp-bridge-dev", + ); + expect(errors).toContain( + "runner comparison evidence must not be wired to out-of-scope job shields-config", + ); + }); + + it.each([ + { + label: "backgrounding the primary MCP test", + mutate: (script: string) => + script.replace( + "npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts", + "npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts &", + ), + }, + { + label: "backgrounding the primary MCP test without whitespace", + mutate: (script: string) => + script.replace( + "npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts", + "npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts&", + ), + }, + { + label: "parallelizing the Deep Agents follow-up", + mutate: (script: string) => script.replace("--no-file-parallelism", "--file-parallelism"), + }, + { + label: "running the follow-up before the primary test", + mutate: (script: string) => { + const main = + "npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts"; + const followUp = "test/e2e/live/openshell-credential-generation-window.test.ts"; + return script + .replace(main, "PRIMARY_TEST_PLACEHOLDER") + .replace(followUp, main) + .replace("PRIMARY_TEST_PLACEHOLDER", followUp); + }, + }, + ])("rejects $label because the shared ledger requires serialized appends", ({ mutate }) => { + const workflow = loadWorkflow(); + const run = namedStep(workflow, "mcp-bridge", "Run MCP OpenShell provider live test"); + run.run = mutate(run.run!); + + expect(validateRunnerPressureWorkflow(workflow)).toContain( + "mcp-bridge Deep Agents runner comparison tests must remain serialized in one job ledger", + ); + }); }); diff --git a/test/e2e/support/runner-pressure.test.ts b/test/e2e/support/runner-pressure.test.ts index cc5c5d0cca7..0b1bfd10bf9 100644 --- a/test/e2e/support/runner-pressure.test.ts +++ b/test/e2e/support/runner-pressure.test.ts @@ -30,12 +30,14 @@ import { parseCgroupMemoryEvents, parseCgroupScalar, parseClassificationLine, + parseCpuTimes, parseDockerSize, parseDockerStats, parseDockerSystemDf, parseLoadAverages, parseMeminfo, parsePressure, + parseSnapshotLine, parseTopProcesses, type ResourceSnapshot, renderBaselineLine, @@ -44,6 +46,7 @@ import { SNAPSHOT_LINE_MAX_LENGTH, SNAPSHOT_LINE_PREFIX, selectFailureBaseline, + summarizeResourceSnapshots, } from "../../../tools/e2e/runner-pressure-core.mts"; const HELPER = path.resolve( @@ -118,6 +121,7 @@ function baseSnapshot(): ResourceSnapshot { return { phase: "rebuild-hermes.image-build", at: "2026-07-18T00:00:00.000Z", + cpu: { logicalCpuCount: 4, idleTicks: 4_000, totalTicks: 10_000 }, meminfo: parseMeminfo(MEMINFO_FIXTURE), load: { load1: 3.5, load5: 2.1, load15: 1.0 }, cgroup: { @@ -151,6 +155,20 @@ function baseSnapshot(): ResourceSnapshot { } describe("host measurement parsers (#7146)", () => { + it("reads aggregate host CPU counters without double-counting guest time", () => { + expect( + parseCpuTimes( + [ + "cpu 100 20 30 400 50 10 20 5 80 10", + "cpu0 1 2 3 4 5 6 7 8 9 10", + "cpu1 1 2 3 4 5 6 7 8 9 10", + "intr 123", + ].join("\n"), + ), + ).toEqual({ logicalCpuCount: 2, idleTicks: 450, totalTicks: 635 }); + expect(parseCpuTimes("cpu malformed\ncpu0 1 2 3\n")).toBeNull(); + }); + it("reads MemAvailable, Cached, SReclaimable, and swap from /proc/meminfo", () => { const sample = parseMeminfo(MEMINFO_FIXTURE); expect(sample).toEqual({ @@ -261,6 +279,7 @@ describe("bounded secret-safe snapshot line (#7146)", () => { "at", "cgroup", "containers", + "cpu", "disk", "dockerDisk", "ioPressure", @@ -272,6 +291,7 @@ describe("bounded secret-safe snapshot line (#7146)", () => { "v", ]); expect(payload.meminfo.memAvailableKb).toBe(12288000); + expect(payload.cpu).toEqual({ logicalCpuCount: 4, idleTicks: 4000, totalTicks: 10000 }); expect(payload.cgroup.limitBytes).toBeNull(); expect(payload.topProcesses[0]).toEqual({ rank: 1, rssKb: 900000 }); expect(payload.containers[0]).toEqual({ @@ -296,6 +316,17 @@ describe("bounded secret-safe snapshot line (#7146)", () => { expect(line).not.toContain("ghp_container_secret"); }); + it("strictly round-trips the allowlisted snapshot and rejects extra fields", () => { + const line = renderSnapshotLine(baseSnapshot()); + expect(parseSnapshotLine(line)).toEqual(baseSnapshot()); + expect(() => parseSnapshotLine(line.replace('"v":1', '"v":1,"token":"ghp_secret"'))).toThrow( + /unsupported shape/, + ); + expect(() => parseSnapshotLine(line.replace('"idleTicks":4000', '"idleTicks":12000'))).toThrow( + /cannot exceed/, + ); + }); + it("stays within the line bound by limiting ranked lists before rendering", () => { const bloated = baseSnapshot(); bloated.topProcesses = Array.from({ length: 500 }, (_, i) => ({ @@ -336,6 +367,119 @@ describe("bounded secret-safe snapshot line (#7146)", () => { }); }); +describe("job-level runner resource summary (#7145)", () => { + function measuredSnapshot( + at: string, + cpu: ResourceSnapshot["cpu"], + peakBytes: number | null, + availableKb: number, + freeBytes: number, + ): ResourceSnapshot { + const snapshot = baseSnapshot(); + return { + ...snapshot, + at, + cpu, + meminfo: { ...snapshot.meminfo!, memAvailableKb: availableKb }, + cgroup: { ...snapshot.cgroup!, peakBytes }, + disk: { ...snapshot.disk!, freeBytes, totalBytes: 100 * 1024 ** 3 }, + }; + } + + it("reports sampled CPU, cgroup memory peak, and disk growth across one lane", () => { + const snapshots = [ + measuredSnapshot( + "2026-07-18T00:00:00.000Z", + { logicalCpuCount: 2, idleTicks: 400, totalTicks: 1_000 }, + 4 * 1024 ** 3, + 12_000_000, + 80 * 1024 ** 3, + ), + measuredSnapshot( + "2026-07-18T00:00:00.500Z", + { logicalCpuCount: 2, idleTicks: 450, totalTicks: 1_500 }, + 5 * 1024 ** 3, + 11_000_000, + 79 * 1024 ** 3, + ), + measuredSnapshot( + "2026-07-18T00:00:02.000Z", + { logicalCpuCount: 2, idleTicks: 800, totalTicks: 3_000 }, + 8 * 1024 ** 3, + 9_000_000, + 70 * 1024 ** 3, + ), + measuredSnapshot( + "2026-07-18T00:00:04.000Z", + { logicalCpuCount: 2, idleTicks: 20, totalTicks: 100 }, + 7 * 1024 ** 3, + 10_000_000, + 75 * 1024 ** 3, + ), + measuredSnapshot( + "2026-07-18T00:00:06.000Z", + { logicalCpuCount: 2, idleTicks: 220, totalTicks: 1_100 }, + 6 * 1024 ** 3, + 11_000_000, + 60 * 1024 ** 3, + ), + ]; + + expect( + summarizeResourceSnapshots(snapshots, { + targetId: "mcp-bridge", + shardId: "deepagents", + }), + ).toEqual({ + version: 1, + targetId: "mcp-bridge", + shardId: "deepagents", + startedAt: "2026-07-18T00:00:00.000Z", + finishedAt: "2026-07-18T00:00:06.000Z", + durationMs: 6_000, + sampleCount: 5, + cpu: { + logicalCpuCount: 2, + peakSampledPercent: 80, + intervalCount: 2, + }, + memory: { + peakBytes: 8 * 1024 ** 3, + capacityBytes: 16_384_000 * 1024, + source: "cgroup-peak", + }, + disk: { + peakDeltaBytes: 20 * 1024 ** 3, + minimumFreeBytes: 60 * 1024 ** 3, + capacityBytes: 100 * 1024 ** 3, + }, + }); + }); + + it("falls back to sampled MemAvailable and exposes an incomplete CPU interval", () => { + const snapshot = measuredSnapshot( + "2026-07-18T00:00:00.000Z", + null, + null, + 12_000_000, + 80 * 1024 ** 3, + ); + const summary = summarizeResourceSnapshots([snapshot], { targetId: "common-egress-agent" }); + expect(summary.durationMs).toBe(0); + expect(summary.sampleCount).toBe(1); + expect(summary.cpu).toEqual({ + logicalCpuCount: null, + peakSampledPercent: null, + intervalCount: 0, + }); + expect(summary.memory).toEqual({ + peakBytes: (16_384_000 - 12_000_000) * 1024, + capacityBytes: 16_384_000 * 1024, + source: "mem-available", + }); + }); +}); + describe("terminal failure classification (#7146)", () => { it("round-trips a strict numeric/boolean phase baseline", () => { const line = renderBaselineLine({ @@ -664,6 +808,64 @@ describe("runner-pressure CLI fail-closed entrypoint (#7146)", () => { } }, 90_000); + it("initializes and summarizes one private job-level measurement ledger", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-runner-measurement-")); + const snapshotsPath = path.join(directory, "runner-resource-snapshots.jsonl"); + const summaryPath = path.join(directory, "runner-resource-summary.json"); + const environment = { + E2E_TARGET_ID: "common-egress-agent", + E2E_RESOURCE_SNAPSHOTS_FILE: snapshotsPath, + E2E_RESOURCE_SUMMARY_FILE: summaryPath, + }; + try { + expect(runHelper(["initialize-measurement"], environment).status).toBe(0); + expect(fs.readFileSync(snapshotsPath, "utf8").trim().split("\n")).toHaveLength(1); + expect(fs.readFileSync(summaryPath, "utf8")).toBe(""); + + const result = runHelper(["summarize-measurement"], environment); + expect(result.status).toBe(0); + expect(fs.readFileSync(snapshotsPath, "utf8").trim().split("\n")).toHaveLength(2); + const summary = JSON.parse(fs.readFileSync(summaryPath, "utf8")); + expect(summary).toMatchObject({ + version: 1, + targetId: "common-egress-agent", + sampleCount: 2, + cpu: { intervalCount: expect.any(Number) }, + disk: { minimumFreeBytes: expect.any(Number) }, + }); + expect(Object.keys(summary.memory).sort()).toEqual(["capacityBytes", "peakBytes", "source"]); + for (const file of [snapshotsPath, summaryPath]) { + expect(fs.statSync(file).mode & 0o777).toBe(0o600); + } + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, 90_000); + + it.each([ + "symlink", + "hardlink", + ] as const)("rejects a %s-substituted measurement ledger", (linkKind) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-linked-measurement-")); + const snapshotsPath = path.join(directory, "runner-resource-snapshots.jsonl"); + const summaryPath = path.join(directory, "runner-resource-summary.json"); + const protectedPath = path.join(directory, "protected.jsonl"); + const protectedContents = "protected\n"; + const environment = { + E2E_TARGET_ID: "common-egress-agent", + E2E_RESOURCE_SNAPSHOTS_FILE: snapshotsPath, + E2E_RESOURCE_SUMMARY_FILE: summaryPath, + }; + try { + fs.writeFileSync(protectedPath, protectedContents, { mode: 0o600 }); + LINK_CREATORS[linkKind](protectedPath, snapshotsPath); + expect(runHelper(["initialize-measurement"], environment).status).not.toBe(0); + expect(fs.readFileSync(protectedPath, "utf8")).toBe(protectedContents); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, 90_000); + it.each([ "assertion", "timeout", diff --git a/tools/e2e/runner-pressure-core.mts b/tools/e2e/runner-pressure-core.mts index 11b9729a718..ec8f50550ab 100644 --- a/tools/e2e/runner-pressure-core.mts +++ b/tools/e2e/runner-pressure-core.mts @@ -82,6 +82,32 @@ export interface LoadSample { load15: number; } +export interface CpuTimesSample { + logicalCpuCount: number; + idleTicks: number; + totalTicks: number; +} + +/** + * Parse the aggregate CPU counters and logical processor rows from + * `/proc/stat`. Guest counters are excluded because Linux already includes + * them in user/nice and counting them again would inflate utilization. + */ +export function parseCpuTimes(text: string): CpuTimesSample | null { + const lines = text.split("\n"); + const aggregate = lines.find((line) => /^cpu\s+/u.test(line)); + const logicalCpuCount = lines.filter((line) => /^cpu\d+\s+/u.test(line)).length; + if (!aggregate || logicalCpuCount < 1) return null; + const values = aggregate.trim().split(/\s+/u).slice(1, 9); + if (values.length !== 8 || values.some((value) => !/^\d+$/u.test(value))) return null; + const counters = values.map(Number); + if (counters.some((value) => !Number.isSafeInteger(value) || value < 0)) return null; + const idleTicks = (counters[3] ?? 0) + (counters[4] ?? 0); + const totalTicks = counters.reduce((total, value) => total + value, 0); + if (!Number.isSafeInteger(idleTicks) || !Number.isSafeInteger(totalTicks)) return null; + return { logicalCpuCount, idleTicks, totalTicks }; +} + /** Parse `/proc/loadavg`; null when the shape is unrecognized. */ export function parseLoadAverages(text: string): LoadSample | null { const match = /^(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)\s/u.exec(text.trim()); @@ -271,6 +297,7 @@ export interface DiskSample { export interface ResourceSnapshot { phase: string; at: string; + cpu: CpuTimesSample | null; meminfo: MeminfoSample | null; load: LoadSample | null; cgroup: { @@ -330,6 +357,14 @@ export function renderSnapshotLine(snapshot: ResourceSnapshot): string { v: 1, phase: assertPhaseLabel(snapshot.phase), at: assertCanonicalTimestamp(snapshot.at), + cpu: + snapshot.cpu === null + ? null + : { + logicalCpuCount: number_(snapshot.cpu.logicalCpuCount), + idleTicks: number_(snapshot.cpu.idleTicks), + totalTicks: number_(snapshot.cpu.totalTicks), + }, meminfo: snapshot.meminfo === null ? null @@ -414,6 +449,386 @@ function renderPressure(sample: PressureSample | null): PressureSample | null { }; } +type UnknownRecord = Record; + +function record_(value: unknown, field: string): UnknownRecord { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + throw new Error(`${field} must be an object`); + } + return value as UnknownRecord; +} + +function exactKeys(record: UnknownRecord, keys: readonly string[], field: string): void { + if (Object.keys(record).sort().join(",") !== [...keys].sort().join(",")) { + throw new Error(`${field} has an unsupported shape`); + } +} + +function nullableNonNegativeNumber(value: unknown, field: string): number | null { + if (value === null) return null; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + throw new Error(`${field} must be null or a non-negative finite number`); + } + return value; +} + +function nullableNonNegativeInteger(value: unknown, field: string): number | null { + const parsed = nullableNonNegativeNumber(value, field); + if (parsed !== null && !Number.isSafeInteger(parsed)) { + throw new Error(`${field} must be null or a non-negative safe integer`); + } + return parsed; +} + +function parseNullableRecord( + value: unknown, + field: string, + parser: (record: UnknownRecord, field: string) => T, +): T | null { + return value === null ? null : parser(record_(value, field), field); +} + +function parseCpuRecord(record: UnknownRecord, field: string): CpuTimesSample { + exactKeys(record, ["logicalCpuCount", "idleTicks", "totalTicks"], field); + const logicalCpuCount = nullableNonNegativeInteger( + record.logicalCpuCount, + `${field}.logicalCpuCount`, + ); + const idleTicks = nullableNonNegativeInteger(record.idleTicks, `${field}.idleTicks`); + const totalTicks = nullableNonNegativeInteger(record.totalTicks, `${field}.totalTicks`); + if ( + logicalCpuCount === null || + logicalCpuCount < 1 || + idleTicks === null || + totalTicks === null + ) { + throw new Error(`${field} must contain complete CPU counters`); + } + if (idleTicks > totalTicks) throw new Error(`${field}.idleTicks cannot exceed totalTicks`); + return { logicalCpuCount, idleTicks, totalTicks }; +} + +function parseMeminfoRecord(record: UnknownRecord, field: string): MeminfoSample { + const keys = [ + "memTotalKb", + "memFreeKb", + "memAvailableKb", + "cachedKb", + "sReclaimableKb", + "swapTotalKb", + "swapFreeKb", + ] as const; + exactKeys(record, keys, field); + return { + memTotalKb: nullableNonNegativeNumber(record.memTotalKb, `${field}.memTotalKb`), + memFreeKb: nullableNonNegativeNumber(record.memFreeKb, `${field}.memFreeKb`), + memAvailableKb: nullableNonNegativeNumber(record.memAvailableKb, `${field}.memAvailableKb`), + cachedKb: nullableNonNegativeNumber(record.cachedKb, `${field}.cachedKb`), + sReclaimableKb: nullableNonNegativeNumber(record.sReclaimableKb, `${field}.sReclaimableKb`), + swapTotalKb: nullableNonNegativeNumber(record.swapTotalKb, `${field}.swapTotalKb`), + swapFreeKb: nullableNonNegativeNumber(record.swapFreeKb, `${field}.swapFreeKb`), + }; +} + +function parseLoadRecord(record: UnknownRecord, field: string): LoadSample { + exactKeys(record, ["load1", "load5", "load15"], field); + const load1 = nullableNonNegativeNumber(record.load1, `${field}.load1`); + const load5 = nullableNonNegativeNumber(record.load5, `${field}.load5`); + const load15 = nullableNonNegativeNumber(record.load15, `${field}.load15`); + if (load1 === null || load5 === null || load15 === null) { + throw new Error(`${field} must contain complete load averages`); + } + return { load1, load5, load15 }; +} + +function parseEventsRecord(record: UnknownRecord, field: string): CgroupMemoryEvents { + exactKeys(record, ["oom", "oomKill"], field); + const oom = nullableNonNegativeInteger(record.oom, `${field}.oom`); + const oomKill = nullableNonNegativeInteger(record.oomKill, `${field}.oomKill`); + if (oom === null || oomKill === null) throw new Error(`${field} must contain complete counters`); + return { oom, oomKill }; +} + +function parseCgroupRecord( + record: UnknownRecord, + field: string, +): NonNullable { + exactKeys(record, ["currentBytes", "peakBytes", "limitBytes", "events"], field); + return { + currentBytes: nullableNonNegativeNumber(record.currentBytes, `${field}.currentBytes`), + peakBytes: nullableNonNegativeNumber(record.peakBytes, `${field}.peakBytes`), + limitBytes: nullableNonNegativeNumber(record.limitBytes, `${field}.limitBytes`), + events: parseNullableRecord(record.events, `${field}.events`, parseEventsRecord), + }; +} + +function parsePressureRecord(record: UnknownRecord, field: string): PressureSample { + exactKeys(record, ["someAvg10", "someAvg60", "fullAvg10", "fullAvg60"], field); + return { + someAvg10: nullableNonNegativeNumber(record.someAvg10, `${field}.someAvg10`), + someAvg60: nullableNonNegativeNumber(record.someAvg60, `${field}.someAvg60`), + fullAvg10: nullableNonNegativeNumber(record.fullAvg10, `${field}.fullAvg10`), + fullAvg60: nullableNonNegativeNumber(record.fullAvg60, `${field}.fullAvg60`), + }; +} + +function parseTopProcessList(value: unknown): ProcessSample[] { + if (!Array.isArray(value) || value.length > TOP_PROCESS_LIMIT) { + throw new Error("snapshot.topProcesses must be a bounded array"); + } + return value.map((entry, index) => { + const record = record_(entry, `snapshot.topProcesses[${index}]`); + exactKeys(record, ["rank", "rssKb"], `snapshot.topProcesses[${index}]`); + if (record.rank !== index + 1) throw new Error("snapshot.topProcesses ranks must be ordered"); + const rssKb = nullableNonNegativeNumber(record.rssKb, `snapshot.topProcesses[${index}].rssKb`); + if (rssKb === null) throw new Error("snapshot.topProcesses.rssKb cannot be null"); + return { rssKb }; + }); +} + +function parseContainerList(value: unknown): ContainerStatSample[] { + if (!Array.isArray(value) || value.length > CONTAINER_STAT_LIMIT) { + throw new Error("snapshot.containers must be a bounded array"); + } + return value.map((entry, index) => { + const record = record_(entry, `snapshot.containers[${index}]`); + exactKeys( + record, + ["rank", "cpuPercent", "memBytes", "memLimitBytes"], + `snapshot.containers[${index}]`, + ); + if (record.rank !== index + 1) throw new Error("snapshot.containers ranks must be ordered"); + return { + cpuPercent: nullableNonNegativeNumber( + record.cpuPercent, + `snapshot.containers[${index}].cpuPercent`, + ), + memBytes: nullableNonNegativeNumber( + record.memBytes, + `snapshot.containers[${index}].memBytes`, + ), + memLimitBytes: nullableNonNegativeNumber( + record.memLimitBytes, + `snapshot.containers[${index}].memLimitBytes`, + ), + }; + }); +} + +function parseDockerDiskRecord(record: UnknownRecord, field: string): DockerDiskSample { + exactKeys(record, ["imagesBytes", "containersBytes", "buildCacheBytes"], field); + return { + imagesBytes: nullableNonNegativeNumber(record.imagesBytes, `${field}.imagesBytes`), + containersBytes: nullableNonNegativeNumber(record.containersBytes, `${field}.containersBytes`), + buildCacheBytes: nullableNonNegativeNumber(record.buildCacheBytes, `${field}.buildCacheBytes`), + }; +} + +function parseDiskRecord(record: UnknownRecord, field: string): DiskSample { + exactKeys(record, ["freeBytes", "totalBytes", "inodesFree", "inodesTotal"], field); + return { + freeBytes: nullableNonNegativeNumber(record.freeBytes, `${field}.freeBytes`), + totalBytes: nullableNonNegativeNumber(record.totalBytes, `${field}.totalBytes`), + inodesFree: nullableNonNegativeNumber(record.inodesFree, `${field}.inodesFree`), + inodesTotal: nullableNonNegativeNumber(record.inodesTotal, `${field}.inodesTotal`), + }; +} + +/** Strictly parse one allowlisted snapshot line; unknown fields are rejected. */ +export function parseSnapshotLine(line: string): ResourceSnapshot { + const trimmed = line.trim(); + if (!trimmed.startsWith(SNAPSHOT_LINE_PREFIX)) { + throw new Error(`resource snapshot must start with ${SNAPSHOT_LINE_PREFIX.trim()}`); + } + let parsed: unknown; + try { + parsed = JSON.parse(trimmed.slice(SNAPSHOT_LINE_PREFIX.length)); + } catch { + throw new Error("resource snapshot must contain valid JSON"); + } + const record = record_(parsed, "snapshot"); + exactKeys( + record, + [ + "v", + "phase", + "at", + "cpu", + "meminfo", + "load", + "cgroup", + "memoryPressure", + "ioPressure", + "topProcesses", + "containers", + "dockerDisk", + "disk", + ], + "snapshot", + ); + if (record.v !== 1) throw new Error("resource snapshot has an unsupported version"); + return { + phase: assertPhaseLabel(typeof record.phase === "string" ? record.phase : undefined), + at: assertCanonicalTimestamp(typeof record.at === "string" ? record.at : undefined), + cpu: parseNullableRecord(record.cpu, "snapshot.cpu", parseCpuRecord), + meminfo: parseNullableRecord(record.meminfo, "snapshot.meminfo", parseMeminfoRecord), + load: parseNullableRecord(record.load, "snapshot.load", parseLoadRecord), + cgroup: parseNullableRecord(record.cgroup, "snapshot.cgroup", parseCgroupRecord), + memoryPressure: parseNullableRecord( + record.memoryPressure, + "snapshot.memoryPressure", + parsePressureRecord, + ), + ioPressure: parseNullableRecord(record.ioPressure, "snapshot.ioPressure", parsePressureRecord), + topProcesses: parseTopProcessList(record.topProcesses), + containers: parseContainerList(record.containers), + dockerDisk: parseNullableRecord( + record.dockerDisk, + "snapshot.dockerDisk", + parseDockerDiskRecord, + ), + disk: parseNullableRecord(record.disk, "snapshot.disk", parseDiskRecord), + }; +} + +export interface RunnerResourceSummary { + version: 1; + targetId: string; + shardId?: string; + startedAt: string; + finishedAt: string; + durationMs: number; + sampleCount: number; + cpu: { + logicalCpuCount: number | null; + peakSampledPercent: number | null; + intervalCount: number; + }; + memory: { + peakBytes: number | null; + capacityBytes: number | null; + source: "cgroup-peak" | "mem-available" | null; + }; + disk: { + peakDeltaBytes: number | null; + minimumFreeBytes: number | null; + capacityBytes: number | null; + }; +} + +function consistentValue(values: readonly number[]): number | null { + const first = values[0]; + return first !== undefined && values.every((value) => value === first) ? first : null; +} + +function maximum(values: readonly number[]): number | null { + return values.length > 0 ? Math.max(...values) : null; +} + +/** Reduce one serialized job ledger into a numeric, runner-comparable summary. */ +export function summarizeResourceSnapshots( + snapshots: readonly ResourceSnapshot[], + identity: { targetId: string; shardId?: string }, +): RunnerResourceSummary { + const first = snapshots[0]; + const last = snapshots.at(-1); + if (!first || !last) throw new Error("resource measurement ledger must contain a snapshot"); + const startedAtMs = Date.parse(first.at); + const finishedAtMs = Date.parse(last.at); + if (finishedAtMs < startedAtMs) { + throw new Error("resource measurement ledger timestamps must be monotonic"); + } + for (let index = 1; index < snapshots.length; index += 1) { + if (Date.parse(snapshots[index]!.at) < Date.parse(snapshots[index - 1]!.at)) { + throw new Error("resource measurement ledger timestamps must be monotonic"); + } + } + + const cpuCounts = snapshots.flatMap((snapshot) => + snapshot.cpu === null ? [] : [snapshot.cpu.logicalCpuCount], + ); + let peakSampledPercent: number | null = null; + let intervalCount = 0; + for (let index = 1; index < snapshots.length; index += 1) { + const previous = snapshots[index - 1]!; + const current = snapshots[index]!; + if ( + previous.cpu === null || + current.cpu === null || + previous.cpu.logicalCpuCount !== current.cpu.logicalCpuCount || + Date.parse(current.at) - Date.parse(previous.at) < 1_000 + ) { + continue; + } + const totalDelta = current.cpu.totalTicks - previous.cpu.totalTicks; + const idleDelta = current.cpu.idleTicks - previous.cpu.idleTicks; + if (totalDelta <= 0 || idleDelta < 0 || idleDelta > totalDelta) continue; + const percent = Math.round(((totalDelta - idleDelta) / totalDelta) * 10_000) / 100; + peakSampledPercent = Math.max(peakSampledPercent ?? 0, percent); + intervalCount += 1; + } + + const hostCapacities = snapshots.flatMap((snapshot) => + snapshot.meminfo?.memTotalKb === null || snapshot.meminfo?.memTotalKb === undefined + ? [] + : [snapshot.meminfo.memTotalKb * 1024], + ); + const cgroupPeaks = snapshots.flatMap((snapshot) => + snapshot.cgroup?.peakBytes === null || snapshot.cgroup?.peakBytes === undefined + ? [] + : [snapshot.cgroup.peakBytes], + ); + const sampledMemoryUsed = snapshots.flatMap((snapshot) => { + const total = snapshot.meminfo?.memTotalKb; + const available = snapshot.meminfo?.memAvailableKb; + return total === null || total === undefined || available === null || available === undefined + ? [] + : [Math.max(0, total - available) * 1024]; + }); + const memorySource = + cgroupPeaks.length > 0 ? "cgroup-peak" : sampledMemoryUsed.length > 0 ? "mem-available" : null; + + const diskSamples = snapshots.flatMap((snapshot) => + snapshot.disk?.freeBytes === null || snapshot.disk?.freeBytes === undefined + ? [] + : [{ freeBytes: snapshot.disk.freeBytes, totalBytes: snapshot.disk.totalBytes }], + ); + const baselineFreeBytes = diskSamples[0]?.freeBytes; + const minimumFreeBytes = maximum(diskSamples.map((sample) => -sample.freeBytes)); + const normalizedMinimumFreeBytes = minimumFreeBytes === null ? null : -minimumFreeBytes; + const diskCapacities = diskSamples.flatMap((sample) => + sample.totalBytes === null ? [] : [sample.totalBytes], + ); + + return { + version: 1, + targetId: assertPhaseLabel(identity.targetId), + ...(identity.shardId ? { shardId: assertPhaseLabel(identity.shardId) } : {}), + startedAt: first.at, + finishedAt: last.at, + durationMs: finishedAtMs - startedAtMs, + sampleCount: snapshots.length, + cpu: { + logicalCpuCount: consistentValue(cpuCounts), + peakSampledPercent, + intervalCount, + }, + memory: { + peakBytes: maximum(cgroupPeaks.length > 0 ? cgroupPeaks : sampledMemoryUsed), + capacityBytes: consistentValue(hostCapacities), + source: memorySource, + }, + disk: { + peakDeltaBytes: + baselineFreeBytes === undefined || normalizedMinimumFreeBytes === null + ? null + : Math.max(0, baselineFreeBytes - normalizedMinimumFreeBytes), + minimumFreeBytes: normalizedMinimumFreeBytes, + capacityBytes: consistentValue(diskCapacities), + }, + }; +} + // ── Terminal classification ────────────────────────────────────────────────── export interface ResourceBaseline { diff --git a/tools/e2e/runner-pressure-workflow-boundary.mts b/tools/e2e/runner-pressure-workflow-boundary.mts index f1491883929..d1b09b8e734 100644 --- a/tools/e2e/runner-pressure-workflow-boundary.mts +++ b/tools/e2e/runner-pressure-workflow-boundary.mts @@ -2,13 +2,49 @@ // SPDX-License-Identifier: Apache-2.0 type WorkflowRecord = Record; -type WorkflowStep = WorkflowRecord & { if?: string; name?: string; run?: string }; +type WorkflowStep = WorkflowRecord & { + "continue-on-error"?: boolean; + if?: string; + name?: string; + run?: string; +}; const RUNNER_PRESSURE_JOBS = [ { id: "rebuild-hermes", runStep: "Run Hermes rebuild live test" }, { id: "rebuild-hermes-stale-base", runStep: "Run Hermes stale-base rebuild live test" }, ] as const; +const INITIALIZE_MEASUREMENT_STEP = "Initialize runner comparison evidence"; +const SUMMARIZE_MEASUREMENT_STEP = "Summarize runner comparison evidence"; +const MCP_MEASUREMENT_CONDITION = "${{ matrix.agent == 'hermes' || matrix.agent == 'deepagents' }}"; +const MCP_SUMMARY_CONDITION = + "${{ always() && (matrix.agent == 'hermes' || matrix.agent == 'deepagents') }}"; +const RUNNER_MEASUREMENT_JOBS = [ + { + id: "common-egress-agent", + publicationStep: "Upload common-egress agent artifacts", + runStep: "Run common-egress agent live test", + }, + { + id: "rebuild-hermes", + publicationStep: "Upload Hermes rebuild artifacts", + runStep: "Run Hermes rebuild live test", + }, + { + id: "rebuild-hermes-stale-base", + publicationStep: "Upload Hermes stale-base rebuild artifacts", + runStep: "Run Hermes stale-base rebuild live test", + }, + { + id: "mcp-bridge", + publicationStep: "Scan MCP artifacts for fixture credentials", + runStep: "Run MCP OpenShell provider live test", + }, +] as const; +const RUNNER_MEASUREMENT_JOB_IDS = new Set( + RUNNER_MEASUREMENT_JOBS.map((contract) => contract.id), +); + function asRecord(value: unknown): WorkflowRecord { return value && typeof value === "object" && !Array.isArray(value) ? (value as WorkflowRecord) @@ -21,6 +57,132 @@ function stepsFor(workflow: WorkflowRecord, jobId: string): WorkflowStep[] { return Array.isArray(job.steps) ? (job.steps as WorkflowStep[]) : []; } +function stepIndex(steps: readonly WorkflowStep[], name: string): number { + return steps.findIndex((step) => step.name === name); +} + +function containsEvery(script: string, fragments: readonly string[]): boolean { + return fragments.every((fragment) => script.includes(fragment)); +} + +function validateMeasurementWiring(workflow: WorkflowRecord, errors: string[]): void { + const jobs = asRecord(workflow.jobs); + for (const contract of RUNNER_MEASUREMENT_JOBS) { + const steps = stepsFor(workflow, contract.id); + const prepare = stepIndex(steps, "Prepare E2E workspace"); + const initialize = stepIndex(steps, INITIALIZE_MEASUREMENT_STEP); + const run = stepIndex(steps, contract.runStep); + const summarize = stepIndex(steps, SUMMARIZE_MEASUREMENT_STEP); + const publication = stepIndex(steps, contract.publicationStep); + const initializeSteps = steps.filter((step) => step.name === INITIALIZE_MEASUREMENT_STEP); + const summarySteps = steps.filter((step) => step.name === SUMMARIZE_MEASUREMENT_STEP); + const initializeStep = initializeSteps[0]; + const summaryStep = summarySteps[0]; + const initializeScript = typeof initializeStep?.run === "string" ? initializeStep.run : ""; + const summaryScript = typeof summaryStep?.run === "string" ? summaryStep.run : ""; + + if ( + initializeSteps.length !== 1 || + prepare < 0 || + initialize !== prepare + 1 || + run <= initialize + ) { + errors.push( + `${contract.id} must initialize one runner comparison ledger after workspace preparation and before execution`, + ); + } + if ( + !containsEvery(initializeScript, [ + 'snapshots_file="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl"', + 'summary_file="$E2E_ARTIFACT_DIR/runner-resource-summary.json"', + 'export E2E_RESOURCE_SNAPSHOTS_FILE="$snapshots_file"', + 'export E2E_RESOURCE_SUMMARY_FILE="$summary_file"', + "runner-pressure.mts initialize-measurement", + "E2E_RESOURCE_SNAPSHOTS_FILE=%s", + "E2E_RESOURCE_SUMMARY_FILE=%s", + '>> "$GITHUB_ENV"', + ]) + ) { + errors.push( + `${contract.id} must export the exact private runner comparison paths to later test processes`, + ); + } + if ( + summarySteps.length !== 1 || + summarize !== run + 1 || + publication <= summarize || + !containsEvery(summaryScript, [ + 'export E2E_RESOURCE_SNAPSHOTS_FILE="$E2E_ARTIFACT_DIR/runner-resource-snapshots.jsonl"', + 'export E2E_RESOURCE_SUMMARY_FILE="$E2E_ARTIFACT_DIR/runner-resource-summary.json"', + "runner-pressure.mts summarize-measurement", + ]) + ) { + errors.push( + `${contract.id} must append a final runner snapshot and summarize before artifact publication`, + ); + } + + const expectedInitializeCondition = + contract.id === "mcp-bridge" ? MCP_MEASUREMENT_CONDITION : undefined; + const expectedSummaryCondition = + contract.id === "mcp-bridge" ? MCP_SUMMARY_CONDITION : "always()"; + if ( + initializeStep?.if !== expectedInitializeCondition || + summaryStep?.if !== expectedSummaryCondition || + initializeStep?.["continue-on-error"] !== true || + summaryStep?.["continue-on-error"] !== true + ) { + errors.push( + contract.id === "mcp-bridge" + ? "mcp-bridge runner comparison evidence must be best-effort and limited to Hermes and Deep Agents shards" + : `${contract.id} runner comparison evidence must remain best-effort after every outcome`, + ); + } + } + + for (const [jobId, jobValue] of Object.entries(jobs)) { + if (RUNNER_MEASUREMENT_JOB_IDS.has(jobId)) continue; + const serialized = JSON.stringify(jobValue); + if ( + serialized.includes(INITIALIZE_MEASUREMENT_STEP) || + serialized.includes(SUMMARIZE_MEASUREMENT_STEP) || + serialized.includes("E2E_RESOURCE_SNAPSHOTS_FILE") || + serialized.includes("E2E_RESOURCE_SUMMARY_FILE") || + serialized.includes("initialize-measurement") || + serialized.includes("summarize-measurement") + ) { + errors.push(`runner comparison evidence must not be wired to out-of-scope job ${jobId}`); + } + } + + const mcpRunStep = stepsFor(workflow, "mcp-bridge").find( + (step) => step.name === "Run MCP OpenShell provider live test", + ); + const mcpScript = typeof mcpRunStep?.run === "string" ? mcpRunStep.run : ""; + const mainTest = mcpScript.indexOf( + "live-vitest-invocation.mts run --test-path test/e2e/live/mcp-bridge.test.ts", + ); + const deepAgentsGuard = mcpScript.indexOf( + 'if [[ "$NEMOCLAW_MCP_BRIDGE_AGENT" == "deepagents" ]]', + ); + const credentialWindow = mcpScript.indexOf( + "test/e2e/live/openshell-credential-generation-window.test.ts", + ); + const serializedRegion = + mainTest >= 0 && credentialWindow > mainTest ? mcpScript.slice(mainTest, credentialWindow) : ""; + if ( + mainTest < 0 || + deepAgentsGuard <= mainTest || + credentialWindow <= deepAgentsGuard || + !mcpScript.slice(credentialWindow).includes("--no-file-parallelism") || + /(?:^|[^&])&(?!&)/u.test(serializedRegion) + ) { + errors.push( + "mcp-bridge Deep Agents runner comparison tests must remain serialized in one job ledger", + ); + } +} + /** * Protect the canonical #7101 Hermes heartbeat integration from becoming an * emit-only diagnostic. Ordinary failures must produce, consume, and upload @@ -76,7 +238,8 @@ export function validateRunnerPressureWorkflow(workflowValue: unknown): string[] !script.includes( 'classification_file="$E2E_ARTIFACT_DIR/runner-pressure-classification.jsonl"', ) || - script.indexOf('export E2E_TERMINAL_CLASSIFICATION_FILE="$classification_file"') >= liveTest || + script.indexOf('export E2E_TERMINAL_CLASSIFICATION_FILE="$classification_file"') >= + liveTest || !script.includes('test_status="$?"') || !script.includes('exit "$test_status"') ) { @@ -90,5 +253,6 @@ export function validateRunnerPressureWorkflow(workflowValue: unknown): string[] errors.push(`${contract.id} must upload runner-pressure evidence after every outcome`); } } + validateMeasurementWiring(workflow, errors); return errors; } diff --git a/tools/e2e/runner-pressure.mts b/tools/e2e/runner-pressure.mts index 874965b8319..1ee21cecdbb 100644 --- a/tools/e2e/runner-pressure.mts +++ b/tools/e2e/runner-pressure.mts @@ -24,6 +24,10 @@ * descriptor when `E2E_TERMINAL_CLASSIFICATION_FILE` is * configured. Requires the baseline file named by * `E2E_RESOURCE_BASELINE_FILE`. + * - `initialize-measurement` — create one private job-level resource ledger + * and summary, then append the initial lightweight sample. + * - `summarize-measurement` — append the final lightweight sample and reduce + * the ledger into the numeric comparison artifact. * - `validate-classification` — fail closed unless the named classification * artifact contains exactly one canonical terminal line. * - `decide-retry` — print a JSON retry decision from `E2E_RUNNER_LOSS`, @@ -53,11 +57,13 @@ import { parseCgroupMemoryEvents, parseCgroupScalar, parseClassificationLine, + parseCpuTimes, parseDockerStats, parseDockerSystemDf, parseLoadAverages, parseMeminfo, parsePressure, + parseSnapshotLine, parseTopProcesses, type ResourceBaseline, type ResourceSnapshot, @@ -65,6 +71,7 @@ import { renderClassificationLine, renderSnapshotLine, selectFailureBaseline, + summarizeResourceSnapshots, TERMINAL_CLASSIFICATIONS, type TerminalClassification, } from "./runner-pressure-core.mts"; @@ -74,6 +81,8 @@ const CONTAINER_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u; const BASELINE_FILE_MAX_BYTES = 4096; const PHASE_BASELINES_FILE_MAX_BYTES = 128 * BASELINE_FILE_MAX_BYTES; const CLASSIFICATION_FILE_MAX_BYTES = 2048; +const RESOURCE_SNAPSHOTS_FILE_MAX_BYTES = 512 * 1024; +const RESOURCE_SNAPSHOT_MAX_LINES = 128; function readTextOrNull(path: string): string | null { try { @@ -106,21 +115,34 @@ function collectDisk(): ResourceSnapshot["disk"] { } } -export function collectResourceSnapshot(phase: string): ResourceSnapshot { +export function collectResourceSnapshot( + phase: string, + options: { includeDiagnostics?: boolean } = {}, +): ResourceSnapshot { + const includeDiagnostics = options.includeDiagnostics ?? true; + const at = new Date().toISOString(); + const cpuText = readTextOrNull("/proc/stat"); const meminfoText = readTextOrNull("/proc/meminfo"); - const loadText = readTextOrNull("/proc/loadavg"); + const loadText = includeDiagnostics ? readTextOrNull("/proc/loadavg") : null; const current = readTextOrNull(`${CGROUP_ROOT}/memory.current`); const peak = readTextOrNull(`${CGROUP_ROOT}/memory.peak`); const limit = readTextOrNull(`${CGROUP_ROOT}/memory.max`); const events = readTextOrNull(`${CGROUP_ROOT}/memory.events`); - const memoryPressure = readTextOrNull(`${CGROUP_ROOT}/memory.pressure`); - const ioPressure = readTextOrNull(`${CGROUP_ROOT}/io.pressure`); - const psText = runOrNull("ps", ["-eo", "rss="]); - const statsText = runOrNull("docker", ["stats", "--no-stream", "--format", "{{json .}}"]); - const dfText = runOrNull("docker", ["system", "df", "--format", "{{json .}}"]); + const memoryPressure = includeDiagnostics + ? readTextOrNull(`${CGROUP_ROOT}/memory.pressure`) + : null; + const ioPressure = includeDiagnostics ? readTextOrNull(`${CGROUP_ROOT}/io.pressure`) : null; + const psText = includeDiagnostics ? runOrNull("ps", ["-eo", "rss="]) : null; + const statsText = includeDiagnostics + ? runOrNull("docker", ["stats", "--no-stream", "--format", "{{json .}}"]) + : null; + const dfText = includeDiagnostics + ? runOrNull("docker", ["system", "df", "--format", "{{json .}}"]) + : null; return { phase, - at: new Date().toISOString(), + at, + cpu: cpuText === null ? null : parseCpuTimes(cpuText), meminfo: meminfoText === null ? null : parseMeminfo(meminfoText), load: loadText === null ? null : parseLoadAverages(loadText), cgroup: @@ -146,6 +168,70 @@ function runSnapshot(): void { console.log(renderSnapshotLine(collectResourceSnapshot(phase))); } +/** Append one already-collected snapshot without collecting diagnostics twice. */ +export function appendResourceSnapshot(path: string, snapshot: ResourceSnapshot): void { + appendPrivateRegularFile( + assertEvidencePath(path, "E2E_RESOURCE_SNAPSHOTS_FILE"), + `${renderSnapshotLine(snapshot)}\n`, + { maxBytes: RESOURCE_SNAPSHOTS_FILE_MAX_BYTES }, + ); +} + +function measurementPhase(suffix: "start" | "finish"): string { + const targetId = assertPhaseLabel(process.env.E2E_TARGET_ID); + return assertPhaseLabel(`${targetId}.measurement-${suffix}`); +} + +function runInitializeMeasurement(): void { + const snapshotsPath = assertEvidencePath( + process.env.E2E_RESOURCE_SNAPSHOTS_FILE, + "E2E_RESOURCE_SNAPSHOTS_FILE", + ); + const summaryPath = assertEvidencePath( + process.env.E2E_RESOURCE_SUMMARY_FILE, + "E2E_RESOURCE_SUMMARY_FILE", + ); + writePrivateRegularFile(snapshotsPath, ""); + writePrivateRegularFile(summaryPath, ""); + appendResourceSnapshot( + snapshotsPath, + collectResourceSnapshot(measurementPhase("start"), { includeDiagnostics: false }), + ); +} + +function runSummarizeMeasurement(): void { + const snapshotsPath = assertEvidencePath( + process.env.E2E_RESOURCE_SNAPSHOTS_FILE, + "E2E_RESOURCE_SNAPSHOTS_FILE", + ); + const summaryPath = assertEvidencePath( + process.env.E2E_RESOURCE_SUMMARY_FILE, + "E2E_RESOURCE_SUMMARY_FILE", + ); + appendResourceSnapshot( + snapshotsPath, + collectResourceSnapshot(measurementPhase("finish"), { includeDiagnostics: false }), + ); + const text = readPrivateRegularFile(snapshotsPath, { + maxBytes: RESOURCE_SNAPSHOTS_FILE_MAX_BYTES, + }); + if (text === null) throw new Error("E2E_RESOURCE_SNAPSHOTS_FILE could not be read"); + const lines = text.split(/\r?\n/u).filter((line) => line.length > 0); + if (lines.length < 2 || lines.length > RESOURCE_SNAPSHOT_MAX_LINES) { + throw new Error( + `resource measurement ledger must contain 2-${RESOURCE_SNAPSHOT_MAX_LINES} snapshots`, + ); + } + const targetId = assertPhaseLabel(process.env.E2E_TARGET_ID); + const shardId = process.env.NEMOCLAW_E2E_SHARD; + const summary = summarizeResourceSnapshots(lines.map(parseSnapshotLine), { + targetId, + ...(shardId ? { shardId: assertPhaseLabel(shardId) } : {}), + }); + writePrivateRegularFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`); + console.log(JSON.stringify(summary)); +} + function containerOomKilled(name: string | undefined): boolean { if (!name) return false; if (!CONTAINER_NAME_PATTERN.test(name)) { @@ -181,9 +267,13 @@ function assertEvidencePath(path: string | undefined, variableName: string): str /** Append one phase baseline without replacing the immutable workflow baseline. */ export function appendResourcePhaseBaseline(path: string, phase: string): void { const validatedPath = assertEvidencePath(path, "E2E_RESOURCE_PHASE_BASELINES_FILE"); - appendPrivateRegularFile(validatedPath, `${renderBaselineLine(collectResourceBaseline(phase))}\n`, { - maxBytes: PHASE_BASELINES_FILE_MAX_BYTES, - }); + appendPrivateRegularFile( + validatedPath, + `${renderBaselineLine(collectResourceBaseline(phase))}\n`, + { + maxBytes: PHASE_BASELINES_FILE_MAX_BYTES, + }, + ); } /** Create the trusted evidence files before PR-controlled live tests execute. */ @@ -201,10 +291,7 @@ function runInitializeEvidence(): void { process.env.E2E_TERMINAL_CLASSIFICATION_FILE, "E2E_TERMINAL_CLASSIFICATION_FILE", ); - writePrivateRegularFile( - baselinePath, - `${renderBaselineLine(collectResourceBaseline(phase))}\n`, - ); + writePrivateRegularFile(baselinePath, `${renderBaselineLine(collectResourceBaseline(phase))}\n`); writePrivateRegularFile(phaseBaselinesPath, ""); writePrivateRegularFile(classificationPath, ""); } @@ -318,6 +405,12 @@ function main(): number { case "initialize-evidence": runInitializeEvidence(); return 0; + case "initialize-measurement": + runInitializeMeasurement(); + return 0; + case "summarize-measurement": + runSummarizeMeasurement(); + return 0; case "classify": runClassify(); return 0; @@ -329,7 +422,7 @@ function main(): number { return 0; default: console.error( - "usage: runner-pressure.mts ", + "usage: runner-pressure.mts ", ); return 2; }