Skip to content

The agent that grows with you

ci: forbid literal /tmp paths outside a burn-down baseline

teknium13999096d1861
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 5855e3bd945..83c064eabde 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -185,6 +185,14 @@ jobs:
- name: Forbid in-tree use of plugin-compat pointers
run: python scripts/check_compat_pointers.py
+ # /tmp is not portable (Termux has none, native Windows has none, macOS aliases it to
+ # /private/tmp, Linux mounts it as a small tmpfs). Production code resolves scratch space
+ # through the scratch-dir helper; skills, docs and prompts must not teach the model a
+ # literal /tmp either. `no-tmp: ok — <why>` marks a deliberate line; _BASELINE in the
+ # script is the burn-down list of pre-existing hits.
+ - name: Forbid literal /tmp paths outside the baseline
+ run: python scripts/check_no_tmp_literals.py
+
# The OS lanes import only files carrying the matching marker, so a test that fakes
# macOS (is_macos -> True, sys.platform -> "darwin") without `macos_only` is green on
# Linux over a faked branch and never runs on macOS (#111866, AGENTS.md § Don't fake the host OS).
diff --git a/scripts/check_no_tmp_literals.py b/scripts/check_no_tmp_literals.py
new file mode 100644
index 00000000000..b214153443c
--- /dev/null
+++ b/scripts/check_no_tmp_literals.py
@@ -0,0 +1,353 @@
+#!/usr/bin/env python3
+"""Fail when production code, skills, docs or prompts hard-code a literal ``/tmp`` path.
+
+``/tmp`` is not portable: Termux has no ``/tmp`` at all, native Windows has no such directory,
+macOS aliases it to ``/private/tmp`` (breaking naive path comparisons), and on most Linux
+distributions it is a RAM-backed tmpfs that fills under Hermes load. Hermes resolves scratch
+space through one helper (``hermes_constants.get_scratch_dir()`` → ``HERMES_HOME/cache/scratch``,
+which every Hermes process also exports as ``TMPDIR``/``TMP``/``TEMP``), and prompts + skills
+must steer the model the same way, because a literal ``/tmp`` in a SKILL.md or system prompt
+becomes a literal ``/tmp`` in the model's shell commands on every platform.
+
+Flags any line containing a ``/tmp`` path token (``/tmp``, ``/tmp/...``) in the scanned trees.
+Automatically NOT flagged (no marker needed):
+
+ ${TMPDIR:-/tmp} shell fallback idiom: TMPDIR wins where it is set
+ /var/tmp, /private/tmp different directories, not the bare ``/tmp`` root
+ tmpfs, tmp_path, ~/tmp not a ``/tmp`` path at all
+ code comments, docstrings they describe code; nothing there reaches a shell or the model
+ (Markdown prose is NOT exempt: docs and skills are read by both)
+
+Opt out of one line with ``no-tmp: ok — <why>`` on that line or on the line directly above it
+(``# no-tmp: ok — ...`` in Python/shell, ``<!-- no-tmp: ok — ... -->`` in Markdown). Legitimate
+reasons: the code *detects* ``/tmp`` (path-alias checks, security denylists, the scratch-dir
+resolver's own POSIX fallback) or the text explains why ``/tmp`` is wrong. "It works on my
+machine" is not one.
+
+``_BASELINE`` maps files that already carried literals when this check landed to their hit
+count. It is a burn-down list, not a policy: fix the file (or mark the lines) and drop the
+entry. A baseline file gaining hits fails the check; an entry that overstates a file (partly or
+fully burned down) is reported as an advisory so parallel clean-ups never turn CI red — refresh
+it with ``--print-baseline`` (``--strict-baseline`` turns those advisories into failures).
+
+Scope: every first-party ``.py .sh .ts .tsx .js .mjs .cjs .md .mdx .txt .yaml .yml .json .toml``
+file except tests (``tests/``, ``tests-js/``, ``__tests__/``, ``e2e/``, ``test_*.py``,
+``*.test.ts`` ...), ``evals/``, CI workflows (``.github/`` runs on Linux runners), container
+build files (``Dockerfile*``, ``docker/``), generated lockfiles and the translated docs mirror
+(``website/i18n/``, regenerated from the English source).
+
+Run: python scripts/check_no_tmp_literals.py [--all] [--print-baseline] [paths...]
+ --all ignore ``_BASELINE`` and report every hit (burn-down view)
+ --print-baseline print a ``_BASELINE`` literal matching the current tree
+ --strict-baseline fail on stale/overstated ``_BASELINE`` entries too
+Exit 1 on any violation, 0 when clean.
+"""
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+import warnings
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+SELF = Path(__file__).resolve()
+
+MARKER = "no-tmp: ok"
+
+SCAN_SUFFIXES = {
+ ".py", ".sh", ".bash", ".ts", ".tsx", ".js", ".mjs", ".cjs",
+ ".md", ".mdx", ".txt", ".yaml", ".yml", ".json", ".toml",
+}
+
+# Pruned at every depth.
+SKIP_DIRS = {
+ ".git", ".venv", "venv", "node_modules", "__pycache__", "build", "dist", ".worktrees",
+ "tests", "tests-js", "__tests__", "e2e", "evals", "docker", "MagicMock",
+ ".pytest_cache", ".ruff_cache", ".mypy_cache", "coverage", "target",
+}
+# Pruned only directly under the repo root.
+ROOT_SKIP_DIRS = {".github"}
+# Pruned as repo-relative paths.
+SKIP_REL_DIRS = {Path("website/i18n"), Path("website/build"), Path("website/node_modules")}
+
+SKIP_FILE_NAMES = {"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "uv.lock", "poetry.lock"}
+SKIP_FILE_PATTERNS = (
+ re.compile(r"^test_.*\.py$"),
+ re.compile(r"_test\.py$"),
+ re.compile(r"^conftest\.py$"),
+ re.compile(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$"),
+ re.compile(r"^Dockerfile(\..*)?$"),
+)
+
+# A `/tmp` path token: not glued to a preceding path/word char (`/var/tmp`, `~/tmp`, `a/tmp`),
+# not the `${TMPDIR:-/tmp}` fallback idiom, and not followed by a word char (`/tmpfs`).
+_TMP_TOKEN = re.compile(r"(?<![\w./~\\-])(?<!:-)/tmp(?![\w-])")
+
+
+_LINE_COMMENT_PREFIX = {
+ ".sh": ("#",), ".bash": ("#",), ".yaml": ("#",), ".yml": ("#",), ".toml": ("#",),
+ ".ts": ("//", "/*", "*"), ".tsx": ("//", "/*", "*"), ".js": ("//", "/*", "*"),
+ ".mjs": ("//", "/*", "*"), ".cjs": ("//", "/*", "*"),
+}
+_TRAILING_COMMENT = {".py": "#", ".sh": "#", ".bash": "#", ".yaml": "#", ".yml": "#", ".toml": "#",
+ ".ts": "//", ".tsx": "//", ".js": "//", ".mjs": "//", ".cjs": "//"}
+
+
+def _python_comment_and_docstring_spans(text: str) -> tuple[dict[int, int], set[int]]:
+ """(line -> column where a `#` comment starts, lines inside doc-strings) via tokenize/ast.
+
+ Comments and docstrings *describe* code; a `/tmp` there cannot reach a shell or the model, so
+ they stay out of the count (prompt strings, defaults and command templates are what matters).
+ """
+ import ast
+ import io
+ import tokenize
+
+ comments: dict[int, int] = {}
+ try:
+ for tok in tokenize.generate_tokens(io.StringIO(text).readline):
+ if tok.type == tokenize.COMMENT:
+ comments[tok.start[0]] = tok.start[1]
+ except (tokenize.TokenError, SyntaxError, IndentationError):
+ pass
+ doc_lines: set[int] = set()
+ try:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore") # scanned files' own SyntaxWarnings are not our business
+ tree = ast.parse(text)
+ except (SyntaxError, ValueError):
+ return comments, doc_lines
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
+ body = getattr(node, "body", [])
+ if body and isinstance(body[0], ast.Expr) and isinstance(getattr(body[0], "value", None), ast.Constant) \
+ and isinstance(body[0].value.value, str):
+ doc_lines.update(range(body[0].lineno, (body[0].end_lineno or body[0].lineno) + 1))
+ return comments, doc_lines
+
+
+def _iter_lines_with_hits(text: str, suffix: str = ""):
+ prev_marked = False
+ comments: dict[int, int] = {}
+ doc_lines: set[int] = set()
+ if suffix == ".py":
+ comments, doc_lines = _python_comment_and_docstring_spans(text)
+ prefixes = _LINE_COMMENT_PREFIX.get(suffix, ())
+ trailing = _TRAILING_COMMENT.get(suffix)
+ for lineno, line in enumerate(text.splitlines(), start=1):
+ marked = MARKER in line
+ try:
+ match = _TMP_TOKEN.search(line)
+ if not match or marked or prev_marked or lineno in doc_lines:
+ continue
+ stripped = line.lstrip()
+ if prefixes and stripped.startswith(prefixes):
+ continue # whole-line comment
+ if suffix == ".py":
+ if lineno in comments and match.start() >= comments[lineno]:
+ continue # inside a trailing `#` comment (tokenize-exact: not a `#` in a string)
+ elif trailing:
+ cut = line.find(trailing)
+ if 0 <= cut < match.start() and not re.search(r"""["'`]""", line[:cut]):
+ continue # trailing comment on a line with no string literal before it
+ yield lineno, line
+ finally:
+ prev_marked = marked
+
+
+def _skip_file(path: Path) -> bool:
+ if path == SELF or path.suffix not in SCAN_SUFFIXES or path.name in SKIP_FILE_NAMES:
+ return True
+ return any(p.search(path.name) for p in SKIP_FILE_PATTERNS)
+
+
+def iter_files(root: Path | None = None):
+ root = (root or ROOT).resolve()
+ for dirpath, dirnames, filenames in os.walk(root):
+ here = Path(dirpath)
+ rel_here = here.relative_to(root) if here != root else Path()
+ excluded = SKIP_DIRS | (ROOT_SKIP_DIRS if here == root else set())
+ dirnames[:] = sorted(
+ d for d in dirnames if d not in excluded and (rel_here / d) not in SKIP_REL_DIRS
+ )
+ for filename in sorted(filenames):
+ path = here / filename
+ if not _skip_file(path):
+ yield path
+
+
+def scan(paths=None, root: Path | None = None) -> dict[str, list[tuple[int, str]]]:
+ """Repo-relative POSIX path -> [(lineno, line)] for every file with at least one hit."""
+ root = (root or ROOT).resolve()
+ hits: dict[str, list[tuple[int, str]]] = {}
+ files = list(paths) if paths else list(iter_files(root))
+ for path in files:
+ path = Path(path).resolve()
+ if paths and _skip_file(path):
+ continue
+ try:
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ found = list(_iter_lines_with_hits(text, path.suffix))
+ if found:
+ try:
+ rel = path.relative_to(root).as_posix()
+ except ValueError:
+ rel = str(path)
+ hits[rel] = found
+ return hits
+
+
+# Files that carried literal /tmp paths when this check landed, with their hit counts.
+# Burn-down list: fix or mark, then delete the entry. Regenerate with --print-baseline.
+_BASELINE: dict[str, int] = {
+ "CONTRIBUTING.md": 1,
+ "apps/desktop/README.md": 1,
+ "apps/desktop/scripts/perf/README.md": 2,
+ "apps/desktop/scripts/profile-typing-lag.md": 4,
+ "gateway/control_socket.py": 1,
+ "hermes_cli/codex_runtime_plugin_migration.py": 1,
+ "hermes_cli/gateway.py": 1,
+ "hermes_constants.py": 1,
+ "mini_swe_runner.py": 1,
+ "plugins/disk-cleanup/README.md": 2,
+ "plugins/disk-cleanup/__init__.py": 1,
+ "plugins/platforms/line/adapter.py": 1,
+ "scripts/generate_conformance_vectors.py": 1,
+ "tools/browser_tool.py": 1,
+ "tools/code_kernel.py": 1,
+ "tools/environments/base.py": 1,
+ "tools/environments/daytona.py": 1,
+ "tools/environments/docker.py": 1,
+ "tools/environments/local.py": 3,
+ "tools/environments/vercel_sandbox.py": 1,
+ "tools/self_repo_guard.py": 2,
+ "tools/skills_guard.py": 2,
+ "website/docs/developer-guide/egress-internals.md": 2,
+ "website/docs/developer-guide/gateway-monitoring.md": 3,
+ "website/docs/developer-guide/image-gen-provider-plugin.md": 1,
+ "website/docs/developer-guide/middleware.md": 2,
+ "website/docs/developer-guide/model-provider-plugin.md": 1,
+ "website/docs/developer-guide/session-storage.md": 1,
+ "website/docs/getting-started/nix-setup.md": 2,
+ "website/docs/guides/delegation-patterns.md": 2,
+ "website/docs/guides/local-ollama-setup.md": 2,
+ "website/docs/guides/pipe-script-output.md": 1,
+ "website/docs/reference/cli-commands.md": 9,
+ "website/docs/reference/faq.md": 1,
+ "website/docs/user-guide/bot-mode.md": 3,
+ "website/docs/user-guide/configuration.md": 3,
+ "website/docs/user-guide/desktop.md": 1,
+ "website/docs/user-guide/docker.md": 2,
+ "website/docs/user-guide/features/built-in-plugins.md": 2,
+ "website/docs/user-guide/features/codex-app-server-runtime.md": 1,
+ "website/docs/user-guide/features/context-files.md": 1,
+ "website/docs/user-guide/features/cron.md": 2,
+ "website/docs/user-guide/features/deliverable-mode.md": 4,
+ "website/docs/user-guide/features/document-extraction.md": 1,
+ "website/docs/user-guide/features/goals.md": 11,
+ "website/docs/user-guide/features/mcp.md": 1,
+ "website/docs/user-guide/features/skills.md": 1,
+ "website/docs/user-guide/messaging/slack.md": 1,
+ "website/docs/user-guide/security.md": 2,
+ "website/docs/user-guide/skills/bundled/apple/apple-findmy.md": 6,
+ "website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-claude-code.md": 3,
+ "website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-codex.md": 6,
+ "website/docs/user-guide/skills/bundled/autonomous-ai-agents/autonomous-ai-agents-opencode.md": 2,
+ "website/docs/user-guide/skills/bundled/creative/creative-ascii-art.md": 2,
+ "website/docs/user-guide/skills/bundled/creative/creative-pretext.md": 1,
+ "website/docs/user-guide/skills/bundled/github/github-github-pr-workflow.md": 2,
+ "website/docs/user-guide/skills/bundled/github/github-github-repo-management.md": 2,
+ "website/docs/user-guide/skills/bundled/productivity/productivity-ocr-and-documents.md": 1,
+ "website/docs/user-guide/skills/bundled/research/research-blocked-page-recovery.md": 1,
+ "website/docs/user-guide/skills/bundled/smart-home/smart-home-openhue.md": 2,
+ "website/docs/user-guide/skills/bundled/software-development/software-development-hermes-agent-skill-authoring.md": 1,
+ "website/docs/user-guide/skills/bundled/software-development/software-development-inspecting-hermes-desktop-dom.md": 2,
+ "website/docs/user-guide/skills/bundled/software-development/software-development-node-inspect-debugger.md": 7,
+ "website/docs/user-guide/skills/bundled/software-development/software-development-python-debugpy.md": 1,
+ "website/docs/user-guide/skills/bundled/web/web-blocked-page-recovery.md": 1,
+ "website/docs/user-guide/skills/optional/autonomous-ai-agents/autonomous-ai-agents-blackbox.md": 2,
+ "website/docs/user-guide/skills/optional/autonomous-ai-agents/autonomous-ai-agents-dynamic-workflow.md": 2,
+ "website/docs/user-guide/skills/optional/autonomous-ai-agents/autonomous-ai-agents-grok.md": 7,
+ "website/docs/user-guide/skills/optional/autonomous-ai-agents/autonomous-ai-agents-openhands.md": 1,
+ "website/docs/user-guide/skills/optional/creative/creative-ascii-art.md": 2,
+ "website/docs/user-guide/skills/optional/creative/creative-meme-generation.md": 9,
+ "website/docs/user-guide/skills/optional/creative/creative-pixel-art.md": 3,
+ "website/docs/user-guide/skills/optional/creative/creative-pretext.md": 1,
+ "website/docs/user-guide/skills/optional/data-science/data-science-jupyter-notebook.md": 1,
+ "website/docs/user-guide/skills/optional/devops/devops-pinggy-tunnel.md": 25,
+ "website/docs/user-guide/skills/optional/gaming/gaming-pokemon-player.md": 1,
+ "website/docs/user-guide/skills/optional/mcp/mcp-mcp-oauth-remote-gateway.md": 2,
+ "website/docs/user-guide/skills/optional/payments/payments-stripe-link-cli.md": 2,
+ "website/docs/user-guide/skills/optional/research/research-bioinformatics.md": 4,
+ "website/docs/user-guide/skills/optional/research/research-darwinian-evolver.md": 5,
+ "website/docs/user-guide/skills/optional/research/research-parallel-cli.md": 2,
+ "website/docs/user-guide/skills/optional/research/research-qmd.md": 2,
+ "website/docs/user-guide/skills/optional/smart-home/smart-home-openhue.md": 2,
+ "website/docs/user-guide/skills/optional/software-development/software-development-pr-lens.md": 1,
+ "website/docs/user-guide/skills/optional/web-development/web-development-har-derived-api-client.md": 2,
+ "website/docs/user-guide/skills/optional/yuanbao/yuanbao-yuanbao.md": 1,
+ "website/docs/user-guide/windows-wsl-quickstart.md": 1,
+}
+
+
+def _format_baseline(hits: dict[str, list]) -> str:
+ body = "".join(f' "{rel}": {len(found)},\n' for rel, found in sorted(hits.items()))
+ return "_BASELINE: dict[str, int] = {\n" + body + "}"
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
+ ap.add_argument("paths", nargs="*", help="files to check (default: whole repo)")
+ ap.add_argument("--all", action="store_true", help="ignore _BASELINE; report every hit")
+ ap.add_argument("--print-baseline", action="store_true", help="print a _BASELINE for the current tree")
+ ap.add_argument("--strict-baseline", action="store_true", help="also fail when _BASELINE overstates a file")
+ args = ap.parse_args(argv)
+
+ hits = scan(args.paths or None)
+ if args.print_baseline:
+ print(_format_baseline(hits))
+ return 0
+
+ baseline = {} if (args.all or args.paths) else _BASELINE
+ problems: list[str] = []
+ advisories: list[str] = []
+ total = 0
+ for rel in sorted(hits):
+ found = hits[rel]
+ allowed = baseline.get(rel)
+ if allowed is not None and len(found) <= allowed:
+ if len(found) < allowed:
+ advisories.append(f"{rel}: {len(found)} literal /tmp path(s) left, _BASELINE says {allowed}")
+ continue
+ for lineno, line in found:
+ total += 1
+ problems.append(f"{rel}:{lineno}: {line.strip()[:160]}")
+ for rel in sorted(baseline):
+ if rel not in hits:
+ advisories.append(f"{rel}: listed in _BASELINE but clean (or gone)")
+ if advisories:
+ print("advisory — _BASELINE in scripts/check_no_tmp_literals.py is stale; regenerate it with "
+ "--print-baseline (fewer hits than listed is progress, not a failure):")
+ print("\n".join(" " + a for a in advisories))
+ if args.strict_baseline and advisories:
+ problems.extend(advisories)
+
+ if not problems:
+ print("no literal /tmp paths outside the baseline")
+ return 0
+ print("\n".join(problems))
+ print(
+ f"\n{total} literal /tmp path(s) flagged. Resolve scratch space through "
+ f"hermes_constants.get_scratch_dir() (or $TMPDIR / tempfile, which Hermes points there), tell the "
+ f"model to do the same in skills and prompts, or mark a deliberate line with `{MARKER} — <why>` (same line or the line above). "
+ f"See scripts/check_no_tmp_literals.py."
+ )
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/scripts/test_check_no_tmp_literals.py b/tests/scripts/test_check_no_tmp_literals.py
new file mode 100644
index 00000000000..e700a5e32c9
--- /dev/null
+++ b/tests/scripts/test_check_no_tmp_literals.py
@@ -0,0 +1,155 @@
+"""scripts/check_no_tmp_literals.py: literal /tmp paths are flagged; idioms, comments, markers and tests are not."""
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "check_no_tmp_literals.py"
+
+
+def _load():
+ spec = importlib.util.spec_from_file_location("check_no_tmp_literals", SCRIPT)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+def _hits(text: str, suffix: str = ".py") -> list[int]:
+ return [lineno for lineno, _ in _load()._iter_lines_with_hits(text, suffix)]
+
+
+ "line",
+ [
+ 'STORAGE_DIR = "/tmp/hermes-results"',
+ 'return "/tmp"',
+ "LOG=/tmp/pinggy.log",
+ 'cwd="/tmp"',
+ "Save the file to `/tmp/report.pdf` and return it.",
+ 'workdir="/tmp/issue-78"',
+ "--output=/tmp/x.json",
+ "Auto-allow workspace and /tmp edits",
+ ],
+)
+def test_literal_tmp_paths_are_flagged(line):
+ assert _hits(line, ".md") == [1]
+
+
+ "line",
+ [
+ 'SOCKET_DIR="${TMPDIR:-/tmp}/hermes"', # shell fallback idiom
+ 'Path("/var/tmp")',
+ 'Path("/private/tmp")',
+ "mounted as tmpfs",
+ "tmp_path / 'x'",
+ "~/tmp/scratch",
+ "cd ./tmp && ls",
+ "C:\\\\Users\\\\x\\\\tmp",
+ "a/tmp/b",
+ "the tmp dir",
+ ],
+)
+def test_non_tmp_tokens_are_not_flagged(line):
+ assert _hits(line, ".md") == []
+
+
+def test_python_comments_and_docstrings_are_exempt_but_strings_are_not():
+ src = (
+ '"""Module docstring mentions /tmp on purpose.\n'
+ "\n"
+ "More /tmp here too.\n"
+ '"""\n'
+ "# a comment about /tmp\n"
+ 'PROMPT = "write scratch files to /tmp/out" # trailing comment: /tmp\n'
+ "def f():\n"
+ ' """Function docstring: /tmp"""\n'
+ ' return "/tmp"\n'
+ 'HASH_IN_STRING = "not a comment # /tmp"\n'
+ )
+ assert _hits(src, ".py") == [6, 9, 10]
+
+
+def test_js_and_shell_comments_are_exempt():
+ assert _hits("// world-shared /tmp dir\nconst p = '/tmp/x'\n", ".ts") == [2]
+ assert _hits("const p = 1 // see /tmp\n", ".ts") == []
+ assert _hits("#!/bin/sh\n# stage under /tmp\nLOG=/tmp/x.log\n", ".sh") == [3]
+
+
+def test_markdown_prose_is_not_exempt():
+ assert _hits("Frames are written to `/tmp` during capture.\n", ".md") == [1]
+
+
+def test_inline_marker_on_same_or_previous_line_allows_one_hit():
+ mod = _load()
+ src = (
+ f'Path("/tmp").resolve() # {mod.MARKER} — macOS alias check\n'
+ f"<!-- {mod.MARKER} — explains the anti-pattern -->\n"
+ "Never write to /tmp on Termux.\n"
+ 'STILL = "/tmp/bad"\n'
+ )
+ assert _hits(src, ".md") == [4]
+
+
+def test_scan_skips_tests_lockfiles_ci_and_translations(tmp_path):
+ mod = _load()
+ files = {
+ "tools/a.py": 'X = "/tmp/a"\n',
+ "skills/x/SKILL.md": "save to /tmp/out\n",
+ "website/docs/guide.md": "cd /tmp\n",
+ "website/i18n/zh/guide.md": "cd /tmp\n",
+ "tests/test_a.py": 'X = "/tmp/a"\n',
+ "tools/test_inline.py": 'X = "/tmp/a"\n',
+ "tools/conftest.py": 'X = "/tmp/a"\n',
+ "app/src/__tests__/a.ts": "const p = '/tmp'\n",
+ "app/src/a.test.ts": "const p = '/tmp'\n",
+ "app/src/a.ts": "const p = '/tmp'\n",
+ ".github/workflows/ci.yml": "run: echo > /tmp/x\n",
+ "Dockerfile": "RUN tar -C /tmp\n",
+ "package-lock.json": '"resolved": "/tmp"\n',
+ "node_modules/x/index.js": "'/tmp'\n",
+ "evals/e.py": '"/tmp"\n',
+ "vendor.rs": 'let p = "/tmp";\n',
+ }
+ for rel, text in files.items():
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text, encoding="utf-8")
+ hits = mod.scan(root=tmp_path)
+ assert sorted(hits) == ["app/src/a.ts", "skills/x/SKILL.md", "tools/a.py", "website/docs/guide.md"]
+ assert all(len(v) == 1 for v in hits.values())
+
+
+def test_baseline_entries_are_burned_down_not_grown(tmp_path, monkeypatch, capsys):
+ mod = _load()
+ (tmp_path / "tools").mkdir()
+ (tmp_path / "tools" / "a.py").write_text('X = "/tmp/a"\nY = "/tmp/b"\n', encoding="utf-8")
+ (tmp_path / "tools" / "clean.py").write_text("X = 1\n", encoding="utf-8")
+ monkeypatch.setattr(mod, "ROOT", tmp_path)
+
+ monkeypatch.setattr(mod, "_BASELINE", {"tools/a.py": 2})
+ assert mod.main([]) == 0
+
+ monkeypatch.setattr(mod, "_BASELINE", {"tools/a.py": 1}) # grew: the new line is reported
+ assert mod.main([]) == 1
+ assert "tools/a.py:1" in capsys.readouterr().out
+
+ monkeypatch.setattr(mod, "_BASELINE", {"tools/a.py": 3}) # shrank: advisory only, strict fails
+ assert mod.main([]) == 0
+ assert "stale" in capsys.readouterr().out
+ assert mod.main(["--strict-baseline"]) == 1
+
+ monkeypatch.setattr(mod, "_BASELINE", {"tools/a.py": 2, "tools/clean.py": 1}) # stale entry
+ assert mod.main([]) == 0
+ assert "tools/clean.py: listed in _BASELINE but clean" in capsys.readouterr().out
+ assert mod.main(["--strict-baseline"]) == 1
+
+ monkeypatch.setattr(mod, "_BASELINE", {"tools/a.py": 2})
+ assert mod.main(["--all"]) == 1 # burn-down view ignores the baseline
+
+
+def test_repo_tree_has_no_hits_outside_the_baseline():
+ """What CI runs: every literal /tmp in the tree is either marked or listed in _BASELINE."""
+ mod = _load()
+ assert mod.main([]) == 0