From b42ab51e6923363f5da22730c94d06c1d55e0be8 Mon Sep 17 00:00:00 2001 From: Julie Yaunches Date: Mon, 10 Aug 2026 22:23:15 -0400 Subject: [PATCH] chore: revert codebase growth guardrails Signed-off-by: Julie Yaunches --- .github/actions/ci-static-checks/action.yaml | 5 + .github/workflows/base-image.yaml | 3 - .../workflows/codebase-growth-guardrails.yaml | 109 ++++++- .github/workflows/managed-images.yaml | 277 ++++++++++-------- .pre-commit-config.yaml | 8 + AGENTS.md | 10 +- CONTRIBUTING.md | 30 +- .../openclaw-2026.6.10-dependency-review.md | 3 +- .../openshell-0.0.99-migration-review.md | 9 +- package.json | 4 +- scripts/check-test-file-size-budget.mts | 13 +- .../verify-openshell-e2e-qualification.mts | 38 +++ scripts/find-test-conditionals.mts | 124 ++++++++ test/codebase-growth-contract.test.ts | 31 -- .../managed-image-activation-e2e-helpers.ts | 2 +- .../live/managed-image-activation-e2e.test.ts | 6 +- test/growth-guardrails-entrypoints.test.ts | 82 ++---- ...rowth-guardrails-workflow-boundary.test.ts | 14 +- test/helpers/vitest-npm-script.ts | 4 +- ...managed-image-publication-workflow.test.ts | 68 ++--- test/openshell-e2e-qualification.test.ts | 11 +- test/vitest-developer-feedback.test.ts | 6 +- tools/growth-guardrails/check-pr.mts | 84 ------ tools/growth-guardrails/codebase-contract.mts | 108 ------- tools/growth-guardrails/test-conditionals.mts | 58 +++- tools/growth-guardrails/test-size-budget.mts | 46 ++- tools/growth-guardrails/workflow-boundary.mts | 23 +- 27 files changed, 656 insertions(+), 520 deletions(-) mode change 100644 => 100755 scripts/check-test-file-size-budget.mts mode change 100644 => 100755 scripts/find-test-conditionals.mts delete mode 100644 test/codebase-growth-contract.test.ts delete mode 100644 tools/growth-guardrails/check-pr.mts delete mode 100644 tools/growth-guardrails/codebase-contract.mts diff --git a/.github/actions/ci-static-checks/action.yaml b/.github/actions/ci-static-checks/action.yaml index 49c85beb5d9..0c13cecaa91 100644 --- a/.github/actions/ci-static-checks/action.yaml +++ b/.github/actions/ci-static-checks/action.yaml @@ -55,12 +55,17 @@ runs: run: | npx prek run --all-files --stage pre-commit \ --skip source-shape-test-budget \ + --skip test-file-size-budget \ --skip test-skills-yaml - name: Run source-shape budget shell: bash run: npm run source-shape:check + - name: Run test file size budget + shell: bash + run: npm run test-size:check + - name: Verify platform matrix is in sync shell: bash run: python3 scripts/generate-platform-docs.py --check diff --git a/.github/workflows/base-image.yaml b/.github/workflows/base-image.yaml index b9a3c759168..67932f1c7ba 100644 --- a/.github/workflows/base-image.yaml +++ b/.github/workflows/base-image.yaml @@ -22,9 +22,6 @@ on: # takes effect immediately after merge instead of waiting for another tag. - ".github/workflows/base-image.yaml" - ".github/workflows/managed-images.yaml" - - - "test/e2e/live/managed-image-activation-e2e.test.ts" - - "test/e2e/live/managed-image-activation-e2e-helpers.ts" - ".github/actions/ci-reviewed-npm-audit/**" - ".github/actions/build-base-image-platform/**" - ".github/actions/publish-base-image-manifest/**" diff --git a/.github/workflows/codebase-growth-guardrails.yaml b/.github/workflows/codebase-growth-guardrails.yaml index 9ae8d221fb5..761e749e39d 100644 --- a/.github/workflows/codebase-growth-guardrails.yaml +++ b/.github/workflows/codebase-growth-guardrails.yaml @@ -4,8 +4,9 @@ name: CI / Codebase Growth Guardrails # pull_request_target runs in the base repo context, so this policy cannot be -# bypassed by editing workflow files or tools in the PR. The trusted assertion -# reads PR metadata and blobs as data. It does not execute PR code. +# bypassed by editing workflow files or scripts in the PR. Keep this workflow +# data-only: do not check out or execute PR code. It only reads GitHub's +# file-level diff metadata. on: pull_request_target: types: [opened, reopened, synchronize, ready_for_review] @@ -20,6 +21,92 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: + - name: Block newly added JavaScript files + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + + rows="$(gh api --paginate "/repos/${REPO}/pulls/${PR_NUMBER}/files" \ + --jq '.[] | select((.filename | test("\\.(js|cjs|mjs)$")) and (.status == "added" or (.status == "renamed" and ((.previous_filename // "") | test("\\.(js|cjs|mjs)$") | not)))) | [.status, .filename, (.previous_filename // "")] | @tsv')" + + if [ -z "$rows" ]; then + echo "PASS: no newly added .js, .cjs, or .mjs files." + exit 0 + fi + + cat <<'EOF' + FAIL: this PR adds JavaScript source files. + + NemoClaw is standardizing on TypeScript for new Node.js code. Please + use .ts for new source, test, and script files instead of .js, .cjs, + or .mjs. Existing JavaScript files may still be modified or deleted. + + Blocked files: + EOF + while IFS=$'\t' read -r file_status file_path previous_path; do + if [ -n "$previous_path" ]; then + echo " - ${file_path} (${file_status} from ${previous_path})" + else + echo " - ${file_path} (${file_status})" + fi + done <<< "$rows" + exit 1 + + - name: Require src/lib/onboard.ts to be net-neutral or smaller + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPO: ${{ github.repository }} + TARGET_FILE: src/lib/onboard.ts + EXTRACTION_DIR: src/lib/onboard/ + run: | + set -euo pipefail + + # Intentionally hard-code TARGET_FILE in the jq expression. gh's jq + # filter does not accept shell variables directly, and missing + # previous_filename values must not match every file. + rows="$(gh api --paginate "/repos/${REPO}/pulls/${PR_NUMBER}/files" \ + --jq '.[] | select(.filename == "src/lib/onboard.ts" or .previous_filename == "src/lib/onboard.ts") | [.additions, .deletions, .filename] | @tsv')" + + if [ -z "$rows" ]; then + echo "${TARGET_FILE} was not changed. New modules under ${EXTRACTION_DIR} are allowed." + exit 0 + fi + + additions=0 + deletions=0 + while IFS=$'\t' read -r file_additions file_deletions _file_path; do + if [ -z "${file_additions:-}" ]; then + continue + fi + additions=$((additions + file_additions)) + deletions=$((deletions + file_deletions)) + done <<< "$rows" + + net=$((additions - deletions)) + echo "${TARGET_FILE}: +${additions}/-${deletions} (net ${net})" + echo "Growth under ${EXTRACTION_DIR} is allowed; this budget applies only to ${TARGET_FILE}." + + if [ "$additions" -le "$deletions" ]; then + echo "PASS: ${TARGET_FILE} is net-neutral or smaller." + exit 0 + fi + + cat <&2 + exit 1 + } + [[ "$DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]] || { + echo "ERROR: PR publication did not return an immutable digest" >&2 + exit 1 + } + reference="${IMAGE}@${DIGEST}" + raw="$RUNNER_TEMP/${AGENT}-published-manifest.raw" + docker buildx imagetools inspect "$reference" --raw > "$raw" + [[ "sha256:$(sha256sum "$raw" | awk '{print $1}')" == "$DIGEST" ]] || { + echo "ERROR: published PR manifest bytes do not match the build digest" >&2 + exit 1 + } + anonymous_config="$(mktemp -d "$RUNNER_TEMP/managed-pr-anonymous.XXXXXX")" + trap 'rm -rf -- "$anonymous_config"' EXIT + DOCKER_CONFIG="$anonymous_config" docker pull --platform linux/amd64 "$reference" + release="v$(node -p 'require("./package.json").version')" + contract_dir="$RUNNER_TEMP/managed-pr-contract" + mkdir -p "$contract_dir" + jq -n \ + --arg agent "$AGENT" \ + --arg cohort "$COHORT" \ + --arg digest "$DIGEST" \ + --arg image "$IMAGE" \ + --arg reference "$reference" \ + --arg release "$release" \ + --arg revision "$CANDIDATE_SHA" \ + '{ + contractVersion: 1, + agent: $agent, + platform: "linux/amd64", + image: $image, + digest: $digest, + reference: $reference, + source: { + repository: "NVIDIA/NemoClaw", + revision: $revision, + release: $release, + cohort: $cohort + }, + startupProfileContractVersion: 1, + capabilityContractVersion: 1 + }' > "$contract_dir/contract.json" + + - name: Upload exact published PR managed-image contract + if: github.event.pull_request.head.repo.full_name == github.repository + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: managed-pr-contract-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.agent }} + path: ${{ runner.temp }}/managed-pr-contract/contract.json + if-no-files-found: error + retention-days: 1 + + pr-managed-activation: + name: PR exact all-agent managed runtime activation + needs: pr-build-and-entrypoint + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 90 + permissions: + contents: read + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/managed-image-activation + E2E_JOB: "1" + E2E_TARGET_ID: managed-image-activation + NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js + NEMOCLAW_MANAGED_ACTIVATION_CATALOG: ${{ github.workspace }}/managed-pr-catalog.json + NEMOCLAW_NON_INTERACTIVE: "1" + NEMOCLAW_RUN_LIVE_E2E: "1" + OPENSHELL_GATEWAY: nemoclaw + steps: + - name: Checkout exact PR head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 22.19.0 + + - name: Download exact published all-agent contracts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: managed-pr-contract-${{ github.run_id }}-${{ github.run_attempt }}-* + path: ${{ runner.temp }}/managed-pr-contracts + merge-multiple: false + + - name: Assemble exact all-agent activation catalog + shell: bash + run: | + set -euo pipefail + mapfile -d '' contracts < <( + find "$RUNNER_TEMP/managed-pr-contracts" -type f -name contract.json -print0 + ) + [[ "${#contracts[@]}" -eq 3 ]] || { + echo "ERROR: exact all-agent activation requires three contracts" >&2 + exit 1 + } + jq -se \ + --arg revision "$CANDIDATE_SHA" ' + if ( + length == 3 and + ([.[].agent] | sort) == ["hermes", "langchain-deepagents-code", "openclaw"] and + ([.[].source.revision] | unique) == [$revision] and + ([.[].source.cohort] | unique | length) == 1 and + ([.[].platform] | unique) == ["linux/amd64"] + ) + then map({key: .agent, value: .}) | from_entries + else error("published PR contracts do not form one exact all-agent cohort") + end + ' "${contracts[@]}" > "$NEMOCLAW_MANAGED_ACTIVATION_CATALOG" + + - name: Build exact candidate CLI + run: | + npm ci --ignore-scripts + npm run build:cli + + - name: Install OpenShell CLI + shell: bash + run: env -u GITHUB_TOKEN bash scripts/install-openshell.sh + + - name: Run real all-agent managed runtime activation + shell: bash + run: | + set -euo pipefail + [[ "$(git rev-parse --verify HEAD)" == "$CANDIDATE_SHA" ]] || { + echo "ERROR: managed activation checkout does not match the exact PR head" >&2 + exit 1 + } + export PATH="$HOME/.local/bin:$HOME/.npm-global/bin:$PATH" + export OPENSHELL_BIN="$(command -v openshell)" + "$OPENSHELL_BIN" --version + npx tsx tools/e2e/live-vitest-invocation.mts run \ + --test-path test/e2e/live/managed-image-activation-e2e.test.ts + + - name: Upload managed runtime activation evidence + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: managed-image-activation-${{ github.run_id }}-${{ github.run_attempt }} + path: e2e-artifacts/live/managed-image-activation/ + if-no-files-found: error + retention-days: 1 + build-and-validate: name: Build and validate ${{ matrix.display_name }} managed image (${{ matrix.arch }}) if: github.event_name != 'pull_request' @@ -2131,119 +2292,3 @@ jobs: exit 1 fi done - - - main-managed-image-lifecycle: - name: Verify managed image lifecycle for all shipped agents - needs: promote - if: github.ref == 'refs/heads/main' - runs-on: ubuntu-24.04 - timeout-minutes: 90 - permissions: - contents: read - env: - MAIN_SHA: ${{ github.sha }} - E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/managed-image-activation - E2E_JOB: "1" - E2E_TARGET_ID: managed-image-activation - NEMOCLAW_CLI_BIN: ${{ github.workspace }}/bin/nemoclaw.js - NEMOCLAW_MANAGED_ACTIVATION_CATALOG: ${{ github.workspace }}/managed-main-catalog.json - NEMOCLAW_NON_INTERACTIVE: "1" - NEMOCLAW_RUN_LIVE_E2E: "1" - OPENSHELL_GATEWAY: nemoclaw - steps: - - name: Check out the workflow commit from main - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.sha }} - persist-credentials: false - - - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: 22.19.0 - - - name: Download published amd64 managed image contracts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: managed-image-${{ github.run_id }}-${{ github.run_attempt }}-*-linux-amd64 - path: ${{ runner.temp }}/managed-main-contracts - merge-multiple: false - - - name: Assemble managed image lifecycle catalog - shell: bash - run: | - set -euo pipefail - mapfile -d '' contracts < <( - find "$RUNNER_TEMP/managed-main-contracts" -type f -name contract.json -print0 - ) - [[ "${#contracts[@]}" -eq 3 ]] || { - echo "ERROR: managed image lifecycle verification requires three contracts" >&2 - exit 1 - } - release="v$(node -p 'require("./package.json").version')" - jq -se \ - --arg release "$release" \ - --arg revision "$MAIN_SHA" ' - if ( - length == 3 and - ([.[].contractVersion] | unique) == [2] and - ([.[].agent] | sort) == ["hermes", "langchain-deepagents-code", "openclaw"] and - ([.[].source.revision] | unique) == [$revision] and - ([.[].source.cohort] | unique | length) == 1 and - ([.[].platform] | unique) == ["linux/amd64"] - ) - then map({ - key: .agent, - value: { - contractVersion: 1, - agent, - platform, - image, - digest, - reference, - source: { - repository: .source.repository, - revision: .source.revision, - release: $release, - cohort: .source.cohort - }, - startupProfileContractVersion: 1, - capabilityContractVersion: 1 - } - }) | from_entries - else error("published main-branch contracts do not form one amd64 cohort for all shipped agents") - end - ' "${contracts[@]}" > "$NEMOCLAW_MANAGED_ACTIVATION_CATALOG" - - - name: Build the CLI from the workflow commit - run: | - npm ci --ignore-scripts - npm run build:cli - - - name: Install OpenShell CLI - shell: bash - run: env -u GITHUB_TOKEN bash scripts/install-openshell.sh - - - name: Verify managed image lifecycle for all shipped agents - shell: bash - run: | - set -euo pipefail - [[ "$(git rev-parse --verify HEAD)" == "$MAIN_SHA" ]] || { - echo "ERROR: managed image lifecycle checkout does not match the workflow commit" >&2 - exit 1 - } - export PATH="$HOME/.local/bin:$HOME/.npm-global/bin:$PATH" - export OPENSHELL_BIN="$(command -v openshell)" - "$OPENSHELL_BIN" --version - npx tsx tools/e2e/live-vitest-invocation.mts run \ - --test-path test/e2e/live/managed-image-activation-e2e.test.ts - - - name: Upload managed image lifecycle evidence - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: managed-image-lifecycle-${{ github.run_id }}-${{ github.run_attempt }} - path: e2e-artifacts/live/managed-image-activation/ - if-no-files-found: error - retention-days: 1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index dbb9fdb51fc..95c4f387a11 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -325,6 +325,14 @@ repos: files: ^(.+\.(test|spec)\.(js|ts|mjs|mts|cjs|cts)|scripts/find-source-shape-tests\.mts|ci/source-shape-test-budget\.json)$ priority: 20 + - id: test-file-size-budget + name: Test file size budget + entry: npm run test-size:check + language: system + pass_filenames: false + files: ^(test/|src/.*\.(test|spec)\.(ts|js|mts|mjs|cts|cjs)$|nemoclaw/src/.*\.(test|spec)\.(ts|js|mts|mjs|cts|cjs)$|scripts/check-test-file-size-budget\.mts$|ci/test-file-size-budget\.json$) + priority: 20 + - id: test-skills-yaml name: Test (skills YAML) entry: npx vitest run test/skills-frontmatter.test.ts diff --git a/AGENTS.md b/AGENTS.md index fca0e02686c..c4923a3e367 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,15 +109,7 @@ When writing tests: - Import CLI source from ordinary tests. Put genuine compiled-artifact assertions under `test/package-contract/`. - Keep project globs disjoint and exhaustive; `npm run test:projects:check` compares filesystem candidates with Vitest and rejects missing, overlapping, or unexpected membership. - Deterministic projects clear mock calls, restore `vi.spyOn`, and undo `vi.stubEnv` and `vi.stubGlobal` before each test. Create those spies and stubs in `beforeEach` or the test body unless a documented import-time stub must run before module evaluation. Restore direct environment or global mutations yourself, and reset mock implementations explicitly when needed. Live E2E and automatic `mockReset` are intentionally excluded. -- Run `npm run test:changed` from a checkout that has the `origin/main` Git ref. - After affected source tests pass, the command rejects: - - Newly added JavaScript files. - - Growth in `src/lib/onboard.ts`. - - Current test-file line-budget violations. - - An increased `if`-statement count in a changed test file. - The trusted PR check also rejects test-file budget limits that increase from the PR base commit. -- Use `npm run test:watch` for focused source-test feedback. -- Add only concrete opaque-input mappings to `test/helpers/vitest-watch-triggers.ts`. +- Use `npm run test:changed` or `npm run test:watch` for focused CLI, plugin, and E2E-support feedback. Add only concrete opaque-input mappings to `test/helpers/vitest-watch-triggers.ts` when the import graph cannot see a YAML, Python, shell, generated, or workflow dependency. - Use `npm run test:shuffle -- --sequence.seed=` to replay a printed test-order seed. Use `npm run test:diagnose:leaks` for async-resource or shutdown-hang diagnostics; both commands keep coverage disabled, and leak diagnostics can accompany exit code 0 when assertions pass. - Write behavior-oriented titles, put local issue references in a final `(#1234)` suffix, and use `npm run test:spec` for the hierarchical specification view. - Mock external dependencies; don't call real NVIDIA APIs in unit tests diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 83b8a94108c..95c97c4f760 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -212,7 +212,7 @@ These are the primary npm scripts for day-to-day development: | `npm test` | Build package artifacts and run every non-live Vitest project for broad changes | | `npm run test:spec` | Run every non-live test with hierarchical behavior-oriented output | | `npm run test:fast` | Clean `dist/` and run source CLI, plugin, and E2E-support tests | -| `npm run test:changed` | Run affected source tests, then check growth against `origin/main`; the PR check also compares test-file budget limits with the base commit | +| `npm run test:changed` | Run tests affected by staged, unstaged, or untracked changes in the CLI, plugin, and E2E-support projects | | `npm run test:watch` | Watch the CLI, plugin, and E2E-support projects and rerun affected tests | | `npm run test:shuffle` | Shuffle test order in the focused source projects without collecting coverage | | `npm run test:diagnose:leaks` | Report async-resource leaks and diagnose a Vitest process that hangs during shutdown | @@ -287,20 +287,12 @@ metrics list every accepted exception so these contracts remain visible during r ### Focused Vitest Feedback -Run `npm run test:changed` from a checkout that has the `origin/main` Git ref. -The command runs affected tests from the source-backed `cli`, `plugin`, and `e2e-support` projects. -After those tests pass, it checks the current checkout for: - -- Newly added JavaScript files. -- Growth in `src/lib/onboard.ts`. -- Test-file line-budget violations. -- An increased `if`-statement count in a changed test file. - -The pull request check compares `ci/test-file-size-budget.json` with the PR base commit. -The local check validates the current budget file but does not compare its limits with the PR base commit. -Keep `npm run test:watch` running for source-test feedback while editing. -Watch mode also maps the repository's current opaque YAML, Python, shell, generated, and workflow inputs to concrete contract tests outside Vitest's import graph. -Add a narrow mapping in `test/helpers/vitest-watch-triggers.ts` when a new opaque input needs the same treatment. +Use `npm run test:changed` for the staged, unstaged, and untracked changes in the current checkout, +or keep `npm run test:watch` running while editing. Both commands select only the source-backed +`cli`, `plugin`, and `e2e-support` projects. Watch mode also maps the repository's current opaque +YAML, Python, shell, generated, and workflow inputs to the concrete contract tests that read or +execute them outside Vitest's import graph. Add a narrow mapping in +`test/helpers/vitest-watch-triggers.ts` when a new opaque input needs the same treatment. Use `npm run test:shuffle` to expose order dependencies in those focused projects. The command shuffles tests within files and leaves coverage disabled. Vitest prints the chosen seed at the @@ -414,13 +406,9 @@ The repository is organized as follows. ## Language Policy -Use TypeScript instead of JavaScript for new source, test, and script files. -Do not add `.js`, `.cjs`, `.mjs`, or `.jsx` files. -Existing JavaScript files may be modified or deleted. +All new source files must be TypeScript. Do not add new `.js` files to the project. When modifying an existing JavaScript file, prefer migrating it to TypeScript in the same PR. -`bin/` retains a small CommonJS launcher and compatibility layer. -The main CLI implementation lives in `src/lib/` and compiles to `dist/`. -Existing ESM JavaScript tests under `test/` may remain, but new tests must use TypeScript. +Only a small CommonJS launcher/compatibility layer remains in `bin/`, while the main CLI implementation now lives in `src/lib/` and compiles to `dist/`. Tests in `test/` may remain ESM JavaScript for now but new test files should use TypeScript where practical. Shell scripts (`scripts/*.sh`) must pass ShellCheck and use `shfmt` formatting. diff --git a/docs/security/openclaw-2026.6.10-dependency-review.md b/docs/security/openclaw-2026.6.10-dependency-review.md index 8aecb8d6f61..b16931e09fc 100644 --- a/docs/security/openclaw-2026.6.10-dependency-review.md +++ b/docs/security/openclaw-2026.6.10-dependency-review.md @@ -394,8 +394,7 @@ No real Microsoft Teams tenant proof is included in this PR. The work remains tr The exact source shapes, replacement SRIs, tarball URLs, patched metadata, and provenance recipe fail closed on drift. The low `body-parser` and moderate Hono and `protobufjs` findings remain documented at the configured `high` threshold. Current NemoClaw closes the WeChat residual with `agents/openclaw/wechat-runtime/package-lock.json` and post-install graph verification. -- `src/lib/messaging/channels/manifests.test.ts` remains within the repository test-file line budget. - This OpenClaw dependency upgrade does not require a split to satisfy that budget. +- `src/lib/messaging/channels/manifests.test.ts` remains below the shared `test-size:check` threshold and does not need extraction in this dependency bump. - The npm audit result in this note remains a point-in-time snapshot. Default PR and main CI rematerialize the production-compatible graph from the reviewed local archives, audit it and the committed mcporter lock with `npm audit --omit=dev --json` through the reviewed evaluator, upload the raw reports and normalized policy results, and fail on unaccepted findings at the configured `high` threshold. The separate `wechat-runtime-audit` gate uses Node `22.19.0` and npm `10.9.4`, installs the committed WeChat production lock with scripts disabled, fails on any low-or-higher production advisory, verifies registry signatures, exercises the reviewed archive through a copied writable cache, and uploads its evidence. diff --git a/docs/security/openshell-0.0.99-migration-review.md b/docs/security/openshell-0.0.99-migration-review.md index 72a35e79703..c268beeccbb 100644 --- a/docs/security/openshell-0.0.99-migration-review.md +++ b/docs/security/openshell-0.0.99-migration-review.md @@ -212,12 +212,9 @@ projects. Reviewed condition-only jobs may be skipped when the empty-selector di select them, including Launchable, Jetson, DGX Spark, retired-selector compatibility, reporting, and scorecard jobs. -The managed image lifecycle job is not a required PR check and does not gate or roll back promotion. -When the base-image workflow publishes managed images from `main`, this job runs after `promote` moves the OpenClaw cohort pointer. -It exercises each published `linux/amd64` digest reference through onboarding, agent turns, gateway restart recovery, and destroy. -The references cover OpenClaw, Hermes, and LangChain Deep Agents Code. -If verification fails, the workflow does not roll back the promoted cohort pointer. -Changes that can affect rootless Podman still require the latest PR commit's rootless Podman CPU lifecycle check with Docker disabled. +Changes that can affect managed activation also require the current head's exact all-agent managed +runtime activation check. Changes that can affect rootless Podman also require the current head's +rootless Podman CPU lifecycle check with Docker disabled. The gate fails closed for missing, expired, duplicate, or malformed evidence. It also rejects a stale head or base, a workflow mismatch, nonempty selectors, an unreviewed skipped job, an diff --git a/package.json b/package.json index c1a69d549f5..17ec7557a8a 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,7 @@ "test": "npm run clean:cli && npm --prefix nemoclaw run clean && npm run build:cli && npm --prefix nemoclaw run build && vitest run --project cli --project integration --project installer-integration --project package-contract --project plugin --project e2e-support", "test:spec": "npm test -- --reporter=tree", "test:fast": "npm run clean:cli && npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support", - "test:changed": "npm run catalog:compile && vitest run --changed --project cli --project plugin --project e2e-support && vitest run --project integration test/codebase-growth-contract.test.ts", + "test:changed": "npm run catalog:compile && vitest run --changed --project cli --project plugin --project e2e-support", "test:watch": "npm run catalog:compile && vitest watch --project cli --project plugin --project e2e-support", "test:shuffle": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --sequence.shuffle.tests --coverage=false", "test:diagnose:leaks": "npm run catalog:compile && vitest run --project cli --project plugin --project e2e-support --detectAsyncLeaks --coverage=false --reporter=default --reporter=hanging-process", @@ -65,8 +65,8 @@ "type-safety:hotspots": "tsx scripts/type-safety-hotspots.mts", "source-shape:scan": "tsx scripts/find-source-shape-tests.mts --metrics", "source-shape:check": "tsx scripts/find-source-shape-tests.mts --check", - "test-size:check": "tsx scripts/check-test-file-size-budget.mts", + "test-conditionals:scan": "tsx scripts/find-test-conditionals.mts", "bump:version": "tsx scripts/bump-version.mts", "release:plan": "tsx scripts/release-plan.mts", "release:e2e-evidence": "node --experimental-strip-types --no-warnings .agents/skills/nemoclaw-maintainer-cut-release-tag/scripts/release-e2e-evidence.mts", diff --git a/scripts/check-test-file-size-budget.mts b/scripts/check-test-file-size-budget.mts old mode 100644 new mode 100755 index 1fe1a336054..1c135dbaae6 --- a/scripts/check-test-file-size-budget.mts +++ b/scripts/check-test-file-size-budget.mts @@ -1,3 +1,4 @@ +#!/usr/bin/env -S npx tsx // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 @@ -167,11 +168,6 @@ export function evaluateTestFileSizeBudget( return violations.sort((a, b) => a.file.localeCompare(b.file)); } -export function evaluateCurrentTestFileSizeBudget(): TestFileSizeViolation[] { - const budget = parseBudget(readFileSync(BUDGET_PATH, "utf-8"), BUDGET_PATH); - return evaluateTestFileSizeBudget(collectTestFileSizes(), budget); -} - export function formatViolations( violations: readonly TestFileSizeViolation[], budgetPath = "ci/test-file-size-budget.json", @@ -204,13 +200,16 @@ export function formatViolations( } function main(): void { - const violations = evaluateCurrentTestFileSizeBudget(); + const budget = parseBudget(readFileSync(BUDGET_PATH, "utf-8"), BUDGET_PATH); + const entries = collectTestFileSizes(); + const violations = evaluateTestFileSizeBudget(entries, budget); + if (violations.length > 0) { console.error(formatViolations(violations)); process.exitCode = 1; return; } - const entries = collectTestFileSizes(); + const maxEntry = entries.reduce( (max, entry) => (max === null || entry.lines > max.lines ? entry : max), null, diff --git a/scripts/checks/verify-openshell-e2e-qualification.mts b/scripts/checks/verify-openshell-e2e-qualification.mts index 374507865a7..dacf1bf4150 100644 --- a/scripts/checks/verify-openshell-e2e-qualification.mts +++ b/scripts/checks/verify-openshell-e2e-qualification.mts @@ -28,6 +28,7 @@ const DISPATCH_KIND = "nemoclaw-e2e-dispatch-v2"; const DISPATCH_FILE = "dispatch.json"; export const REQUIRED_PROOF_CHECKS = { + managed: "PR exact all-agent managed runtime activation", rootless: "Rootless Podman CPU lifecycle with Docker disabled", } as const; @@ -117,6 +118,31 @@ const SENSITIVE_PREFIXES = [ "test/e2e/support/podman-cpu-proof-workflow", ] as const; +const MANAGED_PROOF_EXACT_PATHS = new Set([ + ".dockerignore", + ".github/workflows/managed-images.yaml", + "Dockerfile", + "ci/npm-audit-exceptions.json", + "src/lib/core/json-types.ts", + "src/lib/core/ports.ts", + "src/lib/security/credential-hash.ts", + "src/lib/state/paths.ts", + "src/lib/state/state-root.ts", + "src/lib/tool-disclosure.ts", + "tsconfig.runtime-preloads.json", +]); + +const MANAGED_PROOF_PREFIXES = [ + "agents/", + "nemoclaw/", + "nemoclaw-blueprint/", + "scripts/", + "src/lib/messaging/", + "src/lib/onboard/", + "test/e2e/live/managed-image-activation-e2e", + "tools/mcp-tool-discovery-runtime/", +] as const; + const ROOTLESS_PROOF_EXACT_PATHS = new Set([ ".github/workflows/podman-cpu-proof.yaml", "scripts/install-openshell.sh", @@ -412,6 +438,18 @@ export function classifyQualification(files: readonly PullRequestFile[]): { ...new Set(allPaths.filter(isOpenShellQualificationSensitivePath)), ].sort(); const requiredProofChecks: string[] = []; + if ( + allPaths.some((candidatePath) => + matchesExactOrPrefix(candidatePath, MANAGED_PROOF_EXACT_PATHS, MANAGED_PROOF_PREFIXES), + ) || + allPaths.some((candidatePath) => + /^src\/lib\/actions\/sandbox\/openshell-child-visible-credentials\.v[^/]+\.json$/u.test( + candidatePath, + ), + ) + ) { + requiredProofChecks.push(REQUIRED_PROOF_CHECKS.managed); + } if ( allPaths.some((candidatePath) => matchesExactOrPrefix(candidatePath, ROOTLESS_PROOF_EXACT_PATHS, ROOTLESS_PROOF_PREFIXES), diff --git a/scripts/find-test-conditionals.mts b/scripts/find-test-conditionals.mts old mode 100644 new mode 100755 index 57fde873198..285756b9493 --- a/scripts/find-test-conditionals.mts +++ b/scripts/find-test-conditionals.mts @@ -1,3 +1,4 @@ +#!/usr/bin/env -S npx tsx // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 // @@ -58,6 +59,13 @@ type CallbackContext = { readonly name: string | null; }; +type CliOptions = { + readonly json: boolean; + readonly top: number; + readonly minScore: number; + readonly roots: readonly string[]; +}; + const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const DEFAULT_SCAN_ROOTS = Object.freeze(["test", "src", "nemoclaw/src"]); const TEST_FILE_PATTERN = /\.(?:test|spec)\.(?:[cm]?[jt]s)$/; @@ -481,3 +489,119 @@ export function collectTestConditionals(roots = DEFAULT_SCAN_ROOTS): TestConditi occurrences, }; } + +function formatContext(occurrence: TestConditionalOccurrence): string { + const name = occurrence.contextName === null ? "" : `: ${occurrence.contextName}`; + return `${occurrence.contextKind}${name}`; +} + +function formatOccurrence(occurrence: TestConditionalOccurrence): string { + const reasons = occurrence.reasons.length > 0 ? occurrence.reasons.join(", ") : "plain branch"; + return [ + `- ${occurrence.file}:${occurrence.line}:${occurrence.column}`, + `score=${occurrence.score}`, + `[${formatContext(occurrence)}]`, + `if (${occurrence.condition})`, + `— ${reasons}`, + ].join(" "); +} + +export function formatReport( + report: TestConditionalReport, + options: Pick, +): string { + const lines = [ + `Scanned ${report.summary.scannedFiles} test files; found ${report.summary.conditionalCount} if statement(s) in ${report.summary.filesWithConditionals} file(s).`, + `${report.summary.testBodyConditionalCount} are inside test bodies; ${report.summary.assertionBranchCount} branch assertions; ${report.summary.highScoreCount} score >= ${HIGH_SCORE_THRESHOLD}.`, + "", + "Top files by conditional score:", + ]; + + for (const file of report.files.slice(0, options.top)) { + lines.push( + `- ${file.file}: score=${file.score}, ifs=${file.count}, test-body=${file.testBodyCount}, assertion-branches=${file.assertionBranchCount}, max=${file.maxScore}`, + ); + } + + lines.push("", "Most egregious if statements:"); + for (const occurrence of report.occurrences.slice(0, options.top)) { + lines.push(formatOccurrence(occurrence)); + } + + return lines.join("\n"); +} + +function parsePositiveInt(value: string, flag: string): number { + const parsed = Number.parseInt(value, 10); + if (!Number.isInteger(parsed) || parsed <= 0) { + throw new Error(`${flag} must be a positive integer`); + } + return parsed; +} + +function parseArgs(argv: readonly string[]): CliOptions { + const roots: string[] = []; + let json = false; + let top = 20; + let minScore = 1; + + for (let index = 0; index < argv.length; index += 1) { + const arg = argv[index]; + if (arg === "--json") { + json = true; + } else if (arg === "--top") { + top = parsePositiveInt(argv[++index] ?? "", "--top"); + } else if (arg === "--min-score") { + minScore = parsePositiveInt(argv[++index] ?? "", "--min-score"); + } else if (arg === "--root") { + roots.push(argv[++index] ?? ""); + } else if (arg === "--help" || arg === "-h") { + console.log( + `Usage: tsx scripts/find-test-conditionals.mts [--top N] [--min-score N] [--root PATH] [--json]\n\nScans test/spec files under test, src, and nemoclaw/src by default.`, + ); + process.exit(0); + } else { + throw new Error(`Unknown argument: ${arg}`); + } + } + + if (roots.some((root) => root.trim() === "")) throw new Error("--root requires a path"); + return { json, top, minScore, roots: roots.length > 0 ? roots : DEFAULT_SCAN_ROOTS }; +} + +function filterReport(report: TestConditionalReport, minScore: number): TestConditionalReport { + if (minScore <= 1) return report; + const occurrences = report.occurrences.filter((entry) => entry.score >= minScore); + const files = summarizeFiles(occurrences); + return { + summary: { + ...report.summary, + filesWithConditionals: files.length, + conditionalCount: occurrences.length, + testBodyConditionalCount: occurrences.filter((entry) => entry.contextKind === "test").length, + assertionBranchCount: occurrences.filter((entry) => entry.containsAssertion).length, + highScoreCount: occurrences.filter((entry) => entry.score >= HIGH_SCORE_THRESHOLD).length, + }, + files, + occurrences, + }; +} + +function main(): void { + try { + const options = parseArgs(process.argv.slice(2)); + const report = filterReport(collectTestConditionals(options.roots), options.minScore); + if (options.json) { + console.log(JSON.stringify(report, null, 2)); + return; + } + console.log(formatReport(report, options)); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + } +} + +if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? "")) { + main(); +} diff --git a/test/codebase-growth-contract.test.ts b/test/codebase-growth-contract.test.ts deleted file mode 100644 index c42abe71d91..00000000000 --- a/test/codebase-growth-contract.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { expect, it } from "vitest"; - -import { evaluateCurrentTestFileSizeBudget } from "../scripts/check-test-file-size-budget.mts"; -import { - evaluateCurrentJavaScriptContract, - evaluateCurrentOnboardContract, - evaluateCurrentTestConditionalContract, -} from "../tools/growth-guardrails/codebase-contract.mts"; - -function expectNoViolations(violations: readonly unknown[]): void { - expect(violations, JSON.stringify(violations, null, 2)).toEqual([]); -} - -it("does not add JavaScript files", () => { - expectNoViolations(evaluateCurrentJavaScriptContract()); -}); - -it("does not increase the onboarding entry point line count", () => { - expectNoViolations(evaluateCurrentOnboardContract()); -}); - -it("keeps test files within their line budgets", () => { - expectNoViolations(evaluateCurrentTestFileSizeBudget()); -}); - -it("does not increase if-statement counts in changed test files", () => { - expectNoViolations(evaluateCurrentTestConditionalContract()); -}); diff --git a/test/e2e/live/managed-image-activation-e2e-helpers.ts b/test/e2e/live/managed-image-activation-e2e-helpers.ts index 45e9e450138..e2556d833cb 100644 --- a/test/e2e/live/managed-image-activation-e2e-helpers.ts +++ b/test/e2e/live/managed-image-activation-e2e-helpers.ts @@ -426,7 +426,7 @@ function expectNoDockerfileBuild(trace: string): void { export async function qualifyManagedImageActivation(fixtures: RuntimeFixtures): Promise { const { artifacts, cleanup, host, progress } = fixtures; - progress.phase("validate exact managed image catalog and host runtime"); + progress.phase("validate exact candidate catalog and host runtime"); const catalogPath = requiredCatalogPath(); const contracts = exactCatalog(catalogPath); const guard = createDockerBuildGuard(); diff --git a/test/e2e/live/managed-image-activation-e2e.test.ts b/test/e2e/live/managed-image-activation-e2e.test.ts index 98e6e67bb33..9ab39ee9df2 100644 --- a/test/e2e/live/managed-image-activation-e2e.test.ts +++ b/test/e2e/live/managed-image-activation-e2e.test.ts @@ -6,11 +6,11 @@ import { qualifyManagedImageActivation } from "./managed-image-activation-e2e-he const TIMEOUT_MS = 75 * 60_000; -test("CLI activates exact managed images for every shipped agent without a Dockerfile build (#7744)", { +test("candidate CLI activates exact managed images for every shipped agent without a Dockerfile build (#7744)", { timeout: TIMEOUT_MS, meta: { e2ePhases: [ - "validate exact managed image catalog and host runtime", + "validate exact candidate catalog and host runtime", "onboard and exercise OpenClaw", "restart and recover OpenClaw", "destroy and verify OpenClaw cleanup", @@ -27,7 +27,7 @@ test("CLI activates exact managed images for every shipped agent without a Docke await artifacts.target.declare({ id: "managed-image-activation", boundary: - "CLI and published managed-image digests for all shipped agents through real Docker, OpenShell, agent turns, restart recovery, and exact cleanup", + "exact candidate CLI and published all-agent managed-image digests through real Docker, OpenShell, agent turns, restart recovery, and exact cleanup", agents: ["openclaw", "hermes", "langchain-deepagents-code"], syntheticBoundary: "Only the OpenAI-compatible inference response is synthetic; runtime construction and agent execution are real.", diff --git a/test/growth-guardrails-entrypoints.test.ts b/test/growth-guardrails-entrypoints.test.ts index ce70c4d501d..9428d4e1790 100644 --- a/test/growth-guardrails-entrypoints.test.ts +++ b/test/growth-guardrails-entrypoints.test.ts @@ -18,7 +18,6 @@ const ENTRYPOINT_ENV = { PR_NUMBER: "1", REPO: "NVIDIA/NemoClaw", } as const; -const CLEAN_TEST_BUDGET = '{"defaultMaxLines":1500,"legacyMaxLines":{}}'; const FETCH_PRELOAD = ` const responses = JSON.parse(process.env.MOCK_RESPONSES ?? "[]"); @@ -39,7 +38,10 @@ function blobPayload(text: string | null): unknown { }; } -function runEntrypoint(responses: readonly unknown[]): ReturnType { +function runEntrypoint( + relativeToolPath: string, + responses: readonly unknown[], +): ReturnType { const directory = mkdtempSync(join(tmpdir(), "growth-guardrail-entrypoint-")); const preload = join(directory, "fetch-preload.mjs"); writeFileSync(preload, FETCH_PRELOAD); @@ -49,7 +51,7 @@ function runEntrypoint(responses: readonly unknown[]): ReturnType { - it("prints the consolidated PASS diagnostic", () => { - const result = runEntrypoint([[], blobPayload(CLEAN_TEST_BUDGET)]); +describe("growth-guardrails executable entrypoints (#6953)", () => { + it("prints the conditional guardrail PASS diagnostic", () => { + const result = runEntrypoint("tools/growth-guardrails/test-conditionals.mts", [[]]); expect(result.status).toBe(0); - expect(result.stdout).toContain("PASS: this PR preserves the codebase growth policies."); + expect(result.stdout).toContain( + "PASS: changed test files did not add if statements (0 at PR head vs 0 at base).", + ); }); - it("prints an increased test-file if-statement count in the consolidated failure", () => { - const baseSource = "it('a', () => { expect(1).toBe(1); });"; - const headSource = "it('a', () => { if (condition) expect(1).toBe(1); });"; - const result = runEntrypoint([ - [{ filename: "test/a.test.ts", status: "modified", additions: 1, deletions: 0 }], - blobPayload(CLEAN_TEST_BUDGET), - blobPayload(headSource), - blobPayload(baseSource), - blobPayload(headSource), + it("prints the conditional guardrail FAIL heading and file detail", () => { + const result = runEntrypoint("tools/growth-guardrails/test-conditionals.mts", [ + [{ filename: "test/a.test.ts", status: "modified" }], + blobPayload("it('a', () => { expect(1).toBe(1); });"), + blobPayload("it('a', () => { if (condition) expect(1).toBe(1); });"), ]); expect(result.status).toBe(1); - expect(result.stderr).toContain("FAIL: codebase growth policies rejected this PR."); + expect(result.stderr).toContain("FAIL: changed test files add if statements."); expect(result.stderr).toContain("test/a.test.ts: 1 if statement(s), up from 0"); }); - it("reports an increased default test-file line budget in the consolidated failure", () => { - const result = runEntrypoint([ - [{ filename: "ci/test-file-size-budget.json", status: "added", additions: 1, deletions: 0 }], + it("prints the size-budget guardrail PASS diagnostic", () => { + const result = runEntrypoint("tools/growth-guardrails/test-size-budget.mts", [ + [], blobPayload(null), - blobPayload('{"defaultMaxLines":2000,"legacyMaxLines":{}}'), - ]); - - expect(result.status).toBe(1); - expect(result.stderr).toContain("defaultMaxLines increased from 1500 to 2000"); - }); - - it.each([ - "js", - "cjs", - "mjs", - "jsx", - ])("reports a newly added .%s JavaScript path in the consolidated failure", (extension) => { - const filename = `scripts/new.${extension}`; - const result = runEntrypoint([ - [{ filename, status: "added", additions: 1, deletions: 0 }], - blobPayload(CLEAN_TEST_BUDGET), ]); - expect(result.status).toBe(1); - expect(result.stderr).toContain(`${filename}: new JavaScript files must use TypeScript`); + expect(result.status).toBe(0); + expect(result.stdout).toContain( + "PASS: test size budget policy is monotonic and 0 changed test file(s) are within budget.", + ); }); - it("prints net growth in the onboarding entry point in the consolidated failure", () => { - const result = runEntrypoint([ - [ - { - filename: "src/lib/onboard.ts", - status: "modified", - additions: 3, - deletions: 1, - }, - ], - blobPayload(CLEAN_TEST_BUDGET), + it("prints the size-budget guardrail FAIL heading and budget detail", () => { + const result = runEntrypoint("tools/growth-guardrails/test-size-budget.mts", [ + [{ filename: "ci/test-file-size-budget.json", status: "added" }], + blobPayload(null), + blobPayload('{"defaultMaxLines":2000,"legacyMaxLines":{}}'), ]); expect(result.status).toBe(1); - expect(result.stderr).toContain("src/lib/onboard.ts: grew by 2 line(s) (+3/-1)"); + expect(result.stderr).toContain("FAIL: test size budget policy would be weakened or exceeded."); + expect(result.stderr).toContain("defaultMaxLines increased from 1500 to 2000"); }); }); diff --git a/test/growth-guardrails-workflow-boundary.test.ts b/test/growth-guardrails-workflow-boundary.test.ts index c3789452bed..72c9c6cf510 100644 --- a/test/growth-guardrails-workflow-boundary.test.ts +++ b/test/growth-guardrails-workflow-boundary.test.ts @@ -63,17 +63,17 @@ describe("growth-guardrails workflow trust boundary", () => { "a dropped trusted tool invocation", (s: string) => s.replace( - "node --experimental-strip-types tools/growth-guardrails/check-pr.mts", + "node --experimental-strip-types tools/growth-guardrails/test-conditionals.mts", "echo skip", ), - /must invoke the trusted tool: .*check-pr\.mts/, + /must invoke the trusted tool: .*test-conditionals\.mts/, ], [ "a resurrected inline node heredoc", (s: string) => s.replace( - "node --experimental-strip-types tools/growth-guardrails/check-pr.mts", - "node <<'NODE\n console.log(1)\n NODE", + "node --experimental-strip-types tools/growth-guardrails/test-size-budget.mts", + "node <<'NODE'\n console.log(1)\n NODE", ), /must match the approved shape/, ], @@ -90,8 +90,8 @@ describe("growth-guardrails workflow trust boundary", () => { "an appended PR-head payload execution in a trusted step", (s: string) => s.replace( - "node --experimental-strip-types tools/growth-guardrails/check-pr.mts", - 'node --experimental-strip-types tools/growth-guardrails/check-pr.mts\n gh api "/repos/${HEAD_REPO}/contents/payload.sh?ref=${HEAD_SHA}" --jq .content | base64 -d > "$RUNNER_TEMP/payload.sh"\n bash "$RUNNER_TEMP/payload.sh"', + "node --experimental-strip-types tools/growth-guardrails/test-size-budget.mts", + 'node --experimental-strip-types tools/growth-guardrails/test-size-budget.mts\n gh api "/repos/${HEAD_REPO}/contents/payload.sh?ref=${HEAD_SHA}" --jq .content | base64 -d > "$RUNNER_TEMP/payload.sh"\n bash "$RUNNER_TEMP/payload.sh"', ), /must match the approved shape/, ], @@ -102,7 +102,7 @@ describe("growth-guardrails workflow trust boundary", () => { " - name: Check out the trusted base revision", " - name: Execute an untrusted action\n uses: attacker/payload@main\n\n - name: Check out the trusted base revision", ), - /must contain exactly 3 approved steps, not 4/, + /must contain exactly 6 approved steps, not 7/, ], [ "a non-approved shell field", diff --git a/test/helpers/vitest-npm-script.ts b/test/helpers/vitest-npm-script.ts index 67cb4b09ce7..0b984df17ff 100644 --- a/test/helpers/vitest-npm-script.ts +++ b/test/helpers/vitest-npm-script.ts @@ -21,9 +21,7 @@ export function runVitestNpmScript( fs.mkdirSync(fakeBin); fs.writeFileSync( path.join(fakeBin, "vitest"), - `#!/bin/sh -printf 'vitest %s\\n' "$*" >> "$COMMAND_LOG" -`, + '#!/bin/sh\nprintf \'vitest %s\\n\' "$*" > "$COMMAND_LOG"\n', { mode: 0o755 }, ); fs.writeFileSync(path.join(fakeBin, "tsx"), "#!/bin/sh\nexit 0\n", { mode: 0o755 }); diff --git a/test/managed-image-publication-workflow.test.ts b/test/managed-image-publication-workflow.test.ts index 0a1388cce91..b751c325c53 100644 --- a/test/managed-image-publication-workflow.test.ts +++ b/test/managed-image-publication-workflow.test.ts @@ -168,10 +168,10 @@ function stagingQaDeepCodeBuilder(workflow: Workflow): Job { ); } -function managedMainLifecycle(workflow: Workflow): Job { +function managedPrActivation(workflow: Workflow): Job { return required( - workflow.jobs?.["main-managed-image-lifecycle"], - "managed-image workflow is missing lifecycle verification for all shipped agents on the main branch", + workflow.jobs?.["pr-managed-activation"], + "managed-image workflow is missing its exact all-agent PR activation gate", ); } @@ -613,6 +613,8 @@ describe("complete managed-image publication workflow", () => { const login = step(prBuilder, "Log in to GHCR for exact same-repository PR digest"); const publish = step(prBuilder, "Publish exact same-repository PR managed image by digest"); const logout = step(prBuilder, "Remove PR publication credentials"); + const exportContract = step(prBuilder, "Export exact published PR managed-image contract"); + const uploadContract = step(prBuilder, "Upload exact published PR managed-image contract"); const sameRepository = "github.event.pull_request.head.repo.full_name == github.repository"; expect(login.if).toBe(sameRepository); expect(publish.if).toBe(sameRepository); @@ -625,6 +627,11 @@ describe("complete managed-image publication workflow", () => { }); expect(publish.with?.tags).toBeUndefined(); expect(logout.if).toContain(sameRepository); + expect(exportContract.if).toBe(sameRepository); + expect(uploadContract.if).toBe(sameRepository); + expect(steps.indexOf(logout)).toBeLessThan(steps.indexOf(exportContract)); + expect(exportContract.run).toContain('DOCKER_CONFIG="$anonymous_config" docker pull'); + expect(exportContract.run).toContain("revision: $revision"); expect(JSON.stringify(prBuilder).match(/secrets\.GITHUB_TOKEN/gu)).toHaveLength(1); expect(JSON.stringify(prBuilder)).not.toContain("github.token"); }); @@ -719,42 +726,37 @@ describe("complete managed-image publication workflow", () => { expect(inlineNodeStdinValidator(contractSource)).toBe(inlineNodeStdinValidator(mainContract)); }); - it("runs managed image lifecycle verification for all shipped agents only on the main branch (#7744)", () => { + it("runs the exact candidate CLI through real all-agent Docker and OpenShell activation (#7744)", () => { const workflow = readWorkflow("managed-images.yaml"); - const lifecycle = managedMainLifecycle(workflow); - const steps = lifecycle.steps ?? []; - - expect(workflow.on?.pull_request?.paths).not.toContain( - "test/e2e/live/managed-image-activation-e2e*.ts", - ); - expect(JSON.stringify(managedPrBuilder(workflow))).not.toContain("managed-pr-contract"); - expect(lifecycle.needs).toBe("promote"); - expect(lifecycle.if).toBe("github.ref == 'refs/heads/main'"); - expect(lifecycle.permissions).toEqual({ contents: "read" }); - expect(lifecycle.env?.MAIN_SHA).toBe("${{ github.sha }}"); - expect(lifecycle.env?.NEMOCLAW_MANAGED_ACTIVATION_CATALOG).toBe( - "${{ github.workspace }}/managed-main-catalog.json", + const activation = managedPrActivation(workflow); + const steps = activation.steps ?? []; + + expect(workflow.on?.pull_request?.paths).toEqual( + expect.arrayContaining([ + "src/lib/onboard/**", + "test/e2e/live/managed-image-activation-e2e*.ts", + ]), ); - expect(JSON.stringify(lifecycle)).not.toContain("secrets."); - expect(JSON.stringify(lifecycle)).not.toContain("github.token"); - expect(step(lifecycle, "Check out the workflow commit from main").with?.ref).toBe( - "${{ github.sha }}", + expect(activation.needs).toBe("pr-build-and-entrypoint"); + expect(activation.if).toContain( + "github.event.pull_request.head.repo.full_name == github.repository", ); - expect(step(lifecycle, "Download published amd64 managed image contracts").with?.pattern).toBe( - "managed-image-${{ github.run_id }}-${{ github.run_attempt }}-*-linux-amd64", + expect(activation.permissions).toEqual({ contents: "read" }); + expect(activation.env?.CANDIDATE_SHA).toBe("${{ github.event.pull_request.head.sha }}"); + expect(activation.env?.NEMOCLAW_MANAGED_ACTIVATION_CATALOG).toBe( + "${{ github.workspace }}/managed-pr-catalog.json", ); - const assemble = step(lifecycle, "Assemble managed image lifecycle catalog").run ?? ""; - expect(assemble).toContain("([.[].contractVersion] | unique) == [2]"); - expect(assemble).toContain("contractVersion: 1"); - expect(assemble).toContain('release="v$(node -p'); - expect(step(lifecycle, "Build the CLI from the workflow commit").run).toContain( - "npm run build:cli", + expect(JSON.stringify(activation)).not.toContain("secrets."); + expect(JSON.stringify(activation)).not.toContain("github.token"); + expect(step(activation, "Checkout exact PR head").with?.ref).toBe( + "${{ github.event.pull_request.head.sha }}", ); - expect(step(lifecycle, "Install OpenShell CLI").run).toContain("scripts/install-openshell.sh"); - const run = step(lifecycle, "Verify managed image lifecycle for all shipped agents").run ?? ""; - expect(run).toContain('[[ "$(git rev-parse --verify HEAD)" == "$MAIN_SHA" ]]'); + expect(step(activation, "Build exact candidate CLI").run).toContain("npm run build:cli"); + expect(step(activation, "Install OpenShell CLI").run).toContain("scripts/install-openshell.sh"); + const run = step(activation, "Run real all-agent managed runtime activation").run ?? ""; + expect(run).toContain('[[ "$(git rev-parse --verify HEAD)" == "$CANDIDATE_SHA" ]]'); expect(run).toContain("test/e2e/live/managed-image-activation-e2e.test.ts"); - expect(steps.map(({ name }) => name)).toContain("Upload managed image lifecycle evidence"); + expect(steps.map(({ name }) => name)).toContain("Upload managed runtime activation evidence"); }); it("keeps the activation proof outside mocked runtime boundaries (#7744)", () => { diff --git a/test/openshell-e2e-qualification.test.ts b/test/openshell-e2e-qualification.test.ts index baf0e04b9ca..2a19801d4c1 100644 --- a/test/openshell-e2e-qualification.test.ts +++ b/test/openshell-e2e-qualification.test.ts @@ -189,7 +189,7 @@ function fullApi(files = [prFile("scripts/install-openshell.sh")]): GitHubReader [ (apiPath) => apiPath.includes(`/commits/${HEAD_SHA}/check-runs?`), () => { - const names = [REQUIRED_PROOF_CHECKS.rootless]; + const names = [REQUIRED_PROOF_CHECKS.managed, REQUIRED_PROOF_CHECKS.rootless]; return { check_runs: names.map((name, index) => ({ conclusion: "success", @@ -268,7 +268,7 @@ describe("OpenShell qualification-sensitive path detection", () => { expect(isOpenShellQualificationSensitivePath("docs/index.mdx")).toBe(false); }); - it("does not require managed-image activation before merge and retains the rootless lifecycle check", () => { + it("uses both sides of a rename and aligns separate proof requirements with workflow filters", () => { const renamed = validatePullRequestFile({ filename: "docs/retired.mdx", previous_filename: "scripts/install-openshell.sh", @@ -276,18 +276,18 @@ describe("OpenShell qualification-sensitive path detection", () => { }); expect(classifyQualification([renamed])).toEqual({ required: true, - requiredProofChecks: [REQUIRED_PROOF_CHECKS.rootless], + requiredProofChecks: [REQUIRED_PROOF_CHECKS.managed, REQUIRED_PROOF_CHECKS.rootless], sensitivePaths: ["scripts/install-openshell.sh"], }); expect( classifyQualification([validatePullRequestFile(prFile("agents/hermes/manifest.yaml"))]) .requiredProofChecks, - ).toEqual([]); + ).toEqual([REQUIRED_PROOF_CHECKS.managed]); expect( classifyQualification([ validatePullRequestFile(prFile("scripts/checks/verify-openshell-e2e-qualification.mts")), ]).requiredProofChecks, - ).toEqual([]); + ).toEqual([REQUIRED_PROOF_CHECKS.managed]); }); it.each([ @@ -442,6 +442,7 @@ describe("qualification orchestration", () => { }); expect(evidence.e2e?.runId).toBe(RUN_ID); expect(evidence.proofChecks.map((check) => check.name)).toEqual([ + REQUIRED_PROOF_CHECKS.managed, REQUIRED_PROOF_CHECKS.rootless, ]); }); diff --git a/test/vitest-developer-feedback.test.ts b/test/vitest-developer-feedback.test.ts index 2f6a91dbd82..ac65947e880 100644 --- a/test/vitest-developer-feedback.test.ts +++ b/test/vitest-developer-feedback.test.ts @@ -38,11 +38,9 @@ describe("Vitest developer feedback", () => { expect(testOptions.silent).toBe(resolveVitestFeedback().silent); }); - it("runs changed feedback, the growth contract, and focused watch feedback (#6692)", ({ - resources, - }) => { + it("runs changed and watch feedback on the focused source projects (#6692)", ({ resources }) => { expect(runVitestNpmScript(resources, "test:changed")).toBe( - `vitest run --changed ${focusedProjects}\nvitest run --project integration test/codebase-growth-contract.test.ts`, + `vitest run --changed ${focusedProjects}`, ); expect(runVitestNpmScript(resources, "test:watch")).toBe(`vitest watch ${focusedProjects}`); }); diff --git a/tools/growth-guardrails/check-pr.mts b/tools/growth-guardrails/check-pr.mts deleted file mode 100644 index ba13dbde292..00000000000 --- a/tools/growth-guardrails/check-pr.mts +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 -// -// Trusted pull-request adapter for codebase growth policies. The workflow runs -// this base-revision code and treats pull-request files and blobs as data only. - -import { createPrBlobClient, type PrBlobClient, type PullRequestFile } from "./pr-blob-client.mts"; -import { runTestConditionals, type ConditionalEnv } from "./test-conditionals.mts"; -import { runTestSizeBudget, type BudgetEnv } from "./test-size-budget.mts"; - -const JAVASCRIPT_FILE_RE = /\.(?:js|cjs|mjs|jsx)$/; -const ONBOARD_ENTRYPOINT = "src/lib/onboard.ts"; - -export type GrowthGuardrailEnv = ConditionalEnv & BudgetEnv & { readonly GH_TOKEN: string }; - -export function evaluateAddedJavaScriptFiles(files: readonly PullRequestFile[]): string[] { - return files - .filter( - ({ filename, previous_filename, status }) => - JAVASCRIPT_FILE_RE.test(filename) && - (status === "added" || - (status === "renamed" && !JAVASCRIPT_FILE_RE.test(previous_filename ?? ""))), - ) - .map(({ filename }) => `${filename}: new JavaScript files must use TypeScript`); -} - -export function evaluateOnboardGrowth(files: readonly PullRequestFile[]): string[] { - const rows = files.filter( - ({ filename, previous_filename }) => - filename === ONBOARD_ENTRYPOINT || previous_filename === ONBOARD_ENTRYPOINT, - ); - const additions = rows.reduce((total, file) => total + (file.additions ?? 0), 0); - const deletions = rows.reduce((total, file) => total + (file.deletions ?? 0), 0); - const net = additions - deletions; - return net > 0 - ? [`${ONBOARD_ENTRYPOINT}: grew by ${net} line(s) (+${additions}/-${deletions})`] - : []; -} - -export async function runGrowthGuardrails( - client: PrBlobClient, - env: GrowthGuardrailEnv, -): Promise { - const files = await client.getPullFiles(env.REPO, env.PR_NUMBER); - const violations = [...evaluateAddedJavaScriptFiles(files), ...evaluateOnboardGrowth(files)]; - const size = await runTestSizeBudget(client, env, files); - violations.push(...size.violations); - const conditionals = await runTestConditionals(client, env, files); - violations.push(...conditionals.details); - return violations; -} - -function readEnv(): GrowthGuardrailEnv { - const { BASE_SHA, GH_TOKEN, HEAD_REPO, HEAD_SHA, PR_NUMBER, REPO } = process.env; - if (!BASE_SHA || !GH_TOKEN || !HEAD_REPO || !HEAD_SHA || !PR_NUMBER || !REPO) { - throw new Error( - "Missing required environment: BASE_SHA GH_TOKEN HEAD_REPO HEAD_SHA PR_NUMBER REPO", - ); - } - return { BASE_SHA, GH_TOKEN, HEAD_REPO, HEAD_SHA, PR_NUMBER, REPO }; -} - -async function main(): Promise { - const env = readEnv(); - const client = createPrBlobClient({ token: env.GH_TOKEN }); - const violations = await runGrowthGuardrails(client, env); - if (violations.length > 0) { - console.error("FAIL: codebase growth policies rejected this PR."); - for (const violation of violations) console.error(`- ${violation}`); - console.error("Run current-file checks locally: npm run test:changed"); - console.error( - "The local check validates the current budget file but does not compare its limits with the base commit.", - ); - process.exit(1); - } - console.log("PASS: this PR preserves the codebase growth policies."); -} - -if (import.meta.url === `file://${process.argv[1]}`) { - main().catch((error) => { - console.error(error); - process.exit(1); - }); -} diff --git a/tools/growth-guardrails/codebase-contract.mts b/tools/growth-guardrails/codebase-contract.mts deleted file mode 100644 index beb54a6d3c2..00000000000 --- a/tools/growth-guardrails/codebase-contract.mts +++ /dev/null @@ -1,108 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync } from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -import { countLines } from "../../scripts/check-test-file-size-budget.mts"; -import { evaluateAddedJavaScriptFiles } from "./check-pr.mts"; -import type { PullRequestFile } from "./pr-blob-client.mts"; -import { - evaluateConditionalViolations, - isTestFilePath, - type ConditionalChange, -} from "./test-conditionals.mts"; - -const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); -const ONBOARD_ENTRYPOINT = "src/lib/onboard.ts"; - -type LocalChange = PullRequestFile & { readonly status: string }; - -function git(args: readonly string[]): string { - return execFileSync("git", [...args], { - cwd: REPO_ROOT, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"], - }); -} - -function mergeBase(): string { - return git(["merge-base", "origin/main", "HEAD"]).trim(); -} - -function collectChanges(): LocalChange[] { - - // `git diff ` compares the merge base with tracked working-tree content. - // Add untracked files separately. - const tokens = git(["diff", "--name-status", "-z", "--find-renames", mergeBase(), "--"]) - .split("\0") - .filter(Boolean); - const changes: LocalChange[] = []; - for (let index = 0; index < tokens.length; ) { - const code = tokens[index++]; - const renamed = code.startsWith("R") || code.startsWith("C"); - const previous = renamed ? tokens[index++] : null; - const filename = tokens[index++]; - changes.push({ - filename, - previous_filename: previous, - status: code.startsWith("A") - ? "added" - : code.startsWith("D") - ? "removed" - : renamed - ? "renamed" - : "modified", - }); - } - const known = new Set(changes.map(({ filename }) => filename)); - const untracked = git(["ls-files", "--others", "--exclude-standard", "-z"]) - .split("\0") - .filter((file) => file && !known.has(file)); - return [...changes, ...untracked.map((filename) => ({ filename, status: "added" }))]; -} - -function readBaseFile(base: string, file: string): string | null { - try { - return git(["show", `${base}:${file}`]); - } catch { - return null; - } -} - -function readCurrentFile(file: string): string | null { - const absolute = path.join(REPO_ROOT, file); - return existsSync(absolute) ? readFileSync(absolute, "utf8") : null; -} - -export function evaluateCurrentJavaScriptContract(): string[] { - return evaluateAddedJavaScriptFiles(collectChanges()); -} - -export function evaluateCurrentOnboardContract(): string[] { - const base = readBaseFile(mergeBase(), ONBOARD_ENTRYPOINT) ?? ""; - const current = readCurrentFile(ONBOARD_ENTRYPOINT) ?? ""; - const growth = countLines(current) - countLines(base); - return growth > 0 ? [`${ONBOARD_ENTRYPOINT}: grew by ${growth} line(s)`] : []; -} - -export function evaluateCurrentTestConditionalContract(): string[] { - const base = mergeBase(); - const changes: ConditionalChange[] = []; - const baseBlobs = new Map(); - const headBlobs = new Map(); - for (const file of collectChanges()) { - if (!isTestFilePath(file.filename) && !isTestFilePath(file.previous_filename ?? "")) continue; - const basePath = isTestFilePath(file.previous_filename ?? "") - ? (file.previous_filename as string) - : file.filename; - const headPath = - file.status === "removed" || !isTestFilePath(file.filename) ? null : file.filename; - changes.push({ basePath, headPath, displayName: file.filename }); - baseBlobs.set(basePath, readBaseFile(base, basePath)); - if (headPath !== null) headBlobs.set(headPath, readCurrentFile(headPath)); - } - return evaluateConditionalViolations(changes, baseBlobs, headBlobs).details; -} diff --git a/tools/growth-guardrails/test-conditionals.mts b/tools/growth-guardrails/test-conditionals.mts index 8234ebcbbb6..c3e44f3c919 100644 --- a/tools/growth-guardrails/test-conditionals.mts +++ b/tools/growth-guardrails/test-conditionals.mts @@ -6,24 +6,21 @@ // blobs as DATA only — blob text is PARSED with the TypeScript AST, never // executed. // -// The `if`-statement count reuses the repository contract scanner so local -// Vitest feedback and the trusted PR assertion use one parser. +// The `if`-statement count reuses scanTextForTestConditionals from the local +// scanner (scripts/find-test-conditionals.mts) so the workflow and +// `npm run test-conditionals:scan` agree by construction. No second lexer lives +// in workflow YAML. import { scanTextForTestConditionals } from "../../scripts/find-test-conditionals.mts"; import { assertRepositoryName, type BlobMap, + createPrBlobClient, type PrBlobClient, - type PullRequestFile, } from "./pr-blob-client.mts"; const TEST_FILE_RE = /^(test|src|nemoclaw\/src)\/.*\.(test|spec)\.(?:[cm]?[jt]s)$/; - -export function isTestFilePath(file: string): boolean { - return TEST_FILE_RE.test(file); -} - /** Count `if` statements in test source using the shared TypeScript AST scanner. */ export function countIfStatements(file: string, text: string): number { return scanTextForTestConditionals(file, text).length; @@ -90,12 +87,11 @@ export type ConditionalResult = ConditionalEvaluation & { readonly ok: boolean } export async function runTestConditionals( client: PrBlobClient, env: ConditionalEnv, - pullFiles?: readonly PullRequestFile[], ): Promise { assertRepositoryName(env.REPO, "REPO"); assertRepositoryName(env.HEAD_REPO, "HEAD_REPO"); - const files = pullFiles ?? (await client.getPullFiles(env.REPO, env.PR_NUMBER)); + const files = await client.getPullFiles(env.REPO, env.PR_NUMBER); const changedTests = files.filter( ({ filename, previous_filename }) => TEST_FILE_RE.test(filename) || TEST_FILE_RE.test(previous_filename ?? ""), @@ -123,3 +119,45 @@ export async function runTestConditionals( const evaluation = evaluateConditionalViolations(changes, baseBlobs, headBlobs); return { ...evaluation, ok: evaluation.details.length === 0 }; } + +function readEnv(): ConditionalEnv & { GH_TOKEN: string } { + const { BASE_SHA, GH_TOKEN, HEAD_REPO, HEAD_SHA, PR_NUMBER, REPO } = process.env; + if (!BASE_SHA || !GH_TOKEN || !HEAD_REPO || !HEAD_SHA || !PR_NUMBER || !REPO) { + throw new Error( + "Missing required environment: BASE_SHA GH_TOKEN HEAD_REPO HEAD_SHA PR_NUMBER REPO", + ); + } + return { BASE_SHA, GH_TOKEN, HEAD_REPO, HEAD_SHA, PR_NUMBER, REPO }; +} + +async function main(): Promise { + const env = readEnv(); + const client = createPrBlobClient({ token: env.GH_TOKEN }); + const result = await runTestConditionals(client, env); + if (!result.ok) { + console.error("FAIL: changed test files add if statements."); + console.error( + `Changed test files contain ${result.headTotal} if statement(s) at PR head vs ${result.baseTotal} at base.`, + ); + console.error(""); + console.error( + "Test bodies should stay linear. Split conditional behavior into separate test cases, use it.skipIf/it.runIf for platform or environment gates, or move non-asserting setup branches into named helpers.", + ); + console.error(""); + console.error("Files with increased if counts:"); + for (const detail of result.details) console.error(`- ${detail}`); + console.error(""); + console.error("Run locally: npm run test-conditionals:scan -- --top 25"); + process.exit(1); + } + console.log( + `PASS: changed test files did not add if statements (${result.headTotal} at PR head vs ${result.baseTotal} at base).`, + ); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((error) => { + console.error(error); + process.exit(1); + }); +} diff --git a/tools/growth-guardrails/test-size-budget.mts b/tools/growth-guardrails/test-size-budget.mts index 00ab368f449..f64500d0d55 100644 --- a/tools/growth-guardrails/test-size-budget.mts +++ b/tools/growth-guardrails/test-size-budget.mts @@ -5,15 +5,21 @@ // and the budget itself must stay monotonic (a PR may not weaken it). Runs from // the base checkout under pull_request_target and reads PR blobs as DATA only. // -// Line counting and budget parsing are shared with the repository contract test, -// so local feedback and the trusted PR assertion use one implementation. +// Line counting and budget parsing are reused from the local scanner +// (scripts/check-test-file-size-budget.mts) so the workflow and the local check +// agree by construction — no second implementation lives in workflow YAML. import { countLines, parseBudget, type TestFileSizeBudget, } from "../../scripts/check-test-file-size-budget.mts"; -import { type BlobMap, type PrBlobClient, type PullRequestFile } from "./pr-blob-client.mts"; +import { + type BlobMap, + createPrBlobClient, + type PrBlobClient, + type PullRequestFile, +} from "./pr-blob-client.mts"; const BUDGET_FILE = "ci/test-file-size-budget.json"; const FALLBACK_BUDGET = '{"defaultMaxLines":1500,"legacyMaxLines":{}}'; @@ -121,9 +127,8 @@ export type BudgetResult = { export async function runTestSizeBudget( client: PrBlobClient, env: BudgetEnv, - pullFiles?: readonly PullRequestFile[], ): Promise { - const files = pullFiles ?? (await client.getPullFiles(env.REPO, env.PR_NUMBER)); + const files = await client.getPullFiles(env.REPO, env.PR_NUMBER); const budgetChanged = files.some( ({ filename, previous_filename }) => filename === BUDGET_FILE || previous_filename === BUDGET_FILE, @@ -180,3 +185,34 @@ export async function runTestSizeBudget( return { ok: violations.length === 0, violations, changedTestCount: changedTests.length }; } + +function readEnv(): BudgetEnv & { GH_TOKEN: string } { + const { BASE_SHA, GH_TOKEN, HEAD_REPO, HEAD_SHA, PR_NUMBER, REPO } = process.env; + if (!BASE_SHA || !GH_TOKEN || !HEAD_REPO || !HEAD_SHA || !PR_NUMBER || !REPO) { + throw new Error( + "Missing required environment: BASE_SHA GH_TOKEN HEAD_REPO HEAD_SHA PR_NUMBER REPO", + ); + } + return { BASE_SHA, GH_TOKEN, HEAD_REPO, HEAD_SHA, PR_NUMBER, REPO }; +} + +async function main(): Promise { + const env = readEnv(); + const client = createPrBlobClient({ token: env.GH_TOKEN }); + const result = await runTestSizeBudget(client, env); + if (!result.ok) { + console.error("FAIL: test size budget policy would be weakened or exceeded."); + for (const violation of result.violations) console.error(`- ${violation}`); + process.exit(1); + } + console.log( + `PASS: test size budget policy is monotonic and ${result.changedTestCount} changed test file(s) are within budget.`, + ); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((error) => { + console.error(error); + process.exit(1); + }); +} diff --git a/tools/growth-guardrails/workflow-boundary.mts b/tools/growth-guardrails/workflow-boundary.mts index 14d4b388309..588b0242b17 100644 --- a/tools/growth-guardrails/workflow-boundary.mts +++ b/tools/growth-guardrails/workflow-boundary.mts @@ -18,9 +18,10 @@ import YAML from "yaml"; /** The only ref a checkout in this workflow may use: the trusted base commit. */ export const TRUSTED_BASE_REF = "${{ github.event.pull_request.base.sha }}"; -/** The only trusted policy entrypoint executed by the workflow. */ +/** The trusted tool entrypoints that replace the former inline node heredocs. */ export const REQUIRED_TOOL_INVOCATIONS = [ - "node --experimental-strip-types tools/growth-guardrails/check-pr.mts", + "node --experimental-strip-types tools/growth-guardrails/test-size-budget.mts", + "node --experimental-strip-types tools/growth-guardrails/test-conditionals.mts", ] as const; const HEAD_REF_MARKERS = [ @@ -40,6 +41,14 @@ const APPROVED_JOB_ENVELOPE_SHA256 = // while allowing comments and YAML formatting to change without weakening the // trust boundary. const APPROVED_STEP_SHAPES = [ + { + name: "Block newly added JavaScript files", + sha256: "c2291c5ea47f093845b8e6bc6a93698fd9fe3f617b5c03265c2803439749ea38", + }, + { + name: "Require src/lib/onboard.ts to be net-neutral or smaller", + sha256: "92aba85cd31e30bfaa9cdd05dde6962f14373b1d60a9121bfcea48146ca0348b", + }, { name: "Check out the trusted base revision", sha256: "4ec2659f39a08af0cb6abf60ab63a6732ab2375f538fc5b80601d566fdbcbc5a", @@ -49,8 +58,12 @@ const APPROVED_STEP_SHAPES = [ sha256: "2388fa3f5694ed0db8df96bf5f2bbcc3f377d5fe66e433b32d0ef71e88d0f362", }, { - name: "Enforce the codebase growth contract", - sha256: "281c93a2c5f707db84cee0fc809749968b02a51f4a150cae9497c8b8ff0772d7", + name: "Require changed test files to stay within size budget", + sha256: "5d631c12f457e947bd7bd83447ab2a294cbe4d8430dbed4e92d09d7f7594dd3b", + }, + { + name: "Require changed test files not to add if statements", + sha256: "991a7036d27aeb45fde2f3178936fba6ac87b90200b79c933015f9d63525d3cf", }, ] as const; @@ -228,7 +241,7 @@ export function validateGrowthGuardrailsWorkflowBoundary(workflowPath: string): } } - // 5. The consolidated policy must still use its pinned trusted entrypoint. + // 5. Each policy must still be invoked through its pinned trusted tool. const runScripts = steps.flatMap((step) => (step.run ? [step.run] : [])); const allRun = runScripts.join("\n"); for (const invocation of REQUIRED_TOOL_INVOCATIONS) {