diff --git a/.claude/skills/pr-flow/SKILL.md b/.claude/skills/pr-flow/SKILL.md index 6eabd07ad6..a157765e79 100644 --- a/.claude/skills/pr-flow/SKILL.md +++ b/.claude/skills/pr-flow/SKILL.md @@ -146,11 +146,26 @@ npm run format # TypeScript; in a Python server: uv run --fro npm run local:gate; echo "EXIT=$?" ``` -`local:gate` runs every check CI runs, for both languages, whatever the change -touched. Verify by the exit code, not by grepping the output. What each stage -checks and how to fix a red one is `/pre-push-gate`; the stage list is +`local:gate` runs every check CI runs, for both languages. Its per-server +stages run for the servers the change touches, and for every server when any +file outside a server directory changed; it prints which, and why. Verify by +the exit code, not by grepping the output. What each stage checks and how to +fix a red one is `/pre-push-gate`; the stage list and the scope rule are in [`docs/quality-gate.md`](../../../docs/quality-gate.md). +**A draft PR** (`gh pr create --draft`) needs less until it is marked ready +(`AGENTS.md` **Before pushing**): + +| The PR is | Before each push | In CI | +| --- | --- | --- | +| A draft | `npm run local:gate:draft` (exit 0): `verify:dco` and the touched servers' full `validate` / `validate:py` | Format, lint, typecheck, build and tests; coverage, the boot smoke, the interface diff and the image smoke are skipped | +| Being marked ready | A full `npm run local:gate` (exit 0), then `gh pr ready ` | `ready_for_review` runs what the draft skipped | +| Ready | `npm run local:gate`, as above | Everything | + +A draft is for work still moving, when you want CI or a reviewer's eye before +it settles. A PR that is finished when it opens is opened ready, after a full +gate, as above; the Copilot loop (step 7) starts once it is ready. + One thing the gate deliberately leaves out: | Change touches | Also run | diff --git a/.claude/skills/pre-push-gate/SKILL.md b/.claude/skills/pre-push-gate/SKILL.md index 78e8a22691..4fa7bf67cd 100644 --- a/.claude/skills/pre-push-gate/SKILL.md +++ b/.claude/skills/pre-push-gate/SKILL.md @@ -8,7 +8,10 @@ disable-model-invocation: false **The rule** (stated in [`AGENTS.md`](../../../AGENTS.md#before-pushing)): run **`npm run local:gate`** before every push, and push only when it exits 0. -`npm run validate` is the inner-loop check and is **not** a substitute. +`npm run validate` is the inner-loop check and is **not** a substitute. The +one lighter gate is **`npm run local:gate:draft`**, for a push to a PR that is +still a draft; marking the PR ready for review needs a full `local:gate` +first, and so does every push after that. What each stage covers, and how the gate relates to CI, is [`docs/quality-gate.md`](../../../docs/quality-gate.md). The stage list is @@ -41,6 +44,33 @@ The gate stops at the first failing stage, so the last stage header in the output is the one that failed. Fix it, then **re-run the whole gate**, not just that stage: the stages after it have not run yet. +## Which servers it ran + +The per-server stages (`check`, `coverage`, `validate:py`, `coverage:py`, +`smoke`) run through `scripts/gate-servers.mjs`, which prints its choice +first: + +``` +[gate] base 002bcceed159 +[gate] servers: memory — every changed file is under `src/memory/` +``` + +and then one `[gate] : ` line per step, with `passed (Ns)` or +`FAILED (exit N, Ns)` after it. A change confined to server directories gates +those servers; **any file outside one gates every server**, and the line names +the first few such files. If it gated more than you expected, that line says +why: an untracked file in the worktree root counts too (`git status`). Do not +work around the scope; the rule is in +[`docs/quality-gate.md`](../../../docs/quality-gate.md#which-servers-the-gate-runs). + +- **"could not decide which servers to gate"**: usually `origin/v2/main` is + missing, so `git fetch origin v2/main`. On a stacked branch, + `GATE_BASE= npm run local:gate` scopes against the parent. +- **Each suite runs once, under coverage.** A failing test shows up in the + `coverage` or `coverage:py` step, not in a plain `test` or `pytest` step; + fix it as under [`test`](#test-a-typescript-workspace) or `validate:py`'s + `pytest` below. + ## Diagnosing a failing stage Each heading is a stage or guard name as it appears in the output. @@ -148,7 +178,9 @@ mean a change broke one of its invariants - **"every CI job needs a timeout"**: a job was added without `timeout-minutes`. - **"local:gate must run …"**: a stage was dropped from `local:gate:stages`, - or `local:gate` is no longer exactly the lease wrapper. + or `local:gate` is no longer exactly the lease wrapper. The per-server + stages are pinned through `gatePlan` in `scripts/gate-servers.mjs` ("the + full gate must run …"). Do not edit the guard to make these pass; the split they enforce is the design. @@ -159,6 +191,12 @@ a warning fails exactly as an error does. Fix the finding. If a rule genuinely must be waived on one line, use its inline disable comment **with a one-line justification**; never widen an ignore list or turn the rule off. +### `check` (a TypeScript workspace) + +The workspace's `validate` without its tests: `format:check`, `lint`, +`typecheck`, `build`, in that order. The failing one is named in the npm +output; each has its own section here. + ### `typecheck` / `build` `typecheck` runs `tsc -p tsconfig.test.json` (source and tests); `build` runs @@ -166,8 +204,10 @@ the server's own `tsc`. An error in a test file only shows in `typecheck`. ### `test` (a TypeScript workspace) -Re-run just that suite to iterate: `npm test -w src/`. Read the failure -before changing a timeout: an assertion that races is a bug in the test. +The full gate runs the suite only under `coverage`; `local:gate:draft` runs it +plainly, inside each workspace's `validate`. Re-run just that suite to +iterate: `npm test -w src/`. Read the failure before changing a +timeout: an assertion that races is a bug in the test. ### `coverage` @@ -179,8 +219,8 @@ ERROR: Coverage for branches (71.42%) does not meet global threshold (90%) for r ``` ("global threshold" is Vitest's wording; with `perFile: true` it is checked -per file.) The root `npm run coverage` carries on into the remaining -workspaces after a failure, so **the failing report is not the last thing +per file.) Over several workspaces, `npm run coverage` carries on into the +remaining ones after a failure, so **the failing report is not the last thing printed**: find the `npm ERR!` block, which names the workspace (`in workspace: @modelcontextprotocol/server-`), and read the `ERROR:` lines just above it. @@ -207,7 +247,9 @@ fix it as under `test`, above. The summary at the end names the failing server, and the step that failed is the last `[validate:py] : ` line above it. Re-run one server with -`npm run validate:py -- `. +`npm run validate:py -- `. The full gate passes `--no-pytest`, since +`coverage:py` runs the suite next; `local:gate:draft` and a bare +`npm run validate:py` run it here. | Step | Fix | | --- | --- | @@ -260,7 +302,7 @@ of the server's stderr. Re-run a subset with - **"dist/index.js does not exist — build first"**: you ran the smoke on its own before building. `npm run build -w src/`. Inside the gate this - cannot happen, since `validate` builds first. + cannot happen, since `check` builds first. - **".venv does not exist — sync first"**: the same for a Python server. The smoke never creates an environment; `npm run validate:py -- ` does. - **The server exited before answering**: the stderr tail shows why. This is diff --git a/.github/workflows/image-smoke.yml b/.github/workflows/image-smoke.yml index 0931b56a39..7ec3283ded 100644 --- a/.github/workflows/image-smoke.yml +++ b/.github/workflows/image-smoke.yml @@ -35,7 +35,10 @@ on: branches: [main, v2/main] # No branch filter: PRs to v2/main and to main both run, and so does a PR # stacked on another PR's branch. The base is the PR's own base either way. + # A draft PR is skipped (#5759, the `if:` on `changes`); `ready_for_review` + # runs it once it is marked ready, and every later push runs it too. pull_request: + types: [opened, synchronize, reopened, ready_for_review] workflow_dispatch: permissions: @@ -50,6 +53,9 @@ concurrency: jobs: changes: name: Choose the images to build + # Every other job here needs this one, so skipping it on a draft skips + # the whole run. + if: github.event_name != 'pull_request' || !github.event.pull_request.draft timeout-minutes: 10 runs-on: ubuntu-latest outputs: diff --git a/.github/workflows/mcp-interface-diff.yml b/.github/workflows/mcp-interface-diff.yml index e8ca5936e7..47108093d6 100644 --- a/.github/workflows/mcp-interface-diff.yml +++ b/.github/workflows/mcp-interface-diff.yml @@ -67,7 +67,10 @@ on: branches: [main, v2/main] # No branch filter: PRs to v2/main and to main both run, and so does a PR # stacked on another PR's branch. The base is the PR's own base either way. + # A draft PR is skipped (#5759, the `if:` on `changes`); `ready_for_review` + # runs it once it is marked ready, and every later push runs it too. pull_request: + types: [opened, synchronize, reopened, ready_for_review] # A published Release (a milestone, tagged vX.Y.Z on main; see RELEASING.md) # surfaces the cumulative interface delta since the previous Release, for # each server that changed in between. This replaces #3260's @@ -99,6 +102,9 @@ concurrency: jobs: changes: name: Choose the servers to diff + # Every other job here needs this one, so skipping it on a draft skips + # the whole run. + if: github.event_name != 'pull_request' || !github.event.pull_request.draft timeout-minutes: 10 runs-on: ubuntu-latest permissions: diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 219e515924..54afcdab65 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -1,9 +1,10 @@ name: Python on: - # Push only, as in the Inspector: with pull_request as well, every commit on a - # PR branch ran each workflow twice (once per event). PR checks still report - # from the push run of the head commit. + # Push, as in the Inspector: with every pull_request event as well, every + # commit on a PR branch ran each workflow twice (once per event). PR checks + # still report from the push run of the head commit. The one pull_request + # event taken, `ready_for_review` below, runs only what a draft skipped. push: # A push made with the workflow token starts no workflow, so the version PRs # that automation opens (Version Packages, Prepare Python Release) get no @@ -13,6 +14,11 @@ on: # leaves dispatched checks out, so the `dispatch-status` jobs below report # the run as a commit status instead. workflow_dispatch: + # A draft pull request's pushes skip the coverage gate (#5759; see the + # `draft` job). Marking it ready for review runs exactly that, against the + # PR's merge commit; every later push runs it too. + pull_request: + types: [ready_for_review] # Superseded runs on the same ref are cancelled (e.g. rapid amend-pushes), # except on main, where every merge keeps its own CI run @@ -28,6 +34,37 @@ permissions: contents: read jobs: + # Whether this push goes to a draft pull request's branch (#5759): the same + # job as in typescript.yml. A draft still gets ruff, pyright, pytest and the + # build on every push; the coverage gate waits until it is marked ready. Any + # other run, and a failed lookup, reads as not a draft. + draft: + timeout-minutes: 5 + runs-on: ubuntu-latest + permissions: + pull-requests: read + outputs: + draft: ${{ steps.state.outputs.draft }} + steps: + - name: Look up the branch's pull request + id: state + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + EVENT: ${{ github.event_name }} + BRANCH: ${{ github.ref_name }} + run: | + DRAFT=false + # v2/main is the head of the release merge PR into main, which can + # be a draft; neither long-lived branch is ever a draft's branch. + if [ "$EVENT" = push ] && [ "$BRANCH" != v2/main ] && [ "$BRANCH" != main ]; then + DRAFT=$(gh pr list --head "$BRANCH" --state open --json isDraft \ + --jq 'if length > 0 and all(.[]; .isDraft) then "true" else "false" end') \ + || DRAFT=false + fi + echo "draft=$DRAFT" >> "$GITHUB_OUTPUT" + echo "draft pull request: $DRAFT" + detect-packages: timeout-minutes: 5 runs-on: ubuntu-latest @@ -45,6 +82,9 @@ jobs: script-tests: timeout-minutes: 5 + # The draft's last push ran it; the ready event re-runs only what a + # draft skips. + if: github.event_name != 'pull_request' name: Test the Python gate script runs-on: ubuntu-latest steps: @@ -59,7 +99,8 @@ jobs: test: timeout-minutes: 15 - needs: [detect-packages] + needs: [detect-packages, draft] + if: github.event_name != 'pull_request' strategy: matrix: package: ${{ fromJson(needs.detect-packages.outputs.packages) }} @@ -81,9 +122,13 @@ jobs: node-version: 24 # The same per-server chain `npm run validate:py` runs locally: locked - # sync, ruff check, ruff format --check, pyright, pytest, uv build. + # sync, ruff check, ruff format --check, pyright, pytest, uv build. Each + # suite runs once (#5759): pytest is left to the `coverage` job, which + # runs it instrumented, except on a draft, where `coverage` is skipped. - name: Validate - run: node scripts/validate-py.mjs ${{ matrix.package }} + env: + NO_PYTEST: ${{ needs.draft.outputs.draft != 'true' && '--no-pytest' || '' }} + run: node scripts/validate-py.mjs $NO_PYTEST ${{ matrix.package }} # The per-file coverage gate (#4855), in parallel with `test`: every file of # each server at >= 90% on lines and on branches. The same script @@ -91,7 +136,9 @@ jobs: # one server's shortfall does not cancel the other legs' verdicts. coverage: timeout-minutes: 15 - needs: [detect-packages] + needs: [detect-packages, draft] + # Skipped on a draft (#5759), whose `test` legs run pytest instead. + if: needs.draft.outputs.draft != 'true' strategy: fail-fast: false matrix: @@ -121,6 +168,7 @@ jobs: test-windows: timeout-minutes: 20 needs: [detect-packages] + if: github.event_name != 'pull_request' strategy: fail-fast: false matrix: @@ -239,6 +287,7 @@ jobs: needs: [ dispatch-status-pending, + draft, detect-packages, script-tests, test, diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index d3fbcd1331..d727e94110 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -1,9 +1,10 @@ name: TypeScript on: - # Push only, as in the Inspector: with pull_request as well, every commit on a - # PR branch ran each workflow twice (once per event). PR checks still report - # from the push run of the head commit. + # Push, as in the Inspector: with every pull_request event as well, every + # commit on a PR branch ran each workflow twice (once per event). PR checks + # still report from the push run of the head commit. The one pull_request + # event taken, `ready_for_review` below, runs only what a draft skipped. push: # A push made with the workflow token starts no workflow, so the version PRs # that automation opens (Version Packages, Prepare Python Release) get no @@ -13,6 +14,11 @@ on: # leaves dispatched checks out, so the `dispatch-status` jobs below report # the run as a commit status instead. workflow_dispatch: + # A draft pull request's pushes skip the coverage gate and the boot smoke + # (#5759; see the `draft` job). Marking it ready for review runs exactly + # those, against the PR's merge commit; every later push runs them too. + pull_request: + types: [ready_for_review] # Superseded runs on the same ref are cancelled (e.g. rapid amend-pushes), # except on main, where every merge keeps its own CI run @@ -28,6 +34,39 @@ permissions: contents: read jobs: + # Whether this push goes to a draft pull request's branch (#5759). A draft + # still gets format, lint, typecheck, build and tests on every push; the + # coverage gate and the boot smoke wait until it is marked ready, which + # starts this workflow again (`ready_for_review` above). A branch with no + # open PR, `v2/main`, `main`, a dispatch and the ready event itself all read + # as not a draft, and so does a failed lookup: when in doubt, run it all. + draft: + timeout-minutes: 5 + runs-on: ubuntu-latest + permissions: + pull-requests: read + outputs: + draft: ${{ steps.state.outputs.draft }} + steps: + - name: Look up the branch's pull request + id: state + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + EVENT: ${{ github.event_name }} + BRANCH: ${{ github.ref_name }} + run: | + DRAFT=false + # v2/main is the head of the release merge PR into main, which can + # be a draft; neither long-lived branch is ever a draft's branch. + if [ "$EVENT" = push ] && [ "$BRANCH" != v2/main ] && [ "$BRANCH" != main ]; then + DRAFT=$(gh pr list --head "$BRANCH" --state open --json isDraft \ + --jq 'if length > 0 and all(.[]; .isDraft) then "true" else "false" end') \ + || DRAFT=false + fi + echo "draft=$DRAFT" >> "$GITHUB_OUTPUT" + echo "draft pull request: $DRAFT" + # Root-level guards: the checks over repo-wide tooling that no per-package # matrix leg covers. Created by #4863 for the skills gates; #4864 extended it # to run the root's whole `validate:guards` — the root tooling's format and @@ -75,9 +114,14 @@ jobs: echo "packages=$PACKAGES" >> $GITHUB_OUTPUT # One leg per TypeScript server, each running ONLY its own package's - # `validate` (format:check -> lint -> typecheck -> build -> test). What no - # leg covers — the root tooling and the cross-workspace guards — is the - # root-guards job above; together they are the root `npm run validate`. + # `check` (format:check -> lint -> typecheck -> build) and then its tests. + # What no leg covers — the root tooling and the cross-workspace guards — is + # the root-guards job above; together they are the root `npm run validate`. + # + # Each suite runs once (#5759): the Node 24 leg leaves the tests to the + # `coverage` job, which runs the same suite instrumented, except on a draft, + # where `coverage` is skipped and this leg runs them. The Node 26 leg always + # runs them. The ready event skips this job: the draft's last push ran it. # # Each package is also validated on every Node line it supports (#5068): # 24, the oldest supported (#5168), through 26. The `node` axis multiplies @@ -86,7 +130,8 @@ jobs: # oldest supported, so an API only newer Node has cannot slip in unnoticed. validate: timeout-minutes: 15 - needs: [detect-packages] + needs: [detect-packages, draft] + if: github.event_name != 'pull_request' strategy: fail-fast: false matrix: @@ -109,20 +154,27 @@ jobs: - name: Install dependencies run: npm ci --workspace src/${{ matrix.package }} --include-workspace-root - - name: Validate package + - name: Check package + working-directory: src/${{ matrix.package }} + run: npm run check + + - name: Run tests + if: matrix.node != 24 || needs.draft.outputs.draft == 'true' working-directory: src/${{ matrix.package }} - run: npm run validate + run: npm test # The per-file coverage gate (#4854): one leg per TypeScript server, beside # `validate` rather than inside it, as the Inspector's CI does (inspector#2159). # Each server's `coverage` (`vitest run --coverage`) fails when any file is # below 90% on lines, statements, functions or branches; the thresholds live - # in the server's `vitest.config.ts`. It re-runs the suite instrumented, so it - # is kept out of the fast `test`/`validate` loop and given its own runner. - # `npm run local:gate` runs the same check through the root `npm run coverage`. + # in the server's `vitest.config.ts`. It runs the suite instrumented, so it + # is kept out of the fast `test`/`validate` loop and given its own runner, + # and it is the Node 24 run of the suite (see `validate`). Skipped on a + # draft (#5759). `npm run local:gate` runs the same `coverage` per server. coverage: timeout-minutes: 15 - needs: [detect-packages] + needs: [detect-packages, draft] + if: needs.draft.outputs.draft != 'true' strategy: fail-fast: false matrix: @@ -155,6 +207,9 @@ jobs: test-windows: timeout-minutes: 20 needs: [detect-packages] + # The draft's last push ran it; the ready event re-runs only what a + # draft skips. + if: github.event_name != 'pull_request' strategy: fail-fast: false matrix: @@ -183,9 +238,12 @@ jobs: # then one tool call. It is one job rather than a step in each matrix leg # because it is a single client driving all seven servers, and it lives in # this workflow because that client is Node. `npm run local:gate` runs the - # same `npm run smoke` as its last stage. + # same `npm run smoke`, for the servers its change touches. Skipped on a + # draft (#5759). smoke: name: Boot smoke + needs: [draft] + if: needs.draft.outputs.draft != 'true' timeout-minutes: 15 runs-on: ubuntu-latest steps: @@ -262,6 +320,7 @@ jobs: needs: [ dispatch-status-pending, + draft, root-guards, detect-packages, validate, diff --git a/AGENTS.md b/AGENTS.md index af364d3f75..1b4dbdcf66 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,7 +53,7 @@ servers/ ├── .claude/skills/ On-demand procedures (see the Skills index above) ├── .claude/settings.json The SessionStart hook that checks this session's instructions are current ├── .changeset/ Pending changesets for the TypeScript servers, and the changesets config -├── scripts/ The pre-push gate (gate-lease, smoke-servers, validate-py, coverage-py, interface-diff, image-smoke), its guards (verify-*), +├── scripts/ The pre-push gate (gate-lease, gate-servers, smoke-servers, validate-py, coverage-py, interface-diff, image-smoke), its guards (verify-*), │ the skills tooling, release tooling (npm-publish-guard, prepare-python-release, │ pack-and-verify, release-manifest, mcp-registry-entries, release-notes), and the issue-filing sweeps │ (dependency-refresh, dependabot-alerts, sdk-watch), and the session-start @@ -133,20 +133,37 @@ npm run local:gate **Run `npm run local:gate` before every push, and push only when it exits 0.** It runs every check CI runs, for both languages, in one command: `verify:install-fresh`, `verify:dco` (every commit since `origin/v2/main` is -signed off), the root `validate` (the guards, then each TypeScript -workspace's format check, lint, typecheck, build and tests), `coverage` (each -TypeScript workspace's per-file coverage gate), `validate:py` -(each Python server's locked sync, `ruff check`, `ruff format --check`, -pyright, pytest and build), `coverage:py` (each Python server's per-file -coverage gate), `verify:skills:cli`, `smoke` (every server booted over each -transport it implements), `interface-diff` (the MCP interface of each -server the change touches, diffed against the base it branched from), and -`image-smoke` (the Docker image of each server the change touches, built, -booted and stopped; it needs a running Docker daemon when a change touches -one). The stage-by-stage +signed off), `validate:guards` (the root guards), then for each server the +change touches each TypeScript workspace's `check` (format check, lint, +typecheck, build) and `coverage` (its tests, under the per-file coverage +gate), each Python server's `validate:py` without pytest (locked sync, +`ruff check`, `ruff format --check`, pyright, build) and `coverage:py` (its +tests, under the per-file coverage gate), and `smoke` (the server booted over +each transport it implements); then `verify:skills:cli`, `interface-diff` +(the MCP interface of each server the change touches, diffed against the base +it branched from), and `image-smoke` (the Docker image of each server the +change touches, built, booted and stopped; it needs a running Docker daemon +when a change touches one). The stage-by-stage reference, and what CI runs where, is [`docs/quality-gate.md`](./docs/quality-gate.md); diagnosing a red stage is the `pre-push-gate` skill. +- **A change confined to `src//` directories gates those servers + only; any file outside one gates every server** (#5759). The root guards + always run. The gate prints which servers it chose and why, and + `GATE_BASE=` scopes against another base (a stacked branch's parent). + The rule is in `scripts/lib/gate-scope.mjs`; never narrow it to a list of + repository-wide files. +- **Each test suite runs once per gate, under coverage.** The coverage run + fails on any failed test, so a plain pass beside it adds time and catches + nothing. A workspace's `validate` is `check` and then `test`; the gate and + CI's non-draft runs use `check` and `coverage`. +- **A draft PR needs less until it is marked ready.** While it is a draft, a + push needs `npm run local:gate:draft` (exit 0): `verify:dco` and the touched + servers' full `validate` / `validate:py`. **Marking it ready for review + needs a full `npm run local:gate` (exit 0) first**, and every push after + that needs the full gate. In CI a draft skips coverage, the boot smoke, the + interface diff and the image smoke; `ready_for_review` runs them. + - **`npm run validate` and the per-package commands above are the inner loop, not a substitute.** They skip the other language, the pinned skills validator, the boot smoke, the interface diff and the image smoke. @@ -674,7 +691,9 @@ here. TypeScript server) and `npm run coverage:py` (`-- ` for one) run the suites instrumented and enforce the gate; `test`, `validate` and `uv run pytest` stay fast and do not. CI and `npm run local:gate` run each - as a stage of its own. + as a stage of its own, and it is the only run of the suite there: neither + runs the plain suite beside it (#5759), except CI on a draft PR, which + skips coverage and runs the plain suite instead. - **Test at the protocol level where you can**: drive the server through an MCP client over an in-memory transport and assert on what comes back, rather than only calling internal functions. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 99464a5090..f87b8bbb12 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -150,11 +150,13 @@ The rules for maintainers and the agents working for them are in [`AGENTS.md`](./AGENTS.md), and the procedures are in the skills it indexes. Before pushing, run `npm run format` at the repository root and then **`npm run local:gate`**, which runs every check CI runs for both languages: -the repo-wide guards, each TypeScript server's `validate` (format check, lint -where a warning fails like an error, typecheck, build, tests) and per-file -coverage gate (`coverage`), each Python -server's `validate:py` chain and per-file coverage gate (`coverage:py`), the -skills validator, and a boot smoke of every server. [`docs/quality-gate.md`](./docs/quality-gate.md) describes each stage. +the repo-wide guards, each TypeScript server's checks (format check, lint +where a warning fails like an error, typecheck, build) and its tests under the +per-file coverage gate (`coverage`), each Python server's `validate:py` chain +and its tests under the per-file coverage gate (`coverage:py`), the skills +validator, and a boot smoke of each server. A change confined to one server's +directory runs the per-server checks for that server only. +[`docs/quality-gate.md`](./docs/quality-gate.md) describes each stage. While iterating, `npm run validate -w src/` checks a single TypeScript server and `npm run validate:py -- ` a single Python one; neither replaces the gate. diff --git a/docs/ai-software-factory.md b/docs/ai-software-factory.md index 75f4cc4278..5df064e440 100644 --- a/docs/ai-software-factory.md +++ b/docs/ai-software-factory.md @@ -140,7 +140,10 @@ the verdict. It runs the fresh-install check, the DCO check, the root guards, each TypeScript workspace's format, lint, typecheck, build and tests, each Python server's locked sync, ruff, pyright, pytest and build, both languages' per-file coverage gates, the pinned skills validator, and a boot smoke of -every server over each transport it implements. Among its rules: +each server over each transport it implements. The per-server stages run for +the servers a change touches, and for every server when it touches anything +outside a server directory; each suite runs once, under coverage. Among its +rules: - **Per-file coverage of at least 90**: on all four dimensions in TypeScript, and on lines and branches in Python. A genuinely unreachable branch is diff --git a/docs/quality-gate.md b/docs/quality-gate.md index 07fbab17d1..556f270bc3 100644 --- a/docs/quality-gate.md +++ b/docs/quality-gate.md @@ -9,15 +9,16 @@ out; everything else points here. ## Two tiers, one set of checks -| Tier | Command | Where | When | -| ------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------- | -| Inner loop | `npm run validate -w src/`, `npm run validate:py -- ` | Your machine | While iterating on one server | -| Pre-push gate | `npm run local:gate` | Your machine, under a lease | Before every push | -| CI | `.github/workflows/typescript.yml`, `python.yml`, `mcp-interface-diff.yml`, `image-smoke.yml`; `dco.yml`; `main-source.yml` | GitHub, on every push and pull request (`mcp-interface-diff.yml` diffs, and `image-smoke.yml` builds, only the servers the change touches); `dco.yml` on pull requests only; `main-source.yml` on pull requests into `main` only, and not mirrored by a gate stage, since no local push targets `main` | Before merge | +| Tier | Command | Where | When | +| ------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | +| Inner loop | `npm run validate -w src/`, `npm run validate:py -- ` | Your machine | While iterating on one server | +| Draft gate | `npm run local:gate:draft` | Your machine, under the same lease | Before a push to a draft PR | +| Pre-push gate | `npm run local:gate` | Your machine, under a lease | Before every other push | +| CI | `.github/workflows/typescript.yml`, `python.yml`, `mcp-interface-diff.yml`, `image-smoke.yml`; `dco.yml`; `main-source.yml` | GitHub, on every push and pull request (`mcp-interface-diff.yml` diffs, and `image-smoke.yml` builds, only the servers the change touches; a draft PR skips the coverage gates, the boot smoke, the interface diff and the image smoke); `dco.yml` on pull requests only; `main-source.yml` on pull requests into `main` only, and not mirrored by a gate stage, since no local push targets `main` | Before merge | **`npm run local:gate` runs every check CI runs.** CI splits the same checks into parallel jobs on a fresh install; the gate runs them in sequence on your -checkout. So a green gate means every check CI applies has already passed on +checkout, for the servers your change touches ([scope](#which-servers-the-gate-runs)). So a green gate means every check CI applies has already passed on your machine. It is the strongest predictor of a green CI there is here, though not a proof: CI runs on Linux, on a fresh `npm ci`, with Node 24 (the oldest supported) and each Python server's pinned interpreter, and `typescript.yml`'s @@ -44,23 +45,95 @@ never a substitute for the gate. `local:gate` is exactly `node scripts/gate-lease.mjs npm run local:gate:stages`: the [lease](#the-gate-lease) around the stages, and nothing else. The stages run -in this order, and the first failure stops the run. - -| # | Stage | What it checks | CI counterpart | -| --- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| 1 | `verify:install-fresh` | Every package in `node_modules` is at the version `package-lock.json` records, and every `package.json` declares what the lockfile says it does | None needed: CI installs with `npm ci` | -| 2 | `verify:dco` | Every commit in `origin/v2/main..HEAD` carries a `Signed-off-by:` trailer matching its author or committer (merge and bot commits exempt) | `dco.yml` → **DCO signoff**, over the pull request's `base.sha..head.sha` | -| 3 | `validate` → `validate:guards` | The root guards, listed [below](#the-root-guards) | `typescript.yml` → **Root guards** | -| 4 | `validate` → each workspace's `validate` | Per TypeScript server: `format:check`, `lint` (`--max-warnings 0`), `typecheck`, `build`, `test` | `typescript.yml` → **Validate \ (Node \)** (one leg per server per Node: 24 and 26, in parallel) | -| 5 | `coverage` | Per TypeScript server: `vitest run --coverage`, failing when any file is below 90% on lines, statements, functions or branches | `typescript.yml` → **Coverage \** (one leg each) | -| 6 | `validate:py` | Per Python server: `uv sync --locked`, `ruff check`, `ruff format --check`, `pyright`, `pytest`, `uv build` | `python.yml` → **Test \** (one leg each) | -| 7 | `coverage:py` | Per Python server: `uv sync --locked`, then `uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json`; then **every file** in `coverage.json` must reach **90% on lines and 90% on branches** | `python.yml` → **Coverage \** (one leg each) | -| 8 | `verify:skills:cli` | `claude plugin validate` on `.claude/skills`, at the pinned CLI version | `typescript.yml` → **Root guards** | -| 9 | `smoke` | Every server boots over each transport it implements and answers one tool call | `typescript.yml` → **Boot smoke** | -| 10 | `interface-diff` | For each server the change touches, its MCP interface (capabilities, tools, prompts, resources, resource templates) in this checkout's build, diffed against the same server built from the base. It fails only when a diff cannot run; a changed interface is reported, not failed | `mcp-interface-diff.yml` → **Choose the servers to diff**, then **Diff \** (one leg each, and a PR comment each) | -| 11 | `image-smoke` | For each server the change touches, its Docker image: it builds, a client lists its tools over `docker run -i`, and `docker stop` ends it without killing it, `memory` leaving no lock file behind | `image-smoke.yml` → **Choose the images to build**, then **Image \** (one leg each) | - -Notes on the stages: +in this order, and the first failure stops the run. Stages 4 to 8 are the +**per-server stages**: `scripts/gate-servers.mjs` runs them, once, for the +servers the change touches ([below](#which-servers-the-gate-runs)), and prints +the command and the time of each. + +| # | Stage | What it checks | CI counterpart | +| --- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| 1 | `verify:install-fresh` | Every package in `node_modules` is at the version `package-lock.json` records, and every `package.json` declares what the lockfile says it does | None needed: CI installs with `npm ci` | +| 2 | `verify:dco` | Every commit in `origin/v2/main..HEAD` carries a `Signed-off-by:` trailer matching its author or committer (merge and bot commits exempt) | `dco.yml` → **DCO signoff**, over the pull request's `base.sha..head.sha` | +| 3 | `validate:guards` | The root guards, listed [below](#the-root-guards) | `typescript.yml` → **Root guards** | +| 4 | `check` (per TypeScript server) | `format:check`, `lint` (`--max-warnings 0`), `typecheck`, `build`: the workspace's `validate` without its tests | `typescript.yml` → **Validate \ (Node \)** (one leg per server per Node: 24 and 26, in parallel) | +| 5 | `coverage` (per TypeScript server) | The test suite, once, under `vitest run --coverage`, failing on any failed test and when any file is below 90% on lines, statements, functions or branches | `typescript.yml` → **Coverage \** (one leg each; on a draft, the Node 24 **Validate** leg runs the plain suite instead) | +| 6 | `validate:py -- --no-pytest` | Per Python server: `uv sync --locked`, `ruff check`, `ruff format --check`, `pyright`, `uv build` | `python.yml` → **Test \** (one leg each; on a draft it also runs `pytest`) | +| 7 | `coverage:py` | Per Python server: `uv sync --locked`, then the suite, once, under `uv run --frozen pytest --cov --cov-report=term-missing --cov-report=json`; then **every file** in `coverage.json` must reach **90% on lines and 90% on branches** | `python.yml` → **Coverage \** (one leg each) | +| 8 | `smoke` | Each server boots over each transport it implements and answers one tool call | `typescript.yml` → **Boot smoke** (every server) | +| 9 | `verify:skills:cli` | `claude plugin validate` on `.claude/skills`, at the pinned CLI version | `typescript.yml` → **Root guards** | +| 10 | `interface-diff` | For each server the change touches, its MCP interface (capabilities, tools, prompts, resources, resource templates) in this checkout's build, diffed against the same server built from the base. It fails only when a diff cannot run; a changed interface is reported, not failed | `mcp-interface-diff.yml` → **Choose the servers to diff**, then **Diff \** (one leg each, and a PR comment each) | +| 11 | `image-smoke` | For each server the change touches, its Docker image: it builds, a client lists its tools over `docker run -i`, and `docker stop` ends it without killing it, `memory` leaving no lock file behind | `image-smoke.yml` → **Choose the images to build**, then **Image \** (one leg each) | + +### Which servers the gate runs + +The per-server stages (4 to 8) run for the servers the change touches, decided +by `scripts/lib/gate-scope.mjs` from every file changed since the merge base +with `origin/v2/main`, committed or not (#5759): + +- **Every changed file is under `src//`** for one or more servers: + those servers only. A pending changeset (`.changeset/.md`) does not + widen the scope; it describes a server the change already touches. +- **Any other file changed**: every server. That is anything outside a server + directory: a root manifest or lockfile, `scripts/`, a workflow, + `.changeset/config.json`, the root TypeScript, lint or format configuration, + `AGENTS.md`, a skill, a doc. The rule is deliberately "outside a server + directory" rather than a list of repository-wide files, which would go stale + silently. +- **No server selected** (nothing changed, as when the gate checks `v2/main` + itself, or only changesets): every server, rather than nothing. + +The gate prints its decision before running anything: + +``` +[gate] base 002bcceed159 +[gate] servers: memory — every changed file is under `src/memory/` +``` + +`GATE_BASE= npm run local:gate` scopes against another commit, such as +a stacked branch's parent; stages 10 and 11 read it too, so every stage +compares against the same base. Stages 1 to 3 and 9 are not scoped: they check the +repository, and run every time. Stages 10 and 11 make their own, finer +selection (below), so a change to a root file runs every per-server stage but +diffs and builds only the servers it can reach. + +### Each suite runs once + +Each test suite runs once per gate, under coverage (#5759). A coverage run +executes the same tests and fails on any failed test, so the plain `vitest run` +and `pytest` passes that used to run before it caught nothing more. Stage 4 is +each workspace's `check` (its `validate` is `check` and then `test`), and +stage 6 is `validate:py` with `--no-pytest`. Outside the gate nothing changes: +`npm test`, `uv run pytest`, `npm run validate -w src/` and +`npm run validate:py -- ` still run the plain suite, fast, as the +inner loop. + +CI does the same: the **Coverage** legs run each suite instrumented, so the +Node 24 **Validate** leg and the Python **Test** leg leave the tests to them. +The Node 26 leg always runs the suite, and the Windows legs run it on their +own OS. + +### Draft pull requests + +A draft PR does not need the full gate on every push (#5759): + +- **While a PR is a draft**, a push needs `npm run local:gate:draft`: + `verify:dco`, then the touched servers' full `validate` (format, lint, + typecheck, build and tests) and `validate:py`, with no coverage and no + smoke. It runs under the same lease as `local:gate`. +- **Marking it ready for review** needs a full `npm run local:gate`, exit 0, + first. +- **After that, every push** needs `npm run local:gate` as usual. + +CI follows the same line. In `typescript.yml` and `python.yml`, a `draft` job +looks up whether the pushed branch has an open draft PR; if it does, the +**Coverage** legs and the **Boot smoke** are skipped, and the Node 24 +**Validate** leg and the Python **Test** legs run the plain suite in their +place. `mcp-interface-diff.yml` and `image-smoke.yml` skip a draft's runs +entirely. Marking the PR ready (`ready_for_review`) runs exactly what was +skipped, and every later push runs everything. A branch with no open PR, a +dispatch, and a failed lookup all count as not a draft. + +### Notes on the stages - **`verify:install-fresh` is first on purpose.** The gate never runs `npm ci`, so a checkout whose `node_modules` predates a pulled dependency @@ -74,17 +147,17 @@ Notes on the stages: branch it also checks the lower branch's commits (`npm run verify:dco -- --base ` checks a range of your choosing). A failure names each unsigned commit and the `git rebase --signoff` repair. -- **`coverage` is the TypeScript test suite run a second time, instrumented.** - It is a separate command from `test` and `validate` so the inner loop stays - fast, and a separate CI job so it gets its own runner. The 90% per-file - thresholds are set in each server's `vitest.config.ts` - (`coverage.thresholds`, `perFile: true`), not on the command line, so - `npm run coverage -w src/` enforces exactly what the gate does. The - root `npm run coverage` runs every workspace even after one fails, and exits - non-zero if any did, so the failing workspace's report is not necessarily - the last thing printed. -- **`validate:py` carries on after a failing server**, so one run reports all - three verdicts, and exits non-zero if any failed. Within a server it stops +- **`coverage` is the TypeScript test suite, instrumented.** It is a separate + command from `test` and `validate` so the inner loop stays fast, and a + separate CI job so it gets its own runner. The 90% per-file thresholds are + set in each server's `vitest.config.ts` (`coverage.thresholds`, + `perFile: true`), not on the command line, so + `npm run coverage -w src/` enforces exactly what the gate does. + Over several servers, npm runs every workspace named even after one fails, + and exits non-zero if any did, so the failing workspace's report is not + necessarily the last thing printed. +- **`validate:py` carries on after a failing server**, so one run reports + every verdict, and exits non-zero if any failed. Within a server it stops at the first failing step. - **`coverage:py` is per file, not a total.** coverage.py's own `fail_under` compares the sum across a package, so one well-tested module can carry an @@ -94,8 +167,7 @@ Notes on the stages: 100% on them. What is measured is each server's `[tool.coverage.run]` (`branch = true`, `source` set to its package). Like `validate:py` it carries on after a failing server, and its summary names every file and dimension - below 90. It runs after `validate:py`, so a failing test has already been - reported on the fast, uninstrumented run. + below 90. A failing test fails it, before the per-file check is read. - **`verify:skills:cli` needs the network** when the pinned Claude Code CLI is not the one installed: it fetches it with `npx`. `validate:py` needs it too when a server's environment is missing or behind its lockfile, since @@ -111,14 +183,14 @@ Notes on the stages: `everything`. The servers are given nothing outside the machine to talk to and none of your files: `fetch` is pointed at a page the smoke serves on the loopback interface, and the HTTP transports listen on a free port rather - than the default 3001. It runs after `validate` and `validate:py` because it + than the default 3001. It runs after `check` and `validate:py` because it needs the build and each Python server's synced environment; it creates neither. - **`interface-diff` compares against the merge-base with `origin/v2/main`** locally (`-- --base ` names another), and against the PR's base, the commit before the push, or the previous release's tag in CI. It builds the base from an export of that commit under `node_modules/.cache/` and removes - it afterwards; the head is the build `validate` made (and, for a Python + it afterwards; the head is the build `check` made (and, for a Python server, the environment `validate:py` synced). It drives the `mcp-server-diff` CLI, an exact-pinned root devDependency, which probes with the 2026-07-28 `server/discover` first and falls back to the `initialize` @@ -167,16 +239,16 @@ Notes on the stages: `npm run validate:guards` is the part of `validate` that no per-server check covers: the repo-wide tooling and the guards that keep the gate itself honest. -| Guard | Fails when | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `format:check:root`, `lint:root` | A file under `scripts/` or a root config is unformatted or has a lint finding | -| `verify:format-coverage` | A tracked source file is covered by no `format:check` glob | -| `verify:skills` | A skill's frontmatter does not parse, declares no invocation mode, lacks eval cases, or the listing exceeds its budget; or a skills gate has come unwired | -| `verify:typecheck-coverage` | A tracked TypeScript file lands in no `tsc` program | -| `verify:dep-lockstep` | Two workspaces declare different ranges of a shared toolchain package | -| `verify:no-test-retries` | A test declares a retry (Vitest's `retry`, a pytest rerun plugin or marker) | -| `verify:action-pins` | A job that holds a credential (`id-token: write`, `packages: write`, a secret other than `GITHUB_TOKEN`), or whose artifact such a job downloads, or whose outputs such a job reads (`detect-packages` in `release.yml`), uses an action that is not pinned to a commit SHA with a `# vX.Y.Z` comment | -| `test:scripts` | A guard's own unit tests fail. These include the workflow guard: a workflow invokes a `local:*` script, a CI job has no `timeout-minutes`, or `local:gate` is no longer exactly the lease wrapper around stages that include every check above | +| Guard | Fails when | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `format:check:root`, `lint:root` | A file under `scripts/` or a root config is unformatted or has a lint finding | +| `verify:format-coverage` | A tracked source file is covered by no `format:check` glob | +| `verify:skills` | A skill's frontmatter does not parse, declares no invocation mode, lacks eval cases, or the listing exceeds its budget; or a skills gate has come unwired | +| `verify:typecheck-coverage` | A tracked TypeScript file lands in no `tsc` program | +| `verify:dep-lockstep` | Two workspaces declare different ranges of a shared toolchain package | +| `verify:no-test-retries` | A test declares a retry (Vitest's `retry`, a pytest rerun plugin or marker) | +| `verify:action-pins` | A job that holds a credential (`id-token: write`, `packages: write`, a secret other than `GITHUB_TOKEN`), or whose artifact such a job downloads, or whose outputs such a job reads (`detect-packages` in `release.yml`), uses an action that is not pinned to a commit SHA with a `# vX.Y.Z` comment | +| `test:scripts` | A guard's own unit tests fail. These include the workflow guard: a workflow invokes a `local:*` script, a CI job has no `timeout-minutes`, or `local:gate` is no longer exactly the lease wrapper around stages that include every check above (the per-server stages through `scripts/gate-servers.mjs`) | ## What is in neither tier @@ -185,7 +257,8 @@ covers: the repo-wide tooling and the guards that keep the gate itself honest. or editing a description ([`skill-authoring.md`](./skill-authoring.md)). - **Coverage is not in this list: it is in both tiers.** The per-file gates are stages above: `coverage` (stage 5) for the TypeScript servers and `coverage:py` (stage 7) for the - Python servers, each with its own CI job. They are also the coverage + Python servers, each with its own CI job, and in both tiers they are where + the suite runs ([once](#each-suite-runs-once)). They are also the coverage commands: `npm run coverage -w src/` and `npm run coverage:py -- ` for one server. They stay out of `validate`, `validate:py` and the plain `uv run pytest` loop on purpose, @@ -218,8 +291,9 @@ cannot go stale quietly, so the script tests hold it in place: - **A check added to CI is added to `local:gate:stages` in the same change.** `scripts/lib/workflow-gate.test.mjs` derives this from the workflows: every npm script and every `scripts/*.mjs` that a push or pull-request workflow - runs must be reached by `local:gate`, so a check added to CI alone fails the - script tests. It reads script names, so a check written as a bare command in + runs must be reached by `local:gate`, either through its npm chain or as a + step `scripts/gate-servers.mjs` runs for the full scope (`gatePlan`), so a + check added to CI alone fails the script tests. It reads script names, so a check written as a bare command in a workflow step (not behind an npm script) is outside what it can see; put new checks behind a script. - **No workflow invokes a `local:*` script.** The prefix means local-only. CI @@ -267,8 +341,8 @@ gate-lease: pid 12345 in /path/to/other-worktree, running for 40s holds the gate `$XDG_RUNTIME_DIR` or the system temp directory by default, never inside a worktree. -The lease covers `local:gate` only. A bare `npm run validate` or `npm test` in -another session does not take it. +The lease covers `local:gate` and `local:gate:draft` only. A bare +`npm run validate` or `npm test` in another session does not take it. ### Lease slots diff --git a/package.json b/package.json index b0e081e0b9..79922e8ba3 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,9 @@ "pack:verify": "node scripts/pack-and-verify.mjs", "release:notes": "node scripts/release-notes.mjs", "local:gate": "node scripts/gate-lease.mjs npm run local:gate:stages", - "local:gate:stages": "npm run verify:install-fresh && npm run verify:dco && npm run validate && npm run coverage && npm run validate:py && npm run coverage:py && npm run verify:skills:cli && npm run smoke && npm run interface-diff && npm run image-smoke" + "local:gate:stages": "npm run verify:install-fresh && npm run verify:dco && npm run validate:guards && node scripts/gate-servers.mjs && npm run verify:skills:cli && npm run interface-diff && npm run image-smoke", + "local:gate:draft": "node scripts/gate-lease.mjs npm run local:gate:draft:stages", + "local:gate:draft:stages": "npm run verify:dco && node scripts/gate-servers.mjs --draft" }, "dependencies": { "@modelcontextprotocol/server-everything": "*", diff --git a/scripts/gate-servers.mjs b/scripts/gate-servers.mjs new file mode 100644 index 0000000000..00bf25ec5c --- /dev/null +++ b/scripts/gate-servers.mjs @@ -0,0 +1,181 @@ +#!/usr/bin/env node +/** + * The pre-push gate's per-server stages, run once for the servers a change + * touches (#5759). + * + * node scripts/gate-servers.mjs # a stage of `npm run local:gate` + * node scripts/gate-servers.mjs --draft # a stage of `npm run local:gate:draft` + * GATE_BASE= npm run local:gate # scope against , not origin/v2/main + * + * Two things the gate used to do that this replaces: + * + * - It ran every test suite twice: each TypeScript workspace's `validate` + * ends in `vitest run`, and the gate then ran `vitest run --coverage` over + * the same suites; likewise `pytest` in `validate:py` and `pytest --cov` + * in `coverage:py`. A coverage run executes the same tests and fails on any + * test failure, so the plain pass caught nothing more. Here each suite runs + * once, under coverage: the workspace `check` (its `validate` without the + * tests) and then `coverage`; `validate:py --no-pytest` and then + * `coverage:py`. + * - It ran all seven servers whatever changed. The scope is decided by + * `lib/gate-scope.mjs` from the files changed since the merge base with + * `origin/v2/main` (or `GATE_BASE`: a stacked branch's base, say), and the + * decision and its reason are printed before anything runs. + * + * `--draft` is the lighter gate a push to a draft pull request needs: the + * touched servers' full `validate` (format, lint, typecheck, build, tests) + * and `validate:py`, with no coverage and no smoke. Marking the PR ready for + * review needs a full `npm run local:gate` first (AGENTS.md, **Before + * pushing**). + * + * Each step is an `npm run` of a root or workspace script, never the script's + * body copied here, so a step and its CI job cannot drift. The steps run in + * order and stop at the first failure, as the `&&` chain they replace did. + */ +import { spawnSync } from "node:child_process"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { changesSince, resolveBase } from "./interface-diff.mjs"; +import { chooseScope } from "./lib/gate-scope.mjs"; +import { winShellArgs } from "./lib/win-shell-args.mjs"; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + "..", +); + +/** + * The commands a scope needs, in the order they run. + * + * @param {{ servers: { name: string, language: string }[] }} scope + * @param {{ draft?: boolean }} [options] + * @returns {{ name: string, argv: string[] }[]} + */ +export function gatePlan(scope, { draft = false } = {}) { + const names = (language) => + scope.servers.filter((s) => s.language === language).map((s) => s.name); + const ts = names("ts"); + const py = names("py"); + const workspaces = ts.flatMap((name) => ["-w", `src/${name}`]); + const npm = (...args) => ["npm", "run", ...args]; + const steps = []; + + if (draft) { + if (ts.length > 0) + steps.push({ name: "validate", argv: npm("validate", ...workspaces) }); + if (py.length > 0) + steps.push({ + name: "validate:py", + argv: npm("validate:py", "--", ...py), + }); + return steps; + } + + if (ts.length > 0) { + steps.push({ name: "check", argv: npm("check", ...workspaces) }); + steps.push({ name: "coverage", argv: npm("coverage", ...workspaces) }); + } + if (py.length > 0) { + steps.push({ + name: "validate:py", + argv: npm("validate:py", "--", "--no-pytest", ...py), + }); + steps.push({ name: "coverage:py", argv: npm("coverage:py", "--", ...py) }); + } + if (scope.servers.length > 0) + steps.push({ + name: "smoke", + argv: npm("smoke", "--", ...scope.servers.map((s) => s.name)), + }); + return steps; +} + +/** Spawn one step with the terminal attached; its exit status, or 1. */ +function runStep(argv) { + const [command, ...args] = argv; + // npm is a `.cmd` shim on Windows, which only a shell can start. + const shell = process.platform === "win32"; + const res = spawnSync(command, shell ? winShellArgs(args) : args, { + cwd: repoRoot, + stdio: "inherit", + shell, + }); + if (res.error) { + console.error(`[gate] ${command}: ${res.error.message}`); + return 1; + } + return res.status ?? 1; +} + +/** Parse the command line: `--draft`, and nothing else. */ +export function parseArgs(argv) { + const unknown = argv.filter((a) => a !== "--draft"); + if (unknown.length > 0) + return { error: `unknown argument(s): ${unknown.join(" ")}` }; + return { draft: argv.includes("--draft") }; +} + +/** + * @param {string[]} [argv] + * @param {{ + * env?: Record, + * changes?: (base: string) => { changedFiles: string[] }, + * base?: (ref: string | null, env: Record) => string, + * run?: (argv: string[]) => number, + * log?: (line: string) => void, + * now?: () => number, + * }} [deps] + * @returns {number} the exit code + */ +export function main(argv = process.argv.slice(2), deps = {}) { + const { + env = process.env, + changes = changesSince, + base = resolveBase, + run = runStep, + log = console.log, + now = Date.now, + } = deps; + + const opts = parseArgs(argv); + if ("error" in opts) { + console.error(`[gate] ${opts.error}`); + return 2; + } + + let scope; + let sha; + try { + sha = base(null, env); + scope = chooseScope(changes(sha).changedFiles); + } catch (err) { + console.error( + `[gate] could not decide which servers to gate: ${err.message}`, + ); + return 2; + } + + const label = scope.all + ? "every server" + : scope.servers.map((s) => s.name).join(", "); + log( + `[gate] base ${sha.slice(0, 12)}${env.GATE_BASE ? ` (GATE_BASE=${env.GATE_BASE})` : ""}`, + ); + log(`[gate] servers: ${label} — ${scope.reason}`); + + for (const step of gatePlan(scope, opts)) { + log(`\n[gate] ${step.name}: ${step.argv.join(" ")}`); + const started = now(); + const status = run(step.argv); + const seconds = Math.round((now() - started) / 1000); + if (status !== 0) { + log(`[gate] ${step.name} FAILED (exit ${status}, ${seconds}s)`); + return status; + } + log(`[gate] ${step.name} passed (${seconds}s)`); + } + return 0; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) + process.exitCode = main(); diff --git a/scripts/gate-servers.test.mjs b/scripts/gate-servers.test.mjs new file mode 100644 index 0000000000..e066c54fae --- /dev/null +++ b/scripts/gate-servers.test.mjs @@ -0,0 +1,165 @@ +// Tests for the gate's per-server stages (#5759): which commands a scope +// runs, that each suite runs once (under coverage) in the full gate, that the +// draft gate runs no coverage or smoke, and that the scope and its reason are +// printed before anything runs. Commands are faked; nothing is spawned. +// Run via `npm run test:scripts`. + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { gatePlan, main, parseArgs } from "./gate-servers.mjs"; +import { SERVERS } from "./lib/interface-diff-servers.mjs"; + +const only = (...names) => ({ + servers: SERVERS.filter((s) => names.includes(s.name)), +}); +const every = { servers: SERVERS }; +const commands = (plan) => plan.map((s) => s.argv.join(" ")); + +describe("gatePlan", () => { + it("runs a TypeScript server's checks, then its suite once under coverage, then the smoke", () => { + assert.deepEqual(commands(gatePlan(only("memory"))), [ + "npm run check -w src/memory", + "npm run coverage -w src/memory", + "npm run smoke -- memory", + ]); + }); + + it("runs a Python server's chain without pytest, then pytest under coverage", () => { + assert.deepEqual(commands(gatePlan(only("time"))), [ + "npm run validate:py -- --no-pytest time", + "npm run coverage:py -- time", + "npm run smoke -- time", + ]); + }); + + it("covers every server in the full scope, and runs no plain test pass", () => { + const plan = commands(gatePlan(every)); + assert.deepEqual(plan, [ + "npm run check -w src/everything -w src/filesystem -w src/memory -w src/sequentialthinking", + "npm run coverage -w src/everything -w src/filesystem -w src/memory -w src/sequentialthinking", + "npm run validate:py -- --no-pytest fetch git time", + "npm run coverage:py -- fetch git time", + "npm run smoke -- everything filesystem memory sequentialthinking fetch git time", + ]); + // `validate` (TS) ends in `npm run test`, and plain `validate:py` runs + // pytest: neither may sit beside a coverage run of the same suite. + assert.ok(!plan.some((c) => /npm run validate(?: |$)/.test(c))); + assert.ok(!plan.some((c) => /validate:py -- (?!--no-pytest)/.test(c))); + }); + + it("runs only each touched server's validate in the draft gate", () => { + assert.deepEqual( + commands(gatePlan(only("memory", "git"), { draft: true })), + ["npm run validate -w src/memory", "npm run validate:py -- git"], + ); + }); + + it("leaves out a language with no server in scope", () => { + assert.deepEqual( + gatePlan(only("fetch"), { draft: true }).map((s) => s.name), + ["validate:py"], + ); + assert.deepEqual( + gatePlan(only("memory"), { draft: true }).map((s) => s.name), + ["validate"], + ); + }); +}); + +describe("parseArgs", () => { + it("takes --draft and refuses anything else", () => { + assert.deepEqual(parseArgs([]), { draft: false }); + assert.deepEqual(parseArgs(["--draft"]), { draft: true }); + assert.match(parseArgs(["--all"]).error, /--all/); + assert.match(parseArgs(["memory"]).error, /memory/); + }); +}); + +describe("main", () => { + const fake = (changedFiles, statuses = {}) => { + const lines = []; + const ran = []; + const deps = { + env: {}, + base: () => "0123456789abcdef0123", + changes: () => ({ changedFiles }), + run: (argv) => { + ran.push(argv.join(" ")); + return statuses[argv[2]] ?? 0; + }, + log: (line) => lines.push(line), + now: () => 0, + }; + return { deps, lines, ran }; + }; + + it("prints the servers it chose and why, then runs their plan", () => { + const { deps, lines, ran } = fake(["src/memory/index.ts"]); + assert.equal(main([], deps), 0); + assert.ok( + lines.includes( + "[gate] servers: memory — every changed file is under `src/memory/`", + ), + lines.join("\n"), + ); + assert.deepEqual(ran, commands(gatePlan(only("memory")))); + }); + + it("says when it gates every server", () => { + const { deps, lines } = fake(["package.json"]); + assert.equal(main([], deps), 0); + assert.ok( + lines.some((l) => + l.startsWith( + "[gate] servers: every server — `package.json` is outside", + ), + ), + ); + }); + + it("stops at the first failing step and returns its status", () => { + const { deps, ran, lines } = fake(["src/memory/index.ts"], { coverage: 3 }); + assert.equal(main([], deps), 3); + assert.deepEqual(ran, [ + "npm run check -w src/memory", + "npm run coverage -w src/memory", + ]); + assert.ok(lines.some((l) => /coverage FAILED \(exit 3/.test(l))); + }); + + it("scopes against GATE_BASE when it is set", () => { + const { deps, lines } = fake(["src/memory/index.ts"]); + let asked; + deps.env = { GATE_BASE: "my-parent" }; + deps.base = (ref, env) => { + asked = ref ?? env.GATE_BASE; + return "fedcba9876543210"; + }; + assert.equal(main([], deps), 0); + assert.equal(asked, "my-parent"); + assert.ok(lines.some((l) => l.includes("(GATE_BASE=my-parent)"))); + }); + + it("runs the draft plan with --draft", () => { + const { deps, ran } = fake(["src/memory/index.ts"]); + assert.equal(main(["--draft"], deps), 0); + assert.deepEqual(ran, ["npm run validate -w src/memory"]); + }); + + it("exits 2 when the base cannot be resolved, running nothing", (t) => { + t.mock.method(console, "error", () => {}); + const { deps, ran } = fake([]); + deps.base = () => { + throw new Error("origin/v2/main is not available"); + }; + assert.equal(main([], deps), 2); + assert.deepEqual(ran, []); + }); + + it("exits 2 on an unknown argument, running nothing", (t) => { + t.mock.method(console, "error", () => {}); + const { deps, ran } = fake([]); + assert.equal(main(["--al"], deps), 2); + assert.deepEqual(ran, []); + }); +}); diff --git a/scripts/image-smoke.mjs b/scripts/image-smoke.mjs index 5b56df1be9..d28b04b21b 100644 --- a/scripts/image-smoke.mjs +++ b/scripts/image-smoke.mjs @@ -54,6 +54,7 @@ // Usage: // npm run image-smoke # base: merge-base with origin/v2/main // npm run image-smoke -- --base # any commit, tag or branch +// GATE_BASE= npm run image-smoke # the same, as the gate passes it // npm run image-smoke -- --server # this image, changed or not (repeatable) // npm run image-smoke -- --all # every image, changed or not // npm run image-smoke -- --list # print the selected images as JSON; build nothing diff --git a/scripts/interface-diff.mjs b/scripts/interface-diff.mjs index 1575347c30..c80662d68d 100644 --- a/scripts/interface-diff.mjs +++ b/scripts/interface-diff.mjs @@ -56,6 +56,7 @@ // Usage: // npm run interface-diff # base: merge-base with origin/v2/main // npm run interface-diff -- --base # any commit, tag or branch +// GATE_BASE= npm run interface-diff # the same, as the gate passes it // npm run interface-diff -- --server # this server, changed or not (repeatable) // npm run interface-diff -- --all # every server, changed or not // npm run interface-diff -- --list # print the selected servers as JSON; diff nothing @@ -326,10 +327,17 @@ function run(command, args, cwd, env) { const git = (...args) => run("git", args, repoRoot).trim(); /** - * The commit to compare against, as a full SHA. Exported for the image smoke - * (`scripts/image-smoke.mjs`), which selects from the same change. + * The commit to compare against, as a full SHA: `base` (`--base`) if given, + * else `GATE_BASE` from the environment, else the merge base with + * `origin/v2/main`. Exported for the image smoke (`scripts/image-smoke.mjs`) + * and the gate's per-server stages (`scripts/gate-servers.mjs`), which select + * from the same change. `GATE_BASE` is read here, not by each caller, so that + * one `GATE_BASE= npm run local:gate` scopes every stage against the same + * base (#5759): a stage that scoped against `origin/v2/main` instead could + * select a server the per-server stages never set up. */ -export function resolveBase(base) { +export function resolveBase(base, env = process.env) { + base ||= env.GATE_BASE || null; if (base) return git("rev-parse", "--verify", `${base}^{commit}`); try { git("rev-parse", "--verify", DEFAULT_BASE_BRANCH); diff --git a/scripts/interface-diff.test.mjs b/scripts/interface-diff.test.mjs index 7b158e71a8..6864bf2088 100644 --- a/scripts/interface-diff.test.mjs +++ b/scripts/interface-diff.test.mjs @@ -7,6 +7,7 @@ // repeated here; which servers a change selects is // `lib/interface-diff-servers.test.mjs`. Run via `npm run test:scripts`. +import { execFileSync } from "node:child_process"; import { test } from "node:test"; import assert from "node:assert/strict"; import { @@ -16,6 +17,7 @@ import { main, parseArgs, renderReport, + resolveBase, startCommand, } from "./interface-diff.mjs"; import { SERVERS } from "./lib/interface-diff-servers.mjs"; @@ -226,3 +228,18 @@ test("the report leads with the verdict and shows each changed part", () => { /could not run[\s\S]*boom/, ); }); + +test("resolveBase: --base wins, then GATE_BASE, so one GATE_BASE scopes every gate stage (#5759)", () => { + const rev = (ref) => + execFileSync("git", ["rev-parse", `${ref}^{commit}`], { + encoding: "utf8", + }).trim(); + assert.equal(resolveBase(null, { GATE_BASE: "HEAD" }), rev("HEAD")); + // `--base` wins: an unresolvable GATE_BASE is never read. HEAD only, since + // CI's checkout holds a single commit. + assert.equal( + resolveBase("HEAD", { GATE_BASE: "no-such-ref-5759" }), + rev("HEAD"), + ); + assert.throws(() => resolveBase(null, { GATE_BASE: "no-such-ref-5759" })); +}); diff --git a/scripts/lib/gate-scope.mjs b/scripts/lib/gate-scope.mjs new file mode 100644 index 0000000000..9bd9092caf --- /dev/null +++ b/scripts/lib/gate-scope.mjs @@ -0,0 +1,87 @@ +// Which servers the pre-push gate runs its per-server stages for (#5759). +// +// The gate's per-server stages (each TypeScript server's checks and coverage, +// each Python server's checks and coverage, and the boot smoke) used to run +// all seven servers whatever a change touched, so a fix confined to +// `src/memory/` waited on the fetch, git and everything suites too. This +// module decides the scope from the files a change touched, and says why, so +// the gate log can print the decision: +// +// - Every changed path is under `src//` for one or more known +// servers: those servers only. +// - Any other path (a root manifest or lockfile, `scripts/`, a workflow, +// the root TypeScript, lint or format configuration, `AGENTS.md`, a skill, +// a doc): every server, as before. The rule is "anything outside a server +// directory", not a list of repository-wide files, because a list goes +// stale silently and an unlisted file would then scope a change it can +// break. Over-gating costs minutes; under-gating costs a red `v2/main`. +// - The one exception is a pending changeset (`.changeset/.md`): it is +// release metadata for a server the same change already touches, and every +// TypeScript change carries one. `.changeset/config.json` and +// `.changeset/README.md` are not changesets, so they still select every +// server. +// - No server selected at all (an empty change, as when the gate checks +// `v2/main` itself, or a change of changesets alone): every server, since +// a gate that ran nothing would pass vacuously. +// +// The root guards (`validate:guards`, `verify:dco`, `verify:install-fresh`, +// `verify:skills:cli`) are not scoped; the gate runs them every time. The +// interface diff and the image smoke make their own, finer selection +// (`interface-diff-servers.mjs`, `image-smoke.mjs`), so this module does not +// drive them. +// +// Pure: it takes the changed paths and the server table and returns the +// decision. `scripts/gate-servers.mjs` reads the paths from git. + +import { SERVERS } from "./interface-diff-servers.mjs"; + +/** A pending changeset: `.changeset/.md`, but not its README. */ +export function isChangeset(file) { + return ( + /^\.changeset\/[^/]+\.md$/.test(file) && file !== ".changeset/README.md" + ); +} + +/** + * The servers whose per-server stages a change needs, in `servers` order. + * + * @param {string[]} changedFiles repository-relative, `/`-separated paths + * @param {{ name: string, language: string }[]} [servers] + * @returns {{ all: boolean, reason: string, + * servers: { name: string, language: string }[] }} + */ +export function chooseScope(changedFiles, servers = SERVERS) { + const every = (reason) => ({ all: true, reason, servers: [...servers] }); + const owner = (file) => + servers.find((s) => file.startsWith(`src/${s.name}/`)); + + const wide = changedFiles.filter((f) => !owner(f) && !isChangeset(f)); + if (wide.length > 0) { + const first = wide.slice(0, 3).map((f) => `\`${f}\``); + const more = wide.length > 3 ? ` and ${wide.length - 3} more` : ""; + return every( + `${first.join(", ")}${more} ${wide.length === 1 ? "is" : "are"} outside every server directory`, + ); + } + + const touched = new Set( + changedFiles.map((f) => owner(f)?.name).filter(Boolean), + ); + if (touched.size === 0) + return every( + changedFiles.length === 0 + ? "nothing changed against the base" + : "no server directory changed", + ); + + const chosen = servers.filter((s) => touched.has(s.name)); + return { + all: chosen.length === servers.length, + reason: `every changed file is under ${chosen + .map((s) => `\`src/${s.name}/\``) + .join( + ", ", + )}${changedFiles.some(isChangeset) ? " (or is a changeset)" : ""}`, + servers: chosen, + }; +} diff --git a/scripts/lib/gate-scope.test.mjs b/scripts/lib/gate-scope.test.mjs new file mode 100644 index 0000000000..8ac8200d8d --- /dev/null +++ b/scripts/lib/gate-scope.test.mjs @@ -0,0 +1,105 @@ +// Tests for the gate's server scope (#5759): a change confined to server +// directories gates those servers only, anything else gates every server, and +// the reason printed says which rule decided. Run via `npm run test:scripts`. + +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { SERVERS } from "./interface-diff-servers.mjs"; +import { chooseScope, isChangeset } from "./gate-scope.mjs"; + +const names = (scope) => scope.servers.map((s) => s.name); + +describe("chooseScope", () => { + it("gates only the server a change is confined to", () => { + const scope = chooseScope([ + "src/memory/index.ts", + "src/memory/__tests__/knowledge-graph.test.ts", + ]); + assert.equal(scope.all, false); + assert.deepEqual(names(scope), ["memory"]); + assert.match(scope.reason, /`src\/memory\/`/); + }); + + it("gates each touched server, in table order, across languages", () => { + const scope = chooseScope(["src/time/x.py", "src/memory/index.ts"]); + assert.deepEqual(names(scope), ["memory", "time"]); + assert.deepEqual( + scope.servers.map((s) => s.language), + ["ts", "py"], + ); + }); + + it("does not let a changeset widen the scope", () => { + const scope = chooseScope([ + "src/memory/index.ts", + ".changeset/brave-owls-sing.md", + ]); + assert.deepEqual(names(scope), ["memory"]); + assert.match(scope.reason, /changeset/); + }); + + for (const wide of [ + "package.json", + "package-lock.json", + "tsconfig.json", + "eslint.config.js", + ".prettierrc", + "scripts/smoke-servers.mjs", + ".github/workflows/typescript.yml", + ".changeset/config.json", + ".changeset/README.md", + "AGENTS.md", + ".claude/skills/testing/SKILL.md", + "docs/quality-gate.md", + "README.md", + ]) + it(`gates every server when \`${wide}\` changes`, () => { + const scope = chooseScope(["src/memory/index.ts", wide]); + assert.equal(scope.all, true); + assert.deepEqual( + names(scope), + SERVERS.map((s) => s.name), + ); + assert.match(scope.reason, /outside every server directory/); + assert.ok(scope.reason.includes(`\`${wide}\``)); + }); + + it("does not mistake a sibling directory for a server's", () => { + // `src/memory-next/` is not `src/memory/`. + const scope = chooseScope(["src/memory-next/index.ts"]); + assert.equal(scope.all, true); + }); + + it("names at most three wide files in its reason", () => { + const scope = chooseScope(["a", "b", "c", "d", "e"]); + assert.match(scope.reason, /`a`, `b`, `c` and 2 more are outside/); + }); + + it("gates every server when nothing changed, rather than nothing", () => { + const scope = chooseScope([]); + assert.equal(scope.all, true); + assert.match(scope.reason, /nothing changed/); + }); + + it("gates every server when only changesets changed", () => { + const scope = chooseScope([".changeset/brave-owls-sing.md"]); + assert.equal(scope.all, true); + assert.match(scope.reason, /no server directory changed/); + }); + + it("reports `all` when every server is touched by name", () => { + const scope = chooseScope(SERVERS.map((s) => `src/${s.name}/README.md`)); + assert.equal(scope.all, true); + assert.equal(scope.servers.length, SERVERS.length); + }); +}); + +describe("isChangeset", () => { + it("is a top-level .md under .changeset/, not its README or config", () => { + assert.equal(isChangeset(".changeset/brave-owls-sing.md"), true); + assert.equal(isChangeset(".changeset/README.md"), false); + assert.equal(isChangeset(".changeset/config.json"), false); + assert.equal(isChangeset(".changeset/nested/x.md"), false); + assert.equal(isChangeset("docs/x.md"), false); + }); +}); diff --git a/scripts/lib/workflow-gate.test.mjs b/scripts/lib/workflow-gate.test.mjs index 9aa870ccf1..99e579d422 100644 --- a/scripts/lib/workflow-gate.test.mjs +++ b/scripts/lib/workflow-gate.test.mjs @@ -30,6 +30,8 @@ import { reachableScripts, scriptChainRuns, } from "./npm-scripts.mjs"; +import { gatePlan } from "../gate-servers.mjs"; +import { SERVERS } from "./interface-diff-servers.mjs"; const repoRoot = join(import.meta.dirname, "..", ".."); const workflowDir = join(repoRoot, ".github", "workflows"); @@ -379,19 +381,15 @@ describe("the gate's name", () => { // The stages by name. The CI-parity test under `.github/workflows` derives // the same requirement from what the workflows actually run; this list also - // pins the stage that has no CI counterpart (`verify:install-fresh`), the - // root `coverage` (#4854), whose CI legs run each workspace's `coverage`, and - // `verify:dco` (#4919), which CI runs only on a pull request. + // pins the stage that has no CI counterpart (`verify:install-fresh`) and + // `verify:dco` (#4919), which CI runs only on a pull request. The + // per-server stages run through `scripts/gate-servers.mjs` (#5759), pinned + // below. for (const stage of [ "verify:install-fresh", "verify:dco", - "validate", "validate:guards", - "coverage", - "validate:py", - "coverage:py", "verify:skills:cli", - "smoke", "interface-diff", "image-smoke", ]) { @@ -402,6 +400,52 @@ describe("the gate's name", () => { ); }); } + + it("runs the per-server stages as a step of their own, unmasked", () => { + // A `|| true` or a pipe beside it would swallow every server's verdict. + const segments = scripts["local:gate:stages"] + .split(/&&/) + .map((s) => s.trim()); + assert.ok( + segments.includes("node scripts/gate-servers.mjs"), + `local:gate:stages must run \`node scripts/gate-servers.mjs\` as a segment of its own: ${scripts["local:gate:stages"]}`, + ); + }); + + // Each suite runs once, under coverage (#5759): the TypeScript `check` and + // `coverage` (#4854), the Python chain without pytest and `coverage:py` + // (#4855), and the boot smoke, for every server in the full scope. + it("runs every server's checks, coverage and smoke in the full scope", () => { + const plan = gatePlan({ servers: SERVERS }); + for (const name of [ + "check", + "coverage", + "validate:py", + "coverage:py", + "smoke", + ]) + assert.ok( + plan.some((step) => step.argv[2] === name), + `the full gate must run ${name}`, + ); + }); + + for (const file of ["typescript.yml", "python.yml"]) + it(`${file}: the draft lookup never reads v2/main or main as a draft (#5759)`, () => { + // v2/main heads the release merge PR into main, which can be a draft; + // reading it as one would skip coverage and the smoke on v2/main. + const text = readFileSync(join(workflowDir, file), "utf8"); + assert.match(text, /\[ "\$BRANCH" != v2\/main \]/); + assert.match(text, /\[ "\$BRANCH" != main \]/); + }); + + it("puts the draft gate under the same lease, with verify:dco", () => { + assert.equal( + scripts["local:gate:draft"], + `${GATE_LEASE_WRAPPER}npm run local:gate:draft:stages`, + ); + assert.ok(scriptChainRuns(scripts, "local:gate:draft", "verify:dco")); + }); }); describe(".github/workflows", () => { @@ -435,7 +479,14 @@ describe(".github/workflows", () => { const { scripts } = JSON.parse( readFileSync(join(repoRoot, "package.json"), "utf8"), ); + // What the gate reaches through its npm chain, plus the scripts the + // per-server stage runs (`scripts/gate-servers.mjs`, #5759) in the full + // scope. Their names may be workspace scripts (`check`, `coverage`), which + // CI runs from a workspace directory under the same name. const reached = reachableScripts(scripts, "local:gate"); + for (const step of gatePlan({ servers: SERVERS })) + for (const name of reachableScripts(scripts, step.argv[2])) + reached.add(name); const reachedBodies = [...reached].map((n) => scripts[n] ?? ""); const missing = []; let checked = 0; diff --git a/scripts/validate-py.mjs b/scripts/validate-py.mjs index ceef6d435c..be1acd8d82 100644 --- a/scripts/validate-py.mjs +++ b/scripts/validate-py.mjs @@ -5,6 +5,7 @@ * * node scripts/validate-py.mjs # every server under src/ with a pyproject.toml * node scripts/validate-py.mjs fetch git # just the named ones + * node scripts/validate-py.mjs --no-pytest fetch # every step but pytest * npm run validate:py # the root entry point (all servers) * * Each server runs the same chain, in its own directory, through `uv` (never @@ -20,6 +21,10 @@ * reports every server's verdict. CI calls the same script with one server per * matrix leg, so the local command and CI cannot drift. * + * `--no-pytest` drops the pytest step, for a caller that runs the suite + * under coverage right after (`coverage-py.mjs`): the pre-push gate and CI's + * non-draft legs, which would otherwise run every test twice (#5759). + * * Servers are discovered, not listed: a new Python server is gated the moment * it lands with a `pyproject.toml`, rather than silently falling outside a * hardcoded table. @@ -88,6 +93,25 @@ export function selectServers(args, available) { return { servers: args }; } +/** + * Split the command line into server names and the `--no-pytest` flag. Any + * other `--` flag is an error, so a typo is never read as a server name. + * @param {string[]} argv + * @returns {{ names: string[], steps: typeof STEPS } | { error: string }} + */ +export function parseArgs(argv) { + const flags = argv.filter((a) => a.startsWith("-")); + const unknown = flags.filter((a) => a !== "--no-pytest"); + if (unknown.length > 0) + return { error: `unknown flag(s): ${unknown.join(" ")}` }; + return { + names: argv.filter((a) => !a.startsWith("-")), + steps: flags.includes("--no-pytest") + ? STEPS.filter((s) => s.name !== "pytest") + : STEPS, + }; +} + /** * Run one command and report whether it succeeded. * @param {string[]} argv @@ -178,15 +202,21 @@ function main() { "..", ); const srcDir = path.join(repoRoot, "src"); - const selection = selectServers( - process.argv.slice(2), - discoverServers(srcDir), - ); + const args = parseArgs(process.argv.slice(2)); + if ("error" in args) { + console.error(`[validate:py] ${args.error}`); + return 2; + } + const selection = selectServers(args.names, discoverServers(srcDir)); if ("error" in selection) { console.error(`[validate:py] ${selection.error}`); return 2; } - const results = validateServers({ servers: selection.servers, srcDir }); + const results = validateServers({ + servers: selection.servers, + srcDir, + steps: args.steps, + }); const { lines, exitCode } = summarize(results); console.log(["\n[validate:py] summary", ...lines].join("\n")); return exitCode; diff --git a/scripts/validate-py.test.mjs b/scripts/validate-py.test.mjs index bc9b702f5e..e1ed29a074 100644 --- a/scripts/validate-py.test.mjs +++ b/scripts/validate-py.test.mjs @@ -13,6 +13,7 @@ import { after, describe, it } from "node:test"; import { STEPS, discoverServers, + parseArgs, runCommand, selectServers, summarize, @@ -46,6 +47,28 @@ describe("STEPS", () => { }); }); +describe("parseArgs", () => { + it("passes names through and keeps every step by default", () => { + assert.deepEqual(parseArgs(["fetch", "git"]), { + names: ["fetch", "git"], + steps: STEPS, + }); + }); + + it("drops only pytest with --no-pytest, wherever the flag sits (#5759)", () => { + const parsed = parseArgs(["fetch", "--no-pytest"]); + assert.deepEqual(parsed.names, ["fetch"]); + assert.deepEqual( + parsed.steps.map((s) => s.name), + STEPS.map((s) => s.name).filter((n) => n !== "pytest"), + ); + }); + + it("refuses an unknown flag rather than reading it as a server", () => { + assert.match(parseArgs(["--no-pytests", "fetch"]).error, /--no-pytests/); + }); +}); + describe("discoverServers", () => { it("finds only directories holding a pyproject.toml, sorted", () => { const src = path.join(scratch, "src"); diff --git a/src/everything/package.json b/src/everything/package.json index 609c624687..03fe13b3dd 100644 --- a/src/everything/package.json +++ b/src/everything/package.json @@ -34,7 +34,8 @@ "lint": "eslint . --max-warnings 0", "typecheck": "tsc -p tsconfig.test.json", "coverage": "vitest run --coverage", - "validate": "npm run format:check && npm run lint && npm run typecheck && npm run build && npm run test" + "check": "npm run format:check && npm run lint && npm run typecheck && npm run build", + "validate": "npm run check && npm run test" }, "dependencies": { "@modelcontextprotocol/node": "^2.1.1", diff --git a/src/filesystem/package.json b/src/filesystem/package.json index 21ba5524d5..d7aa86bb04 100644 --- a/src/filesystem/package.json +++ b/src/filesystem/package.json @@ -31,7 +31,8 @@ "lint": "eslint . --max-warnings 0", "typecheck": "tsc -p tsconfig.test.json", "coverage": "vitest run --coverage", - "validate": "npm run format:check && npm run lint && npm run typecheck && npm run build && npm run test" + "check": "npm run format:check && npm run lint && npm run typecheck && npm run build", + "validate": "npm run check && npm run test" }, "dependencies": { "@modelcontextprotocol/node": "^2.1.1", diff --git a/src/memory/package.json b/src/memory/package.json index 498461177c..53a30e4874 100644 --- a/src/memory/package.json +++ b/src/memory/package.json @@ -31,7 +31,8 @@ "lint": "eslint . --max-warnings 0", "typecheck": "tsc -p tsconfig.test.json", "coverage": "vitest run --coverage", - "validate": "npm run format:check && npm run lint && npm run typecheck && npm run build && npm run test" + "check": "npm run format:check && npm run lint && npm run typecheck && npm run build", + "validate": "npm run check && npm run test" }, "dependencies": { "@modelcontextprotocol/node": "^2.1.1", diff --git a/src/sequentialthinking/package.json b/src/sequentialthinking/package.json index 8a650518e5..a132c807e6 100644 --- a/src/sequentialthinking/package.json +++ b/src/sequentialthinking/package.json @@ -31,7 +31,8 @@ "lint": "eslint . --max-warnings 0", "typecheck": "tsc -p tsconfig.test.json", "coverage": "vitest run --coverage", - "validate": "npm run format:check && npm run lint && npm run typecheck && npm run build && npm run test" + "check": "npm run format:check && npm run lint && npm run typecheck && npm run build", + "validate": "npm run check && npm run test" }, "dependencies": { "@modelcontextprotocol/node": "^2.1.1",