Skip to content

The agent that grows with you

feat(ci): report files a CI job leaves in the checkout

Teknium9859e0db5e7e
diff --git a/.github/actions/check-clean-worktree/action.yml b/.github/actions/check-clean-worktree/action.yml
new file mode 100644
index 00000000000..47d5cd995dc
--- /dev/null
+++ b/.github/actions/check-clean-worktree/action.yml
@@ -0,0 +1,81 @@
+name: Check the checkout is clean
+description: >-
+ Fail (or warn) when the job left tracked changes or untracked, non-ignored
+ files in the checkout. Tests and CI steps must write under their own temp
+ dirs (pytest's tmp_path, the HERMES_HOME fixture, $RUNNER_TEMP), not into the
+ repo: stray files from test runs have reached main more than once. Run it as
+ the last step of a job, after the checkout exists:
+
+ - name: Check the checkout is clean
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
+inputs:
+ # MASTER SWITCH. This default is the one place the gate's mode is set: callers
+ # never pass `mode` (tests/ci/test_clean_worktree_check.py enforces that), so
+ # flipping it here changes every job at once without touching the step below.
+ # blocking print the files and fail the job
+ # warning print the files as warnings; the job stays green
+ # off skip the check
+ # Any other value fails closed (blocking).
+ mode:
+ description: 'blocking, warning or off. Set only here; callers do not pass it.'
+ default: warning
+
+runs:
+ using: composite
+ steps:
+ - name: git status --porcelain=v1 --untracked-files=normal
+ shell: bash
+ env:
+ _MODE: ${{ inputs.mode }}
+ run: |
+ set -uo pipefail
+ case "$_MODE" in
+ off) echo "check-clean-worktree: mode=off, skipped"; exit 0 ;;
+ warning) level=warning ;;
+ *) level=error ;;
+ esac
+ if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
+ echo "::$level title=Dirty checkout::no git checkout in $PWD; the clean-worktree check needs actions/checkout to have run"
+ [ "$level" = warning ] && exit 0 || exit 1
+ fi
+ status="$(git status --porcelain=v1 --untracked-files=normal)" || {
+ echo "::$level title=Dirty checkout::git status failed"
+ [ "$level" = warning ] && exit 0 || exit 1
+ }
+ if [ -z "$status" ]; then
+ echo "check-clean-worktree: clean (mode=$_MODE)"
+ exit 0
+ fi
+ count="$(wc -l <<< "$status" | tr -d ' ')"
+ echo "::group::git status --porcelain=v1 --untracked-files=normal ($count entries)"
+ printf '%s\n' "$status"
+ echo "::endgroup::"
+ if ! git diff --quiet; then
+ echo "::group::git diff --stat (tracked files this job modified)"
+ git diff --stat
+ echo "::endgroup::"
+ fi
+ # GitHub keeps at most 10 annotations of a level per step: name the
+ # first 9 files, then one summary line pointing at the full list.
+ # Here-strings, not `printf | head`: under the runner's -eo pipefail a
+ # writer killed by SIGPIPE when head exits early would end the step.
+ while IFS= read -r line; do
+ path="${line:3}"
+ case "${line:0:2}" in
+ '??') what="untracked file left in the checkout" ;;
+ *) what="tracked file changed (git status ${line:0:2})" ;;
+ esac
+ echo "::$level title=Dirty checkout::$path: $what"
+ done <<< "$(sed -n '1,9p' <<< "$status")"
+ echo "::$level title=Dirty checkout::this job left $count changed or untracked path(s) in the checkout (full list in the log above). Tests must write under tmp_path / the HERMES_HOME fixture and CI steps under \$RUNNER_TEMP; a genuine build artifact gets a precise .gitignore entry. Reproduce: run the job's command, then git status --porcelain=v1 --untracked-files=normal."
+ if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then
+ {
+ echo "### Dirty checkout ($count paths, mode=$_MODE)"
+ echo '```'
+ sed -n '1,200p' <<< "$status"
+ echo '```'
+ } >> "$GITHUB_STEP_SUMMARY"
+ fi
+ [ "$level" = warning ] && exit 0 || exit 1
diff --git a/.github/workflows/js-tests.yml b/.github/workflows/js-tests.yml
index 252b135f276..df308ae6bc5 100644
--- a/.github/workflows/js-tests.yml
+++ b/.github/workflows/js-tests.yml
@@ -88,3 +88,8 @@ jobs:
# nothing.
- name: Run all workspace checks
run: node .github/scripts/run-workspace-checks.mjs
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index df75595a86d..a5ed3bbf847 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -70,19 +70,23 @@ jobs:
echo "Base SHA: ${BASE_SHA}"
echo "Base ref: ${BASE_REF}"
+ # Reports live under $RUNNER_TEMP, not the checkout: the clean-worktree step at the end of
+ # every job fails (or warns) on untracked files, and .lint-reports/ is not gitignored.
- name: Run ruff + ty on HEAD
run: |
- mkdir -p .lint-reports/head
+ R="$RUNNER_TEMP/lint-reports"
+ mkdir -p "$R/head"
ruff check --output-format json --exit-zero \
- > .lint-reports/head/ruff.json || true
+ > "$R/head/ruff.json" || true
ty check --output-format gitlab --exit-zero \
- > .lint-reports/head/ty.json || true
- echo "HEAD ruff: $(wc -c < .lint-reports/head/ruff.json) bytes"
- echo "HEAD ty: $(wc -c < .lint-reports/head/ty.json) bytes"
+ > "$R/head/ty.json" || true
+ echo "HEAD ruff: $(wc -c < "$R/head/ruff.json") bytes"
+ echo "HEAD ty: $(wc -c < "$R/head/ty.json") bytes"
- name: Run ruff + ty on base (via git worktree)
run: |
- mkdir -p .lint-reports/base
+ R="$RUNNER_TEMP/lint-reports"
+ mkdir -p "$R/base"
# Use a worktree so we don't clobber the main checkout. If the basex
# SHA is identical to HEAD (e.g. first commit), skip and leave the
# base reports empty — the diff script handles missing files.
@@ -90,35 +94,42 @@ jobs:
BASE_SHA="${{ steps.base.outputs.sha }}"
if [ "$BASE_SHA" = "$HEAD_SHA" ]; then
echo "Base SHA == HEAD SHA, skipping base scan."
- echo '[]' > .lint-reports/base/ruff.json
- echo '[]' > .lint-reports/base/ty.json
+ echo '[]' > "$R/base/ruff.json"
+ echo '[]' > "$R/base/ty.json"
else
git worktree add --detach /tmp/lint-base "$BASE_SHA"
(
cd /tmp/lint-base
ruff check --output-format json --exit-zero \
- > "$GITHUB_WORKSPACE/.lint-reports/base/ruff.json" || true
+ > "$R/base/ruff.json" || true
ty check --output-format gitlab --exit-zero \
- > "$GITHUB_WORKSPACE/.lint-reports/base/ty.json" || true
+ > "$R/base/ty.json" || true
)
git worktree remove --force /tmp/lint-base
fi
- echo "base ruff: $(wc -c < .lint-reports/base/ruff.json) bytes"
- echo "base ty: $(wc -c < .lint-reports/base/ty.json) bytes"
+ echo "base ruff: $(wc -c < "$R/base/ruff.json") bytes"
+ echo "base ty: $(wc -c < "$R/base/ty.json") bytes"
- name: Generate diff summary
env:
HEAD_REF: ${{ inputs.event_name == 'pull_request' && github.head_ref || github.ref_name }}
run: |
+ R="$RUNNER_TEMP/lint-reports"
python scripts/lint_diff.py \
- --base-ruff .lint-reports/base/ruff.json \
- --head-ruff .lint-reports/head/ruff.json \
- --base-ty .lint-reports/base/ty.json \
- --head-ty .lint-reports/head/ty.json \
+ --base-ruff "$R/base/ruff.json" \
+ --head-ruff "$R/head/ruff.json" \
+ --base-ty "$R/base/ty.json" \
+ --head-ty "$R/head/ty.json" \
--base-ref "${{ steps.base.outputs.ref }}" \
--head-ref "$HEAD_REF" \
- --output .lint-reports/summary.md
- cat .lint-reports/summary.md >> "$GITHUB_STEP_SUMMARY"
+ --output "$R/summary.md"
+ cat "$R/summary.md" >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
ruff-blocking:
# Enforce the rules in pyproject.toml [tool.ruff.lint.select]. Currently
@@ -151,6 +162,12 @@ jobs:
run: |
ruff check .
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
code-health:
# Per-unit ratchet: every function and file keeps its own cap (its value on main when it is
# already over target, else the target) and pattern rules compare fingerprints, so a PR
@@ -179,6 +196,12 @@ jobs:
- name: Ratchet the PR against the base branch tip
run: python scripts/check --only health --base HEAD^1
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
windows-footguns:
# Static guardrails on Windows-unsafe Python primitives — os.kill(pid, 0),
# os.killpg, os.setsid, signal.SIGKILL without getattr fallback,
@@ -272,3 +295,8 @@ jobs:
git fetch --no-tags --deepen=1000 origin "${{ github.base_ref }}" "$PR_HEAD"
done
python scripts/ci/check_public_surface.py --base "origin/${{ github.base_ref }}" --head origin/pr-head
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
diff --git a/.github/workflows/tests-os.yml b/.github/workflows/tests-os.yml
index 8e335ff7b13..796fbb1ff12 100644
--- a/.github/workflows/tests-os.yml
+++ b/.github/workflows/tests-os.yml
@@ -195,6 +195,12 @@ jobs:
OPENAI_API_KEY: ''
NOUS_API_KEY: ''
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
install-update-e2e:
# The real scripts/install.ps1 -> `hermes update` HEAD -> NEXT journey on a real Windows
# host (tests/e2e/core/windows_update): fresh install, gateway across the update,
@@ -271,3 +277,8 @@ jobs:
"::error::leftover pid=$($p.ProcessId) ppid=$($p.ParentProcessId): $($p.CommandLine)"
}
exit 1
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 76f17c52ea9..1804c249410 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -125,6 +125,12 @@ jobs:
# slice's files and refreshes its own, so the cache stays complete.
key: test-durations-${{ github.run_id }}-${{ matrix.slice }}
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
e2e:
# The core suites spawn real serve / gateway / tui_gateway / MCP / SQLite
# writer processes per test; a 4-vCPU runner serialises them into timeouts.
@@ -209,6 +215,12 @@ jobs:
OPENAI_API_KEY: ""
NOUS_API_KEY: ""
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
e2e-upgrade-plan:
# One e2e-upgrade shard per suite directory: the files directly under
# tests/e2e/core/upgrade ("core") plus every subdirectory that holds
@@ -225,7 +237,10 @@ jobs:
- name: Checkout code
uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1
with:
- sparse-checkout: tests/e2e/core/upgrade
+ # The clean-worktree step below loads its action from the checkout.
+ sparse-checkout: |
+ tests/e2e/core/upgrade
+ .github/actions/check-clean-worktree
- name: List suite directories
id: plan
run: |
@@ -241,6 +256,12 @@ jobs:
)
echo "shards=$shards" | tee -a "$GITHUB_OUTPUT"
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
+
e2e-upgrade:
# tests/e2e/core/upgrade: a real N-1 -> HEAD `hermes update` (clean,
# autostash, killed mid-pull / mid-deps, offline), fresh-process import and
@@ -366,3 +387,8 @@ jobs:
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
NOUS_API_KEY: ""
+ - name: Check the checkout is clean
+ # Last step of every job (tests/ci/test_clean_worktree_check.py): a test or CI step that
+ # leaves an untracked or modified file in the checkout is reported here.
+ if: always() && !cancelled()
+ uses: ./.github/actions/check-clean-worktree
diff --git a/tests/ci/test_clean_worktree_check.py b/tests/ci/test_clean_worktree_check.py
new file mode 100644
index 00000000000..0947513c4b5
--- /dev/null
+++ b/tests/ci/test_clean_worktree_check.py
@@ -0,0 +1,168 @@
+"""Every job of the main CI lanes ends by checking that it left the checkout clean.
+
+The step (.github/actions/check-clean-worktree) runs ``git status --porcelain=v1
+--untracked-files=normal`` and reports tracked changes and untracked, non-ignored
+files. Stray test output reached main more than once (log.txt, default.tar.gz,
+MagicMock/<name>/<id> SQLite stores, a ``%SystemDrive%`` tree); .gitignore hides
+the rest. Its mode is set in ONE place, the action's ``mode`` input default.
+"""
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+from ruamel.yaml import YAML
+
+ROOT = Path(__file__).resolve().parents[2]
+ACTION_DIR = ".github/actions/check-clean-worktree"
+ACTION = ROOT / ACTION_DIR / "action.yml"
+USES = f"./{ACTION_DIR}"
+WORKFLOWS = ("tests.yml", "tests-os.yml", "lint.yml", "js-tests.yml")
+MODES = ("blocking", "warning", "off")
+
+
+def _load(path: Path):
+ return YAML(typ="base").load(path.read_text(encoding="utf-8"))
+
+
+def _checkout_jobs():
+ for filename in WORKFLOWS:
+ for name, job in (_load(ROOT / ".github/workflows" / filename)["jobs"] or {}).items():
+ steps = job.get("steps") or [] # reusable-workflow calls have none
+ if any(str(step.get("uses", "")).startswith("actions/checkout@") for step in steps):
+ yield f"{filename}:{name}", job, steps
+
+
+def test_every_checkout_job_ends_with_the_clean_worktree_step():
+ jobs = list(_checkout_jobs())
+ assert len(jobs) >= 10, [label for label, *_ in jobs] # tests 4, tests-os 2, lint 4, js 1
+ problems = []
+ for label, job, steps in jobs:
+ last = steps[-1]
+ if last.get("uses") != USES:
+ problems.append(f"{label}: last step is {last.get('name') or last.get('uses')!r}")
+ continue
+ if str(last.get("if", "")).replace(" ", "") != "always()&&!cancelled()":
+ problems.append(f"{label}: needs `if: always() && !cancelled()`, has {last.get('if')!r}")
+ if "mode" in (last.get("with") or {}):
+ problems.append(f"{label}: passes `mode`; the action's default is the only switch")
+ checkout = next(s for s in steps if str(s.get("uses", "")).startswith("actions/checkout@"))
+ sparse = str((checkout.get("with") or {}).get("sparse-checkout", ""))
+ if sparse and ACTION_DIR not in sparse.split():
+ problems.append(f"{label}: sparse checkout omits {ACTION_DIR}, so the step cannot load")
+ assert not problems, "\n".join(problems)
+
+
+def test_no_workflow_overrides_the_master_switch():
+ offenders = []
+ for path in sorted((ROOT / ".github/workflows").glob("*.y*ml")):
+ for name, job in (_load(path).get("jobs") or {}).items():
+ for step in job.get("steps") or []:
+ if step.get("uses") == USES and "mode" in (step.get("with") or {}):
+ offenders.append(f"{path.name}:{name}")
+ assert not offenders, offenders
+
+
+def test_master_switch_is_a_known_mode():
+ assert _load(ACTION)["inputs"]["mode"]["default"] in MODES
+
+
+# ── behaviour: run the action's script against a real repository ──────────────────────
+
+
+def repo(tmp_path):
+ git = shutil.which("git")
+ if git is None:
+ pytest.skip("git not installed")
+ work = tmp_path / "repo"
+ work.mkdir()
+ env = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
+ for args in (["init", "-q"], ["config", "user.email", "[email protected]"], ["config", "user.name", "t"]):
+ subprocess.run([git, *args], cwd=work, env=env, check=True)
+ (work / ".gitignore").write_text("ignored/\n", encoding="utf-8")
+ (work / "tracked.txt").write_text("one\n", encoding="utf-8")
+ subprocess.run([git, "add", "."], cwd=work, env=env, check=True)
+ subprocess.run([git, "commit", "-qm", "init"], cwd=work, env=env, check=True)
+ return work, env
+
+
+def _run(cwd: Path, env: dict, mode: str, tmp_path: Path):
+ bash = shutil.which("bash")
+ if bash is None:
+ pytest.skip("bash not installed")
+ script = _load(ACTION)["runs"]["steps"][0]["run"]
+ summary = tmp_path / "summary.md"
+ result = subprocess.run(
+ [bash, "--noprofile", "--norc", "-eo", "pipefail", "-c", script],
+ cwd=cwd, env={**env, "_MODE": mode, "GITHUB_STEP_SUMMARY": str(summary)},
+ capture_output=True, text=True, encoding="utf-8", timeout=60, check=False,
+ )
+ return result.returncode, result.stdout, summary
+
+
+def test_clean_checkout_passes_and_ignored_files_do_not_count(repo, tmp_path):
+ work, env = repo
+ (work / "ignored").mkdir()
+ (work / "ignored" / "out.db").write_text("x", encoding="utf-8")
+ code, out, _ = _run(work, env, "blocking", tmp_path)
+ assert code == 0, out
+ assert "clean" in out and "::error" not in out
+
+
+def test_blocking_fails_and_names_untracked_and_modified_files(repo, tmp_path):
+ work, env = repo
+ (work / "log.txt").write_text("stray", encoding="utf-8")
+ (work / "tracked.txt").write_text("two\n", encoding="utf-8")
+ code, out, summary = _run(work, env, "blocking", tmp_path)
+ assert code == 1, out
+ assert "::error title=Dirty checkout::log.txt: untracked file left in the checkout" in out
+ assert "::error title=Dirty checkout::tracked.txt: tracked file changed" in out
+ assert "tracked.txt | 2 +-" in out # git diff --stat
+ assert "log.txt" in summary.read_text(encoding="utf-8")
+
+
+def test_warning_mode_reports_without_failing(repo, tmp_path):
+ work, env = repo
+ (work / "default.tar.gz.part").write_text("stray", encoding="utf-8")
+ code, out, _ = _run(work, env, "warning", tmp_path)
+ assert code == 0, out
+ assert "::warning title=Dirty checkout::default.tar.gz.part" in out
+ assert "::error" not in out
+
+
+def test_off_skips_and_unknown_mode_fails_closed(repo, tmp_path):
+ work, env = repo
+ (work / "stray").write_text("x", encoding="utf-8")
+ assert _run(work, env, "off", tmp_path)[0] == 0
+ code, out, _ = _run(work, env, "blockng", tmp_path)
+ assert code == 1 and "::error" in out
+
+
+def test_annotations_cap_at_ten_with_the_full_list_in_the_log(repo, tmp_path):
+ work, env = repo
+ for i in range(25):
+ (work / f"stray{i:02}").write_text("x", encoding="utf-8")
+ code, out, _ = _run(work, env, "blocking", tmp_path)
+ assert code == 1
+ assert out.count("::error ") == 10 # GitHub keeps 10 per step: 9 files + the summary line
+ assert "left 25 changed or untracked path(s)" in out
+ assert all(f"?? stray{i:02}" in out for i in range(25))
+
+
+def test_missing_checkout_is_reported(tmp_path):
+ bare = tmp_path / "nogit"
+ bare.mkdir()
+ env = {**os.environ, "GIT_CEILING_DIRECTORIES": str(tmp_path)}
+ code, out, _ = _run(bare, env, "blocking", tmp_path)
+ assert code == 1 and "no git checkout" in out
+ assert _run(bare, env, "warning", tmp_path)[0] == 0