From 32042bccdc157f2becfc970ea8f886ee8f754ba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Sat, 21 Nov 2026 12:46:10 +0100 Subject: [PATCH 1/4] Add an escape-hatch ratchet and a .ub/ tamper guard ub ratchet counts lint suppressions, coverage exclusions, and skipped tests in every file Git lists, and fails when a count grows past the human-owned .ub/ratchet. ub check runs it first and keeps running the other gates. ub init writes .ub/ratchet when it is absent. ub ratchet --guard --base REF fails when commits change .ub/check, delete .ub/ratchet, or raise a count, and on uncommitted .ub/ edits. The pre-push hook runs it from the installed ub for each pushed branch. The Stop hook warns the human when .ub/ has uncommitted changes. --- README.md | 104 +++++++- scripts/smoke-release.sh | 4 +- src/ub_cli/check.py | 16 +- src/ub_cli/cli.py | 21 +- src/ub_cli/hooks.py | 95 +++++-- src/ub_cli/project.py | 13 +- src/ub_cli/ratchet.py | 311 +++++++++++++++++++++++ src/ub_cli/skills/ub-mode/SKILL.md | 3 + tests/test_check.py | 12 + tests/test_project.py | 132 +++++++++- tests/test_ratchet.py | 385 +++++++++++++++++++++++++++++ 11 files changed, 1054 insertions(+), 42 deletions(-) create mode 100644 src/ub_cli/ratchet.py create mode 100644 tests/test_ratchet.py diff --git a/README.md b/README.md index 31e851f..b103171 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,8 @@ ub init -s src Use the source directory for your project, repeat `-s` for multiple trees, or omit it to check the whole project. `ub init` creates an executable `.ub/check` -that runs `ub check`, adds a managed instruction block to `AGENTS.md` and +that runs `ub check`, writes `.ub/ratchet` with the current escape-hatch counts +(see [Escape-hatch ratchet](#escape-hatch-ratchet)) unless one exists, adds a managed instruction block to `AGENTS.md` and `CLAUDE.md`, and ignores generated metrics and mutation-worker directories. It does not run tests or install hooks. Review and commit these files so new agent sessions and teammates use the same workflow. Other instructions are @@ -111,7 +112,11 @@ Repeat `--target` to select several hooks. Installation is explicit and repeatab be on the PATH used by Git and your agent. Installation from a subdirectory uses the Git worktree root. `--root PATH` selects another repository. -The Git hook runs `.ub/check` first, then the existing shell hook, preserving its +The Git hook first runs `ub ratchet --guard` on each pushed branch (see +[Escape-hatch ratchet](#escape-hatch-ratchet)). The guard runs from the +installed `ub`, not from `.ub/check`, which the pushed commits could edit. Hooks +installed by earlier releases lack the guard; rerun `ub hooks install` to +upgrade the block. The hook then runs `.ub/check`, then the existing shell hook, preserving its path, arguments, stdin, and failing exit status. A copy of the original is kept beside it as `pre-push.ub-original`. Git's configured `core.hooksPath` is respected when it is inside the repository; external shared directories and @@ -181,6 +186,97 @@ ran a line (the message names the custom or Python coverage command that ran), and when a path or filter argument matches no source file (except with `--changed`). A bare run on a project without source files still exits 0. +## Escape-hatch ratchet + +Agents can pass a gate by switching a check off instead of fixing the code. +`ub ratchet` counts those escape hatches in every file Git tracks or would +track (`git ls-files -co --exclude-standard`), tests included, whatever `-s` +selects. Each kind has its own count: + +| Language | Keys | +| --- | --- | +| Python | `lint.noqa` (also `# ruff: noqa`, `# flake8: noqa`, any case), `lint.type_ignore` (also `# mypy: ignore-errors`), `lint.pyright_ignore` (also `# pyright: basic`), `coverage.pragma_no_cover`, `skip.unittest` (`@unittest.skip`, `@skipIf`, `@skipUnless`, `@expectedFailure`, `self.skipTest(`, `SkipTest(`), `skip.pytest` (`mark.skip`, `mark.skipif`, `mark.xfail`, `pytest.skip(`, `pytest.xfail(`, `pytest.importorskip(`) | +| JS/TS, Vue, Svelte | `lint.eslint_disable`, `lint.ts_ignore`, `lint.ts_expect_error`, `lint.ts_nocheck`, `lint.biome_ignore`, `coverage.istanbul_ignore`, `coverage.c8_ignore`, `coverage.v8_ignore`, `skip.js` (`.skip`, `.only`, `.todo`, `.fixme`, `.fails`, `.skipIf` on `describe`/`it`/`test`/`suite`/`context`, `xit(`, `fit(`, `xdescribe(`, `fdescribe(`, `this.skip(`) | +| Java | `skip.no_mutate_tag` (`@Tag("no-mutate")`, which the mutation tests exclude) | + +Lint and coverage patterns match only in comments; skips match decorator and +call syntax. Python string literals are blanked before matching, so a quoted +directive does not count. Each occurrence counts, including two on one line. +Symlinks are not followed. + +`.ub/ratchet` sits at the Git worktree root and holds one `key count` line per +kind. `ub check` runs the ratchet before coverage and fails when any count +exceeds its line, listing every current `file:line` of that kind (the file +stores counts, not locations); the other gates still run and report. Equal or +lower counts pass. Without `.ub/ratchet` the counts are report-only, and outside +a Git repository the ratchet is skipped. A malformed or symlinked `.ub/ratchet`, +or a failed file listing, makes the check incomplete. `ub ratchet` runs the +same comparison alone. + +The counts belong to a human. After removing escape hatches, or to accept a new +one, run `ub ratchet --update` and commit the file. The managed agent +instructions tell agents never to run it or edit `.ub/` unless asked. + +`ub ratchet --guard --base REF [--head REF]` fails when the commits since the +merge base of the head (default `HEAD`) and `REF` change `.ub/check` (content +or mode), delete `.ub/ratchet`, or raise any of its counts, and when the +worktree's `.ub/check` or `.ub/ratchet` differs from `HEAD`. Adding them to a +repository that had none, and lowering counts, pass. Set `UB_ALLOW_UB_CHANGE=1` +to accept a reviewed change. The guard exits 2 when it cannot find the merge +base, as in a shallow clone, or when a committed `.ub/ratchet` is malformed or +not a regular file. Run it in CI as a separate step, not through `.ub/check`, +with full history: + +```yaml +on: + pull_request: + # labeled and unlabeled rerun the guard when a human adds the approval label. + types: [opened, synchronize, reopened, labeled, unlabeled] +# ... +- uses: actions/checkout@v4 + with: + fetch-depth: 0 +- run: ub ratchet --guard --base origin/main + env: + # A human approves a .ub/ change by labelling the pull request. + UB_ALLOW_UB_CHANGE: ${{ contains(github.event.pull_request.labels.*.name, 'ub-change') && '1' || '' }} +- run: ./.ub/check +``` + +The pre-push hook guards each pushed branch against the remote's default +branch (`refs/remotes//HEAD`), as CI does, or, without one, against the +remote's copy of the branch or the branch's upstream. With none of these it +exits 2 and asks for `git remote set-head --auto`, unless the remote +has no known branches yet, when it skips the guard with a note. The local hook +is advisory: an agent can skip it with `--no-verify`, set the override, or +change Git config. An agent that edits the CI workflow can remove the CI steps. +Put `/.ub/` and `/.github/workflows/` under +[CODEOWNERS](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) +with required review; that review is the human gate. The Stop hook also warns +the human, without blocking, when `.ub/` has staged, unstaged, or untracked +changes, or files that differ from `HEAD`. + +Known limits: + +- Moving an escape hatch, by removing one and adding another of the same kind, + keeps the count. So does widening one, such as `# noqa: E501` to `# noqa`. +- Configuration-file hatches are not counted: per-file lint ignores, coverage + `omit`, pytest `addopts`, `collect_ignore`, `tsconfig` strictness. +- A directive inside a multi-line block comment, after its first line, is missed. +- Outside Python, strings and comments are not parsed: a quoted directive or a + commented-out skip in JS/TS or Java counts. +- The Stop hook keeps the last 8,000 bytes of output, so a very long list of + matches can push the kind and counts out of the agent's view. +- Deleting a failing test and passing extra arguments to `./.ub/check` are not + detected. +- Go, Rust, and Clojure patterns are not yet counted. + +| `ub ratchet` status | Meaning | +| --- | --- | +| 0 | No count above `.ub/ratchet`, or the guard found no loosening (or `UB_ALLOW_UB_CHANGE=1`). | +| 1 | A count grew, or the guard found `.ub/check` changed, `.ub/ratchet` deleted, a count raised, or uncommitted `.ub/` changes. | +| 2 | Usage error, a malformed or symlinked `.ub/ratchet`, a failed file listing, `--update` outside Git, or no merge base for the guard. | + ## Combined gate `ub check` checks the whole project, or the trees named with `-s PATH`. It @@ -205,8 +301,8 @@ mutant log, and to stream the coverage command's output. | Status | Meaning | | --- | --- | | 0 | All gates passed. | -| 1 | A function scored CRAP ≥ 10, a pair scored similarity ≥ 0.8, or a mutation site was uncovered or survived. | -| 2 | The check was incomplete, including missing coverage, coverage with no executed lines, a failing baseline, or a usage error. | +| 1 | A function scored CRAP ≥ 10, a pair scored similarity ≥ 0.8, a mutation site was uncovered or survived, or an escape-hatch count exceeded `.ub/ratchet`. | +| 2 | The check was incomplete, including missing coverage, coverage with no executed lines, a failing baseline, a malformed `.ub/ratchet`, or a usage error. | The tools write their native reports to `.metrics/crap.edn`, `.metrics/dry.edn`, and `.metrics/mutate/`. Standalone commands retain their upstream exit codes, diff --git a/scripts/smoke-release.sh b/scripts/smoke-release.sh index 94f313a..2459bdb 100755 --- a/scripts/smoke-release.sh +++ b/scripts/smoke-release.sh @@ -45,7 +45,9 @@ git init -q "$ub" hooks install --target git --target codex --target claude .git/hooks/pre-push origin unused hook-result.json -grep -qx '{}' hook-result.json +# The uncommitted .ub/ earns a notice to the human, not a block. +grep -q 'review .ub/ before committing' hook-result.json +if grep -q '"decision"' hook-result.json; then exit 1; fi # A test-only change must turn the previously killed mutant into a survivor. printf '%s\n' 'import unittest' 'class Tests(unittest.TestCase):' ' def test_weak(self): pass' > test_arithmetic.py status=0 diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index f64104c..93d1b8b 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -12,6 +12,7 @@ import tempfile from pathlib import Path +from ub_cli.ratchet import gate as ratchet_gate from ub_cli.vendor.crapper.coverage import _profile_segments, load_bundle from ub_cli.vendor.crapper.crap import make_entry, sort_entries from ub_cli.vendor.crapper.discover import iter_source_files, language_of @@ -498,17 +499,21 @@ def _mutation_gate(root: Path, files, bundle, runner, baselines, options): return failures, incomplete -def _gates(root: Path, files, duplicates_files, options, coverage_log: str, ran) -> int: +def _gates(root: Path, files, duplicates_files, options, coverage_log: str, ran, held) -> int: + """Run the CRAP, duplication, and mutation gates after the ratchet's `held` results.""" + runner = FocusedRunner() baselines = _baselines(root, files, runner, options.test_command) bundle = load_bundle(root) failures, incomplete = _static_gates( root, files, duplicates_files, bundle, options, coverage_log, ran ) + held_failures, held_incomplete = held + failures = held_failures + failures if incomplete: - return _verdict(failures, incomplete) + return _verdict(failures, held_incomplete + incomplete) mutation_failures, incomplete = _mutation_gate(root, files, bundle, runner, baselines, options) - return _verdict(failures + mutation_failures, incomplete) + return _verdict(failures + mutation_failures, held_incomplete + incomplete) def _check(options, ran: list[str]) -> int: @@ -517,16 +522,17 @@ def _check(options, ran: list[str]) -> int: raise ValueError(f"Project root is not a directory: {root}") for path in restore_backups(root): print(f"Restored {path} from an interrupted mutation.", file=sys.stderr) + held = ratchet_gate(root) roots = [(root / source).resolve() for source in options.source_root] or [root] files = iter_source_files(roots) duplicates_files = dry_files(roots) if not files and not duplicates_files: raise ValueError("No supported source files found.") if options.use_existing_coverage: - return _gates(root, files, duplicates_files, options, "", ran) + return _gates(root, files, duplicates_files, options, "", ran, held) coverage_log, stale = _generate_coverage(root, files, options) with _set_aside(stale): - return _gates(root, files, duplicates_files, options, coverage_log, ran) + return _gates(root, files, duplicates_files, options, coverage_log, ran, held) def run(argv: list[str] | None = None) -> int: diff --git a/src/ub_cli/cli.py b/src/ub_cli/cli.py index 9ee7bbc..468c92a 100644 --- a/src/ub_cli/cli.py +++ b/src/ub_cli/cli.py @@ -1,5 +1,6 @@ """Dispatch ub commands to the engines and the ub-only tools.""" +from importlib import import_module from importlib.metadata import version import sys @@ -8,7 +9,8 @@ crap Score function complexity and test coverage dry Find structurally similar code mutate Test whether mutations are caught - check Enforce all three ub-mode gates + check Enforce all three ub-mode gates and the escape-hatch ratchet + ratchet Count escape hatches against .ub/ratchet, or guard .ub/ changes init Set up repository quality checks and agent instructions hooks Install Git and agent hooks for the repository skill Install a bundled agent skill @@ -19,6 +21,9 @@ """ ENGINES = {"crap": "crapper", "dry": "dryer", "mutate": "mutator"} +# Each command's module, imported on use. +COMMANDS = {"update": "update", "skill": "skill", "check": "check", "ratchet": "ratchet", + "init": "project", "hooks": "hooks"} def run(argv: list[str]) -> int: @@ -44,20 +49,10 @@ def run(argv: list[str]) -> int: from ub_cli.engines import run as run_engine return run_engine(command, ENGINES[command], args) - if command == "update": - from ub_cli.update import run as execute - elif command == "skill": - from ub_cli.skill import run as execute - elif command == "check": - from ub_cli.check import run as execute - elif command == "init": - from ub_cli.project import run as execute - elif command == "hooks": - from ub_cli.hooks import run as execute - else: + if command not in COMMANDS: print(f"Unknown command: {command}\nRun ub --help for usage.", file=sys.stderr) return 2 - return execute(args) + return import_module(f"ub_cli.{COMMANDS[command]}").run(args) def main() -> None: diff --git a/src/ub_cli/hooks.py b/src/ub_cli/hooks.py index ed2509b..6cccc17 100644 --- a/src/ub_cli/hooks.py +++ b/src/ub_cli/hooks.py @@ -13,13 +13,45 @@ from ub_cli.project import git, local_file, repository, write_file -GIT_CHECK = '''# ub:begin +LEGACY_GIT_CHECK = '''# ub:begin ( ub_check_root=$(git rev-parse --show-toplevel) || exit $? "$ub_check_root/.ub/check" "$ub_refs" || exit $? +( + ub_check_root=$(git rev-parse --show-toplevel) || exit $? + ub_default=$(git rev-parse --verify -q "refs/remotes/$1/HEAD") || ub_default= + ub_known=$(git for-each-ref --count=1 --format=known "refs/remotes/$1/") + while read -r ub_local ub_sha ub_remote ub_remote_sha; do + case $ub_remote in refs/heads/*) ;; *) continue ;; esac + case $ub_sha in *[!0]*) ;; *) continue ;; esac + ub_base=$ub_default + case $ub_remote_sha in *[!0]*) ub_base=${ub_base:-$ub_remote_sha} ;; esac + [ -n "$ub_base" ] || ub_base=$(git rev-parse --verify -q "$ub_local@{upstream}") || ub_base= + if [ -z "$ub_base" ] && [ -n "$ub_known" ]; then + echo "ub: no base to guard $ub_remote; run: git remote set-head $1 --auto" >&2 + exit 2 + elif [ -z "$ub_base" ]; then + echo "ub: $1 has no known branches; skipping the .ub/ tamper guard." >&2 + continue + fi + ub ratchet --root "$ub_check_root" --guard --base "$ub_base" --head "$ub_sha" None: raise ValueError(f"Cannot wrap a symlink or non-file hook: {hook}") original = hook.read_text() if hook.exists() else "" if "# ub:begin" in original or "# ub:end" in original: + if original.count(LEGACY_GIT_CHECK) == 1: + write_file(hook, original.replace(LEGACY_GIT_CHECK, GIT_CHECK), 0o755) + return if original.count(GIT_CHECK) != 1: raise ValueError(f"Edited UB hook block needs review: {hook}") hook.chmod(0o755) @@ -156,26 +191,52 @@ def check_output(root: Path, timeout: int) -> tuple[int, str]: return code, output.read().decode(errors="replace") +UB_CHANGED = "ub config has uncommitted changes: review .ub/ before committing." + + +def stop_decision(payload, timeout: int) -> dict: + if not isinstance(payload, dict): + raise ValueError("Expected a hook event JSON object.") + if payload.get("stop_hook_active") is True: + return {"systemMessage": "UB continuation guard: report any unresolved check failures."} + cwd = payload.get("cwd") + if not isinstance(cwd, str) or not cwd: + raise ValueError("Hook event is missing cwd.") + code, output = check_output(repository(Path(cwd)), timeout) + if code == 0: + return {} + return {"decision": "block", + "reason": f"UB checks failed (exit {code}). Fix failures within the task scope or report the blocker.\n{output}"} + + +def ub_changed(payload) -> bool: + """Whether .ub/ has staged, unstaged, or untracked changes, or files that differ from HEAD. + + Unknown counts as no. + """ + + from ub_cli.ratchet import uncommitted + + try: + root = repository(Path(payload["cwd"])) + return bool(git(root, "status", "--porcelain", "--", ".ub/") or uncommitted(root)) + except (KeyError, TypeError, OSError, ValueError): + return False + + def run_stop(timeout: int) -> int: + payload = changed = None try: payload = json.load(sys.stdin) - if not isinstance(payload, dict): - raise ValueError("Expected a hook event JSON object.") - if payload.get("stop_hook_active") is True: - print(json.dumps({"systemMessage": "UB continuation guard: report any unresolved check failures."})) - return 0 - cwd = payload.get("cwd") - if not isinstance(cwd, str) or not cwd: - raise ValueError("Hook event is missing cwd.") - root = repository(Path(cwd)) - code, output = check_output(root, timeout) - if code == 0: - print("{}") - return 0 - reason = f"UB checks failed (exit {code}). Fix failures within the task scope or report the blocker.\n{output}" + # Before the check runs, which could rewrite .ub/. + changed = ub_changed(payload) + decision = stop_decision(payload, timeout) except (OSError, ValueError, subprocess.SubprocessError) as exc: - reason = f"UB checks could not run: {exc}" - print(json.dumps({"decision": "block", "reason": reason})) + decision = {"decision": "block", "reason": f"UB checks could not run: {exc}"} + if changed: + # Warn the human only: the pre-push guard and CI enforce. + decision["systemMessage"] = " ".join(filter(None, [decision.get("systemMessage"), UB_CHANGED])) + print(json.dumps(decision)) return 0 diff --git a/src/ub_cli/project.py b/src/ub_cli/project.py index b89d664..7a7684b 100644 --- a/src/ub_cli/project.py +++ b/src/ub_cli/project.py @@ -1,6 +1,7 @@ """Set up a repository's shared quality command and agent instructions.""" import argparse +import os from pathlib import Path import shlex import subprocess @@ -18,6 +19,9 @@ Use `ub COMMAND --help` for focused diagnostics. `--changed` selects working-tree changes, not the committed changes in a pull request. Do not weaken the check, skip hooks, or claim success without a passing run. +`.ub/ratchet` caps lint suppressions, coverage exclusions, and skipped tests; +remove the new escape hatch instead. Never run `ub ratchet --update` or edit +`.ub/` unless the user asks. """ @@ -73,6 +77,8 @@ def write_file(path: Path, data: str, mode: int | None = None) -> None: def initialize(options) -> None: + from ub_cli.ratchet import ratchet_file, render, scan, tally, toplevel + root = options.root.resolve() if not root.is_dir(): raise ValueError(f"Project root is not a directory: {root}") @@ -97,6 +103,11 @@ def initialize(options) -> None: raise ValueError(".ub/check already differs; edit it directly to change the project commands.") script = check.read_text() pending = {check: (script, 0o755)} + top = toplevel(root) + ratchet = top and ratchet_file(top) + if ratchet and not ratchet.exists(): + pending[ratchet] = (render(tally(scan(top))), None) + generated = [".ub/check"] + ([os.path.relpath(ratchet, root)] if ratchet else []) for name in ("AGENTS.md", "CLAUDE.md", ".gitignore"): path = local_file(root, name) text = path.read_text() if path.exists() else "" @@ -108,7 +119,7 @@ def initialize(options) -> None: for path, (data, mode) in pending.items(): write_file(path, data, mode) print(f"Ready: {root / '.ub/check'}") - print("Review and commit .ub/check, AGENTS.md, CLAUDE.md, and .gitignore.") + print(f"Review and commit {', '.join(generated)}, AGENTS.md, CLAUDE.md, and .gitignore.") print("Run ./.ub/check locally and in CI after installing the project's test and coverage tools.") print("Optional: ub hooks install (Git pre-push), or --target codex / --target claude.") diff --git a/src/ub_cli/ratchet.py b/src/ub_cli/ratchet.py new file mode 100644 index 0000000..302a364 --- /dev/null +++ b/src/ub_cli/ratchet.py @@ -0,0 +1,311 @@ +"""Count escape hatches and fail when any count grows past .ub/ratchet.""" + +import argparse +import io +from itertools import accumulate +import os +from pathlib import Path +import re +import subprocess +import sys +import tokenize + +from ub_cli.project import git, local_file, write_file + + +RATCHET = ".ub/ratchet" +CHECK = ".ub/check" +OVERRIDE = "UB_ALLOW_UB_CHANGE" +HEADER = "# Escape-hatch counts. ub check fails when one grows. Only a human lowers or raises them.\n" +REGULAR = ("100644", "100755") + +PYTHON = (".py", ".pyi") +SCRIPT = (".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".vue", ".svelte") +JS_COMMENT = r"(?://|/\*+)\s*" +JS_TEST = r"\b(?:describe|it|test|suite|context)(?:\s*\.\s*concurrent)?\s*\.\s*" + +# One row per kind: its key, the file extensions it applies to, and a pattern anchored +# to comment, decorator, or call syntax. Each match counts once. In Python, `skip.` +# rules see code only and the others see code and comments (see `views`). +# Add a language by adding rows. +PATTERNS = [ + ("lint.noqa", PYTHON, r"(?i:#\s*(?:(?:ruff|flake8)\s*:\s*)?noqa)\b"), + ("lint.type_ignore", PYTHON, r"#\s*(?:type:\s*ignore|mypy:\s*ignore-errors)\b"), + ("lint.pyright_ignore", PYTHON, r"#\s*pyright:\s*(?:ignore|basic)\b"), + ("coverage.pragma_no_cover", PYTHON, r"(?i:#\s*pragma[:\s]?\s*no\s*cover)"), + ("skip.unittest", PYTHON, + r"^\s*@\s*(?:unittest\s*\.\s*)?(?:skip(?:If|Unless)?|expectedFailure)\b|\.\s*skipTest\s*\(|\bSkipTest\s*\("), + ("skip.pytest", PYTHON, + r"\b(?:pytest\s*\.\s*)?mark\s*\.\s*(?:skip|skipif|xfail)\b|\bpytest\s*\.\s*(?:skip|xfail|importorskip)\s*\("), + ("lint.eslint_disable", SCRIPT, JS_COMMENT + r"eslint-disable"), + ("lint.ts_ignore", SCRIPT, JS_COMMENT + r"@ts-ignore\b"), + ("lint.ts_expect_error", SCRIPT, JS_COMMENT + r"@ts-expect-error\b"), + ("lint.ts_nocheck", SCRIPT, JS_COMMENT + r"@ts-nocheck\b"), + ("lint.biome_ignore", SCRIPT, JS_COMMENT + r"biome-ignore\b"), + ("coverage.istanbul_ignore", SCRIPT, JS_COMMENT + r"istanbul\s+ignore\b"), + ("coverage.c8_ignore", SCRIPT, JS_COMMENT + r"c8\s+ignore\b"), + ("coverage.v8_ignore", SCRIPT, JS_COMMENT + r"v8\s+ignore\b"), + ("skip.js", SCRIPT, + JS_TEST + r"(?:skip|only|todo|fixme|fails|skipIf)\b|(? Path | None: + try: + return Path(git(root, "rev-parse", "--show-toplevel")).resolve() + except (OSError, ValueError): + return None + + +def scan(top: Path) -> dict[str, list[str]]: + """Each kind's `file:line` matches in the files Git tracks or would track under `top`.""" + + command = ["git", "-C", str(top), "ls-files", "-z", "-co", "--exclude-standard"] + listing = subprocess.run(command, capture_output=True) + if listing.returncode: + raise ValueError(f"git ls-files failed: {listing.stderr.decode(errors='replace').strip()}") + found = {key: [] for key, _, _ in RULES} + # A conflicted index lists a path once per stage. + for name in dict.fromkeys(filter(None, listing.stdout.split(b"\0"))): + shown = name.decode(errors="replace") + rules = [(key, pattern) for key, suffixes, pattern in RULES if shown.endswith(suffixes)] + path = top / os.fsdecode(name) + # A path that resolves elsewhere passes through a symlink, which is not followed. + if rules and path.is_file() and path.resolve() == path: + _scan_file(path, shown, rules, found) + return found + + +def views(path: Path) -> tuple[list[str], list[str]]: + """The file's lines for directive rules and for skip rules. + + In Python, string literals are blanked from both, so quoted directives do not count, + and comments are blanked from the second, so a commented-out skip does not count. + """ + + text = path.read_text(encoding="utf-8", errors="replace") + lines = io.StringIO(text).readlines() + if path.suffix not in PYTHON: + return lines, lines + try: + tokens = list(tokenize.generate_tokens(io.StringIO(text).readline)) + except (tokenize.TokenError, SyntaxError): + return lines, lines + return blank(text, lines, tokens, STRINGS), blank(text, lines, tokens, STRINGS | {tokenize.COMMENT}) + + +def blank(text: str, lines: list[str], tokens, types: set[int]) -> list[str]: + starts = list(accumulate(map(len, lines), initial=0)) + pieces, last = [], 0 + for token in tokens: + if token.type in types: + start = starts[token.start[0] - 1] + token.start[1] + end = starts[token.end[0] - 1] + token.end[1] + pieces += [text[last:start], re.sub(r"[^\n]", " ", text[start:end])] + last = end + return io.StringIO("".join(pieces) + text[last:]).readlines() + + +def _scan_file(path: Path, name: str, rules, found: dict[str, list[str]]) -> None: + directives, code = views(path) + for number, (directive_line, code_line) in enumerate(zip(directives, code), 1): + for key, pattern in rules: + line = code_line if key.startswith("skip.") else directive_line + found[key] += [f"{name}:{number}"] * len(pattern.findall(line)) + + +def tally(found: dict[str, list[str]]) -> dict[str, int]: + return {key: len(places) for key, places in found.items()} + + +def parse(text: str) -> dict[str, int]: + counts = {} + for number, line in enumerate(text.splitlines(), 1): + words = line.split() + if not words or words[0].startswith("#"): + continue + if len(words) != 2 or not words[1].isdigit(): + raise ValueError(f"{RATCHET} line {number} is not 'key count': {line}") + counts[words[0]] = int(words[1]) + return counts + + +def render(counts: dict[str, int]) -> str: + return HEADER + "".join(f"{key} {counts[key]}\n" for key in sorted(counts)) + + +def grown(current: dict[str, int], baseline: dict[str, int]) -> list[tuple[str, int, int]]: + return [(key, count, baseline.get(key, 0)) for key, count in sorted(current.items()) + if count > baseline.get(key, 0)] + + +def ratchet_file(top: Path) -> Path: + """The worktree's .ub/ratchet, which must be a regular file inside the repository if present.""" + + if (top / RATCHET).is_symlink(): + raise ValueError(f"{RATCHET} must be a regular file, not a symlink.") + return local_file(top, RATCHET) + + +def gate(root: Path) -> tuple[list[str], list[str]]: + """Print the ratchet summary. Return one failure per kind that grew, and incomplete reasons.""" + + top = toplevel(root) + if top is None: + print("Ratchet: skipped outside a Git repository.") + return [], [] + present = os.path.lexists(top / RATCHET) + try: + baseline = parse(ratchet_file(top).read_text()) if present else None + found = scan(top) + except (OSError, ValueError) as exc: + if present: + print("Ratchet: incomplete.") + return [], [f"Ratchet: {exc}"] + print(f"Ratchet: report only without {RATCHET}; counting failed: {exc}") + return [], [] + counts = tally(found) + if baseline is None: + print(f"Ratchet: {sum(counts.values())} escape hatches, report only without {RATCHET}.") + return [], [] + rows = grown(counts, baseline) + if not rows: + lower = any(counts.get(key, 0) < count for key, count in baseline.items()) + hint = "; a human can lower it with ub ratchet --update" if lower else "" + print(f"Ratchet: {sum(counts.values())} escape hatches, none above {RATCHET}{hint}.") + return [], [] + # The ratchet stores counts, not locations, so every current match of a grown kind is listed. + print(f"Ratchet: {len(rows)} kinds above {RATCHET}, with every current match") + failures = [] + for key, now, then in rows: + failures.append(f"{key}: {now} > {then}") + print(f" {failures[-1]}") + print("".join(f" {place}\n" for place in found[key]), end="") + return failures, [] + + +def update(root: Path) -> None: + top = toplevel(root) + if top is None: + raise ValueError("ub ratchet --update needs a Git repository.") + counts = tally(scan(top)) + write_file(ratchet_file(top), render(counts)) + print(f"Wrote {top / RATCHET}: {sum(counts.values())} escape hatches.") + + +def entry(root: Path, revision: str, name: str) -> tuple[str, str] | None: + """The Git mode and object id of `name` at `revision`, or None when absent.""" + + listing = git(root, "ls-tree", "--full-tree", revision, "--", name) + return tuple(listing.split("\t")[0].split()[::2]) if listing else None + + +def worktree_entry(root: Path, name: str) -> tuple[str, str] | None: + path = root / name + if path.is_symlink() or (path.exists() and not path.is_file()): + return ("not a regular file", name) + if not path.exists(): + return None + return ("100755" if os.access(path, os.X_OK) else "100644", git(root, "hash-object", "--", name)) + + +def uncommitted(root: Path) -> list[str]: + """The .ub/ files whose worktree copy, file type, or mode differs from HEAD.""" + + try: + git(root, "rev-parse", "--verify", "-q", "HEAD") + except ValueError: + head = {} + else: + head = {name: entry(root, "HEAD", name) for name in (CHECK, RATCHET)} + return [name for name in (CHECK, RATCHET) if worktree_entry(root, name) != head.get(name)] + + +def committed_counts(root: Path, item: tuple[str, str] | None) -> dict[str, int] | None: + if item is None: + return None + if item[0] not in REGULAR: + raise ValueError(f"Committed {RATCHET} is not a regular file.") + return parse(git(root, "cat-file", "blob", item[1])) + + +def tampering(root: Path, start: str, head: str) -> list[str]: + """How `head`'s .ub/ loosens the gate relative to commit `start`.""" + + problems = [] + check = entry(root, start, CHECK) + if check is not None and check != entry(root, head, CHECK): + problems.append(f"{CHECK} changed") + before = committed_counts(root, entry(root, start, RATCHET)) + after = committed_counts(root, entry(root, head, RATCHET)) + if before is not None and after is None: + problems.append(f"{RATCHET} was deleted") + elif before is not None: + problems += [f"{RATCHET} raised {key}: {then} -> {now}" for key, now, then in grown(after, before)] + return problems + + +def guard(root: Path, base: str, head: str = "HEAD") -> int: + try: + start = git(root, "merge-base", head, base) + except ValueError as exc: + print(f"ub ratchet: no merge base of {head} and {base}: {exc}\n" + "Fetch the base branch with full history (actions/checkout fetch-depth: 0).", + file=sys.stderr) + return 2 + problems = tampering(root, start, head) + [f"{name} has uncommitted changes" for name in uncommitted(root)] + if not problems: + print(f"Guard: {head} does not loosen .ub/ since {base}.") + return 0 + print(f"Guard: {head} against {base}:") + for problem in problems: + print(f" {problem}") + if os.environ.get(OVERRIDE) == "1": + print(f"Guard: allowed by {OVERRIDE}=1.") + return 0 + print(f"Guard failed: .ub/ changes need human review; a human may override with {OVERRIDE}=1.") + return 1 + + +def check(root: Path) -> int: + failures, incomplete = gate(root) + for reason in incomplete: + print(reason, file=sys.stderr) + return 2 if incomplete else 1 if failures else 0 + + +def arguments(argv: list[str]) -> argparse.Namespace: + parser = argparse.ArgumentParser(prog="ub ratchet", description=__doc__) + parser.add_argument("--root", type=Path, default=Path.cwd()) + mode = parser.add_mutually_exclusive_group() + mode.add_argument("--update", action="store_true", help=f"Write the current counts to {RATCHET}") + mode.add_argument("--guard", action="store_true", + help="Fail when commits change .ub/check, delete .ub/ratchet, or raise a count") + parser.add_argument("--base", metavar="REF", help="Compare with the merge base of the head and REF (--guard)") + parser.add_argument("--head", metavar="REF", help="Commit to guard (default: HEAD)") + options = parser.parse_args(argv) + if options.guard != bool(options.base) or (options.head and not options.guard): + parser.error("--guard needs --base REF; --base and --head need --guard.") + return options + + +def run(argv: list[str]) -> int: + try: + options = arguments(argv) + except SystemExit as exc: + return int(exc.code) + try: + root = toplevel(options.root) or options.root.resolve() + if options.guard: + return guard(root, options.base, options.head or "HEAD") + if options.update: + update(root) + return 0 + return check(root) + except (OSError, ValueError) as exc: + print(f"ub ratchet: {exc}", file=sys.stderr) + return 2 diff --git a/src/ub_cli/skills/ub-mode/SKILL.md b/src/ub_cli/skills/ub-mode/SKILL.md index 852207c..6bd3a06 100644 --- a/src/ub_cli/skills/ub-mode/SKILL.md +++ b/src/ub_cli/skills/ub-mode/SKILL.md @@ -30,6 +30,9 @@ Every time you are asked to make a change follow: * A skill describes the workflow; installed hooks and required CI checks enforce it. Do not weaken checks or bypass hooks. Report remaining failures, missing tools, and checks that could not finish without claiming success. +* `.ub/ratchet` caps lint suppressions, coverage exclusions, and skipped tests. + When `ub check` reports a count above it, remove the new escape hatch. Never + run `ub ratchet --update` or edit `.ub/` unless the user asks. * Keep fixes within the requested task. This skill does not authorize unrelated cleanup, commits, or publication. diff --git a/tests/test_check.py b/tests/test_check.py index 32a5a44..73aabed 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -84,6 +84,18 @@ def test_surviving_mutant_fails_the_gate(self): self.assertEqual(1, status, output) self.assertIn("\n src/example.py:2 survived + -> -\n", output) + def test_ratchet_growth_fails_without_stopping_the_other_gates(self): + subprocess.run(["git", "init", "-q", str(self.root)], check=True) + (self.root / ".ub").mkdir() + (self.root / ".ub" / "ratchet").write_text("skip.unittest 0\n") + (self.root / "test_example.py").write_text("@unittest.skip('later')\ndef test(): pass\n") + self.coverage() + status, output = self.run_check("pass") + self.assertEqual(1, status, output) + self.assertIn(" skip.unittest: 1 > 0\n test_example.py:1\n", output) + self.assertIn("\n src/example.py:2 survived + -> -\n", output) + self.assertIn("Gates failed with 2 failing items.", output) + def test_uncovered_site_fails_even_without_survivors(self): self.coverage(hits=0) status, output = self.run_check("pass") diff --git a/tests/test_project.py b/tests/test_project.py index eb8a9b1..3689c78 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -64,6 +64,16 @@ def test_preserves_instructions_and_local_commands_on_repeat(self): self.initialize() self.assertEqual(before, [(p.read_bytes(), p.stat().st_mtime_ns) for p in files]) + def test_writes_the_ratchet_once_and_never_overwrites_it(self): + (self.root / "t.py").write_text("x = 1 # noqa\n") + self.initialize() + ratchet = self.root / ".ub/ratchet" + self.assertIn("\nlint.noqa 1\n", ratchet.read_text()) + ratchet.write_text("lint.noqa 5\n") + self.initialize() + self.assertEqual(ratchet.read_text(), "lint.noqa 5\n") + self.assertIn("ub ratchet --update", (self.root / "AGENTS.md").read_text()) + def test_script_forwards_literal_commands_scope_and_runtime_arguments(self): source = "src ' $cash" (self.root / source).mkdir() @@ -243,9 +253,26 @@ def test_stop_pass_fail_loop_guard_and_subdirectory(self): self.executable(check, "touch ran\nexit 0\n") self.assertNotIn("decision", self.stop({"cwd": str(self.root), "stop_hook_active": True})) self.assertFalse((self.root / "ran").exists()) - self.assertEqual(self.stop(), {}) + self.assertNotIn("decision", self.stop()) self.assertTrue((self.root / "ran").exists()) + def test_stop_warns_the_human_about_uncommitted_ub_changes(self): + check = self.initialize() + self.executable(check, "exit 0\n") + notice = "ub config has uncommitted changes: review .ub/ before committing." + guard = "UB continuation guard: report any unresolved check failures." + active = {"cwd": str(self.root), "stop_hook_active": True} + self.assertEqual(self.stop(), {"systemMessage": notice}) + self.assertEqual(self.stop(active), {"systemMessage": f"{guard} {notice}"}) + self.git("add", ".ub") + self.git("-c", "user.name=UB Test", "-c", "user.email=test@example.invalid", + "commit", "--no-gpg-sign", "-qm", "ub") + self.assertEqual(self.stop(), {}) + self.assertEqual(self.stop(active), {"systemMessage": guard}) + self.executable(check, "exit 1\n") + failure = self.stop() + self.assertEqual((failure["decision"], failure["systemMessage"]), ("block", notice)) + def test_stop_missing_check_bad_event_and_timeout_block(self): self.assertEqual(self.stop()["decision"], "block") self.assertEqual(self.stop({"cwd": 1})["decision"], "block") @@ -280,6 +307,61 @@ def test_real_push_is_blocked_then_succeeds_after_check_passes(self): self.git("push", str(remote), "HEAD:refs/heads/main") self.assertIn("refs/heads/main", self.git("ls-remote", str(remote))) + def test_push_that_raises_the_ratchet_is_refused_unless_a_human_allows_it(self): + check = self.initialize() + self.executable(check, "exit 0\n") + remote = self.root.parent / "remote.git" + self.git("init", "--bare", "-q", str(remote)) + self.git("remote", "add", "origin", str(remote)) + commit = ["-c", "user.name=UB Test", "-c", "user.email=test@example.invalid", + "commit", "--no-gpg-sign", "-qam", "change"] + self.git("add", ".") + self.git(*commit) + self.git("push", "-qu", "origin", "HEAD:main") + self.install() + ratchet = self.root / ".ub/ratchet" + ratchet.write_text(ratchet.read_text().replace("lint.noqa 0", "lint.noqa 1")) + self.git(*commit) + refused = self.command(["git", "push", "-q", "origin", "HEAD:main"]) + self.assertNotEqual(refused.returncode, 0) + self.assertIn("\n .ub/ratchet raised lint.noqa: 0 -> 1\n", refused.stdout + refused.stderr) + allowed = self.command(["git", "push", "-q", "origin", "HEAD:main"], + env=dict(self.env, UB_ALLOW_UB_CHANGE="1")) + self.assertEqual(allowed.returncode, 0, allowed.stderr) + + def test_push_guards_each_pushed_branch_not_the_checked_out_one(self): + check = self.initialize() + self.executable(check, "exit 0\n") + remote = self.root.parent / "remote.git" + self.git("init", "--bare", "-q", str(remote)) + self.git("remote", "add", "origin", str(remote)) + commit = ["-c", "user.name=UB Test", "-c", "user.email=test@example.invalid", + "commit", "--no-gpg-sign", "-qam", "change"] + self.git("add", ".") + self.git(*commit) + self.git("push", "-q", "origin", "HEAD:main") + self.install() + self.git("checkout", "-qb", "tamper") + self.executable(check, "exit 0 # loosened\n") + self.git(*commit) + self.git("checkout", "-q", "-") + unguarded = self.command(["git", "push", "-q", "origin", "tamper"]) + self.assertNotEqual(unguarded.returncode, 0) + self.assertIn("run: git remote set-head origin --auto", unguarded.stderr) + self.git("remote", "set-head", "origin", "main") + refused = self.command(["git", "push", "-q", "origin", "tamper"]) + self.assertNotEqual(refused.returncode, 0) + self.assertIn("\n .ub/check changed\n", refused.stdout) + + def test_install_upgrades_the_previous_hook_block(self): + from ub_cli.hooks import GIT_CHECK, LEGACY_GIT_CHECK + + self.initialize() + hook = self.root / ".git/hooks/pre-push" + self.executable(hook, LEGACY_GIT_CHECK + "echo original\n") + self.install() + self.assertEqual(hook.read_text(), "#!/bin/sh\n" + GIT_CHECK + "echo original\n") + def test_hook_install_works_from_linked_worktree_subdirectory(self): self.git("-c", "user.name=UB Test", "-c", "user.email=test@example.invalid", "commit", "--allow-empty", "--no-gpg-sign", "-qm", "fixture") @@ -314,3 +396,51 @@ def test_timeout_terminates_tests_started_in_a_new_session(self): if status.returncode == 0 and not status.stdout.strip().startswith("Z"): os.killpg(pid, signal.SIGKILL) self.fail(f"Detached test process {pid} survived: {status.stdout}") + + +class StopDecisionTests(RepositoryTests): + def test_decision_covers_continuation_pass_fail_and_bad_events(self): + from ub_cli.hooks import stop_decision + + check = self.initialize() + self.assertEqual(stop_decision({"stop_hook_active": True}, 5), + {"systemMessage": "UB continuation guard: report any unresolved check failures."}) + self.executable(check, "exit 0\n") + self.assertEqual(stop_decision({"cwd": str(self.root)}, 5), {}) + self.executable(check, "echo broken\nexit 3\n") + failure = stop_decision({"cwd": str(self.root)}, 5) + self.assertEqual(failure["decision"], "block") + self.assertTrue(failure["reason"].startswith("UB checks failed (exit 3).")) + self.assertIn("broken", failure["reason"]) + for payload in ([], {"cwd": ""}, {"cwd": 1}): + with self.subTest(payload=payload), self.assertRaises(ValueError): + stop_decision(payload, 5) + self.executable(check, "sleep 20\n") + self.assertIn("exceeded 1s", stop_decision({"cwd": str(self.root)}, 1)["reason"]) + + def test_changed_sees_staged_untracked_and_hidden_edits(self): + from ub_cli.hooks import ub_changed + + commit = ["-c", "user.name=UB Test", "-c", "user.email=test@example.invalid", + "commit", "--no-gpg-sign", "-qm", "ub"] + payload = {"cwd": str(self.root)} + self.assertFalse(ub_changed(payload)) + check = self.initialize() + self.assertTrue(ub_changed(payload)) + self.git("add", ".ub") + self.git(*commit) + self.assertFalse(ub_changed(payload)) + (self.root / ".ub/notes").write_text("x") + self.assertTrue(ub_changed(payload)) + (self.root / ".ub/notes").unlink() + original = check.read_text() + check.write_text(original + "# staged\n") + self.git("add", ".ub/check") + check.write_text(original) + self.assertTrue(ub_changed(payload)) + self.git("reset", "-q", ".ub/check") + self.git("update-index", "--assume-unchanged", ".ub/check") + check.write_text(original + "# hidden\n") + self.assertTrue(ub_changed(payload)) + for bad in (None, {}, {"cwd": 1}, {"cwd": str(self.root.parent)}): + self.assertFalse(ub_changed(bad)) diff --git a/tests/test_ratchet.py b/tests/test_ratchet.py new file mode 100644 index 0000000..213d143 --- /dev/null +++ b/tests/test_ratchet.py @@ -0,0 +1,385 @@ +import contextlib +import io +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +from ub_cli import ratchet + + +PYTHON_SAMPLE = { + "x = 1 # noqa: E501": "lint.noqa", + "x = 1 # NoQA: F401": "lint.noqa", + "# ruff: noqa": "lint.noqa", + "y = f() # type: ignore[attr-defined]": "lint.type_ignore", + "# mypy: ignore-errors": "lint.type_ignore", + "z = g() # pyright: ignore[reportGeneralTypeIssues]": "lint.pyright_ignore", + "# pyright: basic": "lint.pyright_ignore", + "if debug: # pragma: no cover": "coverage.pragma_no_cover", + "else: # PRAGMA NO COVER": "coverage.pragma_no_cover", + '@unittest.skip("slow")': "skip.unittest", + '@skipIf(True, "x")': "skip.unittest", + '@skipUnless(False, "x")': "skip.unittest", + "@unittest.expectedFailure": "skip.unittest", + 'self.skipTest("later")': "skip.unittest", + 'raise unittest.SkipTest("x")': "skip.unittest", + '@pytest.mark.skip(reason="x")': "skip.pytest", + '@pytest.mark.skipif(True, reason="x")': "skip.pytest", + "@mark.xfail": "skip.pytest", + 'pytest.skip("x")': "skip.pytest", + 'pytest.importorskip("numpy")': "skip.pytest", + 'message = "x = 1 # noqa"': None, + "pattern = f'# type: ignore {x}'": None, + "@skipper": None, + "def skip_this(): pass": None, + "@pytest.mark.skipping": None, + "stream.skip(2)": None, + 'self.skipTest ("later")': "skip.unittest", + 'pytest . skip ("later")': "skip.pytest", + "# Document pytest.skip() here.": None, + "# @unittest.skip('old')": None, +} +SCRIPT_SAMPLE = { + "// eslint-disable-next-line no-console": "lint.eslint_disable", + "/* eslint-disable */": "lint.eslint_disable", + "// @ts-ignore": "lint.ts_ignore", + "/** @ts-ignore */": "lint.ts_ignore", + "// @ts-expect-error": "lint.ts_expect_error", + "// @ts-nocheck": "lint.ts_nocheck", + "// biome-ignore lint: reason": "lint.biome_ignore", + "/* istanbul ignore next */": "coverage.istanbul_ignore", + "/* c8 ignore next */": "coverage.c8_ignore", + "/* v8 ignore next */": "coverage.v8_ignore", + 'it.skip("x", () => {})': "skip.js", + 'describe.only("x", () => {})': "skip.js", + 'it.concurrent.skip("x", () => {})': "skip.js", + 'test.todo("x")': "skip.js", + 'test.skipIf(ci)("x", () => {})': "skip.js", + 'xit("x", () => {})': "skip.js", + 'fdescribe("x", () => {})': "skip.js", + "this.skip()": "skip.js", + 'const s = "eslint-disable @ts-ignore"': None, + "stream.skip(2)": None, + "profit(2)": None, + "model.fit(xs, ys)": None, + 'test . skip("later", fn)': "skip.js", + 'fit("x", () => {})': "skip.js", + "x = 1 # noqa": None, +} + + +def git(root, *args): + return subprocess.run(["git", "-C", str(root), *args], check=True, + capture_output=True, text=True).stdout.strip() + + +def call(function, *args): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + result = function(*args) + return result, out.getvalue(), err.getvalue() + + +class RepositoryTest(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name).resolve() / "repo" + self.root.mkdir() + git(self.root, "init", "-q", "-b", "main") + + def write(self, name, text): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + def commit(self): + git(self.root, "add", "-A") + git(self.root, "-c", "user.name=t", "-c", "user.email=t@example.invalid", + "commit", "--no-gpg-sign", "--allow-empty", "-qm", "c") + + +class ScanTests(RepositoryTest): + def test_each_kind_matches_only_its_syntax_and_language(self): + expected = {key: [] for key, _, _ in ratchet.PATTERNS} + for name, sample in (("pkg/a.py", PYTHON_SAMPLE), ("web/b.ts", SCRIPT_SAMPLE)): + self.write(name, "\n".join(sample) + "\n") + for number, key in enumerate(sample.values(), 1): + if key: + expected[key].append(f"{name}:{number}") + self.write("C.java", '@Tag("slow")\n@Tag ( value = "no-mutate" )\n') + expected["skip.no_mutate_tag"].append("C.java:2") + self.write("notes.md", "x # noqa\n") + self.write("ignored.py", "x # noqa\n") + self.write(".gitignore", "ignored.py\n") + self.commit() + (self.root / "web/b.ts").rename(self.root / "web/c.ts") + expected = {key: [place.replace("web/b.ts", "web/c.ts") for place in places] + for key, places in expected.items()} + self.assertEqual(ratchet.scan(self.root), expected) + + def test_python_strings_are_blanked_but_their_lines_still_count(self): + self.write("a.py", 'doc = """\n# noqa\n@unittest.skip\n"""; x = 1 # noqa\ny = 2 # type: ignore\n') + found = ratchet.scan(self.root) + self.assertEqual((found["lint.noqa"], found["skip.unittest"], found["lint.type_ignore"]), + (["a.py:4"], [], ["a.py:5"])) + self.assertEqual(ratchet.views(self.root / "a.py"), + (["doc = \n", " \n", " \n", + " ; x = 1 # noqa\n", "y = 2 # type: ignore\n"], + ["doc = \n", " \n", " \n", + " ; x = 1" + " " * 8 + "\n", "y = 2" + " " * 16 + "\n"])) + + def test_a_conflicted_path_is_scanned_once(self): + self.write("a.py", "x = 1\n") + self.commit() + git(self.root, "checkout", "-qb", "other") + self.write("a.py", "x = 2 # noqa\n") + self.commit() + git(self.root, "checkout", "-q", "main") + self.write("a.py", "x = 3 # noqa\n") + self.commit() + subprocess.run(["git", "-C", str(self.root), "merge", "-q", "other"], capture_output=True) + self.assertIn("a.py\0a.py", subprocess.run(["git", "-C", str(self.root), "ls-files", "-z", "-co"], + capture_output=True, text=True).stdout) + self.assertEqual(len(ratchet.scan(self.root)["lint.noqa"]), 2) + + def test_each_occurrence_counts_and_bad_files_do_not_hide_matches(self): + self.write("a.test.ts", 'it.skip("a"); it.skip("b")\n') + (self.root / "latin.py").write_bytes(b"# caf\xe9\nx = 1 # noqa\n") + self.write("broken.py", 'x = (\n"# noqa" # noqa\n') + found = ratchet.scan(self.root) + self.assertEqual(found["skip.js"], ["a.test.ts:1", "a.test.ts:1"]) + self.assertEqual(found["lint.noqa"], ["broken.py:2", "broken.py:2", "latin.py:2"]) + + def test_symlinks_and_unreadable_names_are_skipped(self): + outside = self.root.parent / "outside.py" + outside.write_text("x = 1 # noqa\n") + (self.root / "link.py").symlink_to(outside) + self.write("pkg/a.py", "") + self.commit() + (self.root / "pkg/a.py").unlink() + (self.root / "pkg").rmdir() + (self.root.parent / "elsewhere").mkdir() + (self.root.parent / "elsewhere/a.py").write_text("x = 1 # noqa\n") + (self.root / "pkg").symlink_to(self.root.parent / "elsewhere") + blob = git(self.root, "hash-object", "-w", str(outside)) + subprocess.run([b"git", b"-C", bytes(self.root), b"update-index", b"--add", b"--cacheinfo", + b"100644," + blob.encode() + b",caf\xe9.py"], check=True) + self.assertEqual(ratchet.scan(self.root)["lint.noqa"], []) + + def test_outside_git_skips_and_listing_errors_are_incomplete(self): + with tempfile.TemporaryDirectory() as outside: + self.assertEqual(call(ratchet.gate, Path(outside))[:2], + (([], []), "Ratchet: skipped outside a Git repository.\n")) + (self.root / ".git/index").write_bytes(b"corrupt") + (failures, incomplete), output, _ = call(ratchet.gate, self.root) + self.assertEqual((failures, incomplete), ([], [])) + self.assertRegex(output, "^Ratchet: report only without .ub/ratchet; counting failed: git ls-files failed: ") + self.write(".ub/ratchet", "lint.noqa 0\n") + (failures, incomplete), output, _ = call(ratchet.gate, self.root) + self.assertEqual((failures, output), ([], "Ratchet: incomplete.\n")) + self.assertRegex(incomplete[0], "^Ratchet: git ls-files failed: .*index") + + +class GateTests(RepositoryTest): + def test_without_a_ratchet_file_reports_only(self): + self.write("t.py", "x # noqa\ny # noqa\n") + self.assertEqual(call(ratchet.gate, self.root)[:2], + (([], []), "Ratchet: 2 escape hatches, report only without .ub/ratchet.\n")) + + def test_growth_fails_with_every_current_location_from_any_directory(self): + self.write("t.py", "x # noqa\n") + call(ratchet.update, self.root) + self.write("t.py", "x # noqa\n@unittest.skip('x')\n" + "z # noqa\n" * 20) + self.write("sub/u.py", "y # noqa\n") + (failures, incomplete), output, _ = call(ratchet.gate, self.root / "sub") + self.assertEqual((failures, incomplete), (["lint.noqa: 22 > 1", "skip.unittest: 1 > 0"], [])) + noqa = "".join(f" {place}\n" for place in ["sub/u.py:1", "t.py:1"] + + [f"t.py:{line}" for line in range(3, 23)]) + self.assertEqual(output, "Ratchet: 2 kinds above .ub/ratchet, with every current match\n" + f" lint.noqa: 22 > 1\n{noqa}" + " skip.unittest: 1 > 0\n t.py:2\n") + + def test_equal_and_lower_counts_pass(self): + self.write("t.py", "x # noqa\n") + self.write(".ub/ratchet", "lint.noqa 1\n") + self.assertEqual(call(ratchet.gate, self.root)[:2], + (([], []), "Ratchet: 1 escape hatches, none above .ub/ratchet.\n")) + self.write(".ub/ratchet", "lint.noqa 1\nretired.kind 1\n") + self.assertEqual(call(ratchet.gate, self.root)[:2], + (([], []), "Ratchet: 1 escape hatches, none above .ub/ratchet; " + "a human can lower it with ub ratchet --update.\n")) + + def test_malformed_or_symlinked_ratchet_is_incomplete(self): + self.write(".ub/ratchet", "lint.noqa many\n") + (_, incomplete), _, _ = call(ratchet.gate, self.root) + self.assertEqual(incomplete, ["Ratchet: .ub/ratchet line 1 is not 'key count': lint.noqa many"]) + (self.root / ".ub/ratchet").unlink() + (self.root / ".ub/ratchet").symlink_to("missing") + (_, incomplete), _, _ = call(ratchet.gate, self.root) + self.assertEqual(incomplete, ["Ratchet: .ub/ratchet must be a regular file, not a symlink."]) + with self.assertRaisesRegex(ValueError, "not a symlink"): + ratchet.update(self.root) + + def test_update_refuses_a_ub_directory_outside_the_repository(self): + outside = self.root.parent / "elsewhere" + outside.mkdir() + (self.root / ".ub").symlink_to(outside) + with self.assertRaisesRegex(ValueError, "outside the project"): + ratchet.update(self.root) + self.assertEqual(list(outside.iterdir()), []) + + def test_update_writes_every_kind_and_round_trips(self): + self.write("t.py", "x # noqa\n") + result, output, _ = call(ratchet.update, self.root) + text = (self.root / ".ub/ratchet").read_text() + self.assertTrue(text.startswith("# ")) + counts = ratchet.parse(text) + self.assertEqual(counts, {key: int(key == "lint.noqa") for key, _, _ in ratchet.PATTERNS}) + self.assertEqual(list(counts), sorted(counts)) + self.assertEqual(output, f"Wrote {self.root / '.ub/ratchet'}: 1 escape hatches.\n") + + def test_parse_skips_comments_and_rejects_malformed_lines(self): + self.assertEqual(ratchet.parse("# note\n\n lint.noqa 2\n"), {"lint.noqa": 2}) + for line in ("lint.noqa", "lint.noqa -1", "lint.noqa 1 2", "lint.noqa x"): + with self.subTest(line=line), self.assertRaisesRegex(ValueError, "line 2 is not 'key count'"): + ratchet.parse("# note\n" + line + "\n") + + +class GuardTests(RepositoryTest): + def setUp(self): + super().setUp() + self.write(".ub/check", "#!/bin/sh\nexec ub check\n") + (self.root / ".ub/check").chmod(0o755) + self.write(".ub/ratchet", "lint.noqa 1\nskip.js 2\n") + self.commit() + git(self.root, "checkout", "-qb", "work") + + def guard(self, override=None, head="HEAD"): + environ = {key: value for key, value in os.environ.items() if key != ratchet.OVERRIDE} + if override: + environ[ratchet.OVERRIDE] = override + with patch.dict(os.environ, environ, clear=True): + return call(ratchet.guard, self.root, "main", head) + + def symlink_same_ratchet(self): + copy = self.root.parent / "ratchet-copy" + copy.write_bytes((self.root / ".ub/ratchet").read_bytes()) + (self.root / ".ub/ratchet").unlink() + (self.root / ".ub/ratchet").symlink_to(copy) + + def test_unchanged_and_lowered_config_passes(self): + self.commit() + self.assertEqual(self.guard()[:2], (0, "Guard: HEAD does not loosen .ub/ since main.\n")) + self.write(".ub/ratchet", "lint.noqa 0\n") + self.commit() + self.assertEqual(self.guard()[0], 0) + + def test_loosening_commits_and_worktree_edits_fail(self): + cases = { + "raise": (lambda: self.write(".ub/ratchet", "lint.noqa 2\nskip.js 2\nskip.pytest 1\n"), True, + [".ub/ratchet raised lint.noqa: 1 -> 2", ".ub/ratchet raised skip.pytest: 0 -> 1"]), + "delete": (lambda: (self.root / ".ub/ratchet").unlink(), True, [".ub/ratchet was deleted"]), + "edit": (lambda: self.write(".ub/check", "#!/bin/sh\nexit 0\n"), True, [".ub/check changed"]), + "mode": (lambda: (self.root / ".ub/check").chmod(0o644), True, [".ub/check changed"]), + "dirty check": (lambda: self.write(".ub/check", "#!/bin/sh\nexit 0\n"), False, + [".ub/check has uncommitted changes"]), + "dirty ratchet": (lambda: (self.root / ".ub/ratchet").unlink(), False, + [".ub/ratchet has uncommitted changes"]), + "symlinked ratchet": (self.symlink_same_ratchet, False, [".ub/ratchet has uncommitted changes"]), + } + for name, (change, commit, problems) in cases.items(): + with self.subTest(name): + git(self.root, "reset", "-q", "--hard", "main") + change() + if commit: + self.commit() + code, output, _ = self.guard() + self.assertEqual(code, 1) + lines = output.splitlines() + self.assertEqual(lines[0], "Guard: HEAD against main:") + self.assertEqual(lines[1:-1], [f" {problem}" for problem in problems]) + self.assertIn(ratchet.OVERRIDE, lines[-1]) + code, output, _ = self.guard("1") + self.assertEqual(code, 0) + self.assertTrue(output.endswith(f"Guard: allowed by {ratchet.OVERRIDE}=1.\n")) + self.assertEqual(self.guard("yes")[0], 1) + + def test_head_selects_the_pushed_commit(self): + self.write(".ub/check", "#!/bin/sh\nexit 0\n") + self.commit() + tampered = git(self.root, "rev-parse", "HEAD") + git(self.root, "checkout", "-q", "main") + self.assertEqual(self.guard()[0], 0) + self.assertEqual(self.guard(head=tampered)[0], 1) + + def test_adopting_ub_passes_unless_the_ratchet_is_malformed(self): + git(self.root, "rm", "-rq", ".ub") + self.commit() + git(self.root, "branch", "-qf", "main") + self.write(".ub/check", "#!/bin/sh\n") + self.write(".ub/ratchet", "lint.noqa 9\n") + self.commit() + self.assertEqual(self.guard()[0], 0) + self.write(".ub/ratchet", "lint.noqa many\n") + self.commit() + with self.assertRaisesRegex(ValueError, "not 'key count'"): + self.guard() + + def test_missing_base_is_incomplete(self): + code, output, error = call(ratchet.guard, self.root, "origin/missing") + self.assertEqual((code, output), (2, "")) + self.assertIn("no merge base of HEAD and origin/missing", error) + self.assertIn("fetch-depth: 0", error) + + def test_symlinked_or_malformed_committed_ratchet_is_incomplete(self): + def symlink(): + (self.root / ".ub/ratchet").unlink() + (self.root / ".ub/ratchet").symlink_to("../t.py") + + for change in (lambda: self.write(".ub/ratchet", "lint.noqa many\n"), symlink): + with self.subTest(change=change): + git(self.root, "reset", "-q", "--hard", "main") + change() + self.commit() + code, _, error = call(ratchet.run, ["--root", str(self.root), "--guard", "--base", "main"]) + self.assertEqual(code, 2, error) + + +class CommandTests(RepositoryTest): + def ub(self, *args, cwd=None): + return call(ratchet.run, ["--root", str(cwd or self.root), *args]) + + def test_check_update_and_usage(self): + (self.root / "sub").mkdir() + self.assertEqual(self.ub("--update", cwd=self.root / "sub")[0], 0) + self.assertTrue((self.root / ".ub/ratchet").is_file()) + self.assertEqual(self.ub()[0], 0) + for args in (["--guard"], ["--base", "main"], ["--head", "HEAD"], + ["--update", "--guard", "--base", "main"]): + with self.subTest(args=args): + self.assertEqual(self.ub(*args)[0], 2) + self.write("t.py", "x # noqa\n") + self.assertEqual(self.ub(cwd=self.root / "sub")[0], 1) + self.write(".ub/ratchet", "bad\n") + code, _, error = self.ub() + self.assertEqual(code, 2) + self.assertIn("line 1 is not 'key count'", error) + + def test_guard_from_a_subdirectory_reads_the_worktree_root(self): + self.write(".ub/check", "#!/bin/sh\n") + self.write("sub/x.txt", "") + call(ratchet.update, self.root) + GuardTests.commit(self) + self.assertEqual(self.ub("--guard", "--base", "HEAD", cwd=self.root / "sub")[:2], + (0, "Guard: HEAD does not loosen .ub/ since HEAD.\n")) + + def test_outside_git_checks_nothing_and_cannot_update(self): + with tempfile.TemporaryDirectory() as outside: + self.assertEqual(self.ub(cwd=Path(outside))[0], 0) + code, _, error = self.ub("--update", cwd=Path(outside)) + self.assertEqual(code, 2) + self.assertIn("needs a Git repository", error) From ec4dd61f68178b8dade5bb44875b2cf372e078e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Sat, 21 Nov 2026 12:55:41 +0100 Subject: [PATCH 2/4] Give the conflict test's merge an identity, as CI has none --- tests/test_ratchet.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_ratchet.py b/tests/test_ratchet.py index 213d143..0113f56 100644 --- a/tests/test_ratchet.py +++ b/tests/test_ratchet.py @@ -141,7 +141,9 @@ def test_a_conflicted_path_is_scanned_once(self): git(self.root, "checkout", "-q", "main") self.write("a.py", "x = 3 # noqa\n") self.commit() - subprocess.run(["git", "-C", str(self.root), "merge", "-q", "other"], capture_output=True) + merge = subprocess.run(["git", "-C", str(self.root), "-c", "user.name=t", "-c", "user.email=t@example.invalid", + "merge", "-q", "other"], capture_output=True, text=True) + self.assertIn("CONFLICT", merge.stdout + merge.stderr) self.assertIn("a.py\0a.py", subprocess.run(["git", "-C", str(self.root), "ls-files", "-z", "-co"], capture_output=True, text=True).stdout) self.assertEqual(len(ratchet.scan(self.root)["lint.noqa"]), 2) From 20d9b96852202db298edbb3e0f5fc6d793f033b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Sat, 21 Nov 2026 13:30:34 +0100 Subject: [PATCH 3/4] Kill the mutants that in-process hook tests newly expose The Stop and init helpers now run in the measured process, so their mutation sites count. Assert the empty-stderr Git message, a second ratchet write, nested parent creation, and a failing ps. Drop the unused managed_block default, text=True, and the <= that only equivalent mutants could change. --- src/ub_cli/hooks.py | 6 +++--- src/ub_cli/project.py | 2 +- tests/test_project.py | 31 ++++++++++++++++++++++++++++--- tests/test_ratchet.py | 6 ++++++ 4 files changed, 38 insertions(+), 7 deletions(-) diff --git a/src/ub_cli/hooks.py b/src/ub_cli/hooks.py index 6cccc17..46cfaa4 100644 --- a/src/ub_cli/hooks.py +++ b/src/ub_cli/hooks.py @@ -146,14 +146,14 @@ def terminate_check(process) -> None: try: os.killpg(process.pid, signal.SIGSTOP) while True: - table = subprocess.run(["ps", "-e", "-o", "pid=", "-o", "ppid="], - capture_output=True, text=True, check=True) + # int() reads the byte strings directly. + table = subprocess.run(["ps", "-e", "-o", "pid=", "-o", "ppid="], capture_output=True, check=True) parents = {int(pid): int(parent) for pid, parent in (line.split() for line in table.stdout.splitlines())} descendants = {process.pid} while True: children = {pid for pid, parent in parents.items() if parent in descendants} - if children <= descendants: + if not children - descendants: break descendants.update(children) new = descendants - stopped diff --git a/src/ub_cli/project.py b/src/ub_cli/project.py index 7a7684b..fa81c10 100644 --- a/src/ub_cli/project.py +++ b/src/ub_cli/project.py @@ -45,7 +45,7 @@ def local_file(root: Path, name: str) -> Path: return path -def managed_block(text: str, body: str, *, markdown: bool = True) -> str: +def managed_block(text: str, body: str, *, markdown: bool) -> str: start, end = (("", "") if markdown else ("# ub:begin", "# ub:end")) block = f"{start}\n{body.rstrip()}\n{end}\n" diff --git a/tests/test_project.py b/tests/test_project.py index 3689c78..5b5cb1f 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -7,6 +7,7 @@ import sys import tempfile import unittest +from unittest.mock import patch import ub_cli @@ -385,11 +386,13 @@ def test_stop_keeps_only_the_tail_of_large_diagnostics(self): self.assertIn("last diagnostic", failure["reason"]) def test_timeout_terminates_tests_started_in_a_new_session(self): + from ub_cli.hooks import stop_decision + check = self.initialize() code = ("from pathlib import Path; from ub_cli.vendor.mutator.runner import CommandRunner; " "CommandRunner().run('echo $$ > child.pid; sleep 30', Path.cwd(), None)") self.executable(check, f"exec {shlex.quote(sys.executable)} -c {shlex.quote(code)}\n") - failure = self.stop(None, "--timeout", "1") + failure = stop_decision({"cwd": str(self.root)}, 1) self.assertIn("exceeded 1s", failure["reason"]) pid = int((self.root / "child.pid").read_text()) status = self.command(["ps", "-p", str(pid), "-o", "stat="]) @@ -398,6 +401,30 @@ def test_timeout_terminates_tests_started_in_a_new_session(self): self.fail(f"Detached test process {pid} survived: {status.stdout}") +class TerminateTests(RepositoryTests): + def test_a_failing_ps_is_an_error_not_a_partial_kill(self): + from ub_cli.hooks import stop_decision + + check = self.initialize() + self.executable(check, "sleep 20\n") + self.executable(self.bin / "ps", "exit 1\n") + with patch.dict(os.environ, {"PATH": self.env["PATH"]}): + with self.assertRaises(subprocess.CalledProcessError): + stop_decision({"cwd": str(self.root)}, 1) + + +class WriteFileTests(unittest.TestCase): + def test_creates_parents_and_rewrites_only_changed_content(self): + from ub_cli.project import write_file + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "a" / "b" / "file.txt" + write_file(path, "one\n", 0o755) + self.assertEqual((path.read_text(), path.stat().st_mode & 0o777), ("one\n", 0o755)) + write_file(path, "two\n") + self.assertEqual((path.read_text(), path.stat().st_mode & 0o777), ("two\n", 0o755)) + + class StopDecisionTests(RepositoryTests): def test_decision_covers_continuation_pass_fail_and_bad_events(self): from ub_cli.hooks import stop_decision @@ -415,8 +442,6 @@ def test_decision_covers_continuation_pass_fail_and_bad_events(self): for payload in ([], {"cwd": ""}, {"cwd": 1}): with self.subTest(payload=payload), self.assertRaises(ValueError): stop_decision(payload, 5) - self.executable(check, "sleep 20\n") - self.assertIn("exceeded 1s", stop_decision({"cwd": str(self.root)}, 1)["reason"]) def test_changed_sees_staged_untracked_and_hidden_edits(self): from ub_cli.hooks import ub_changed diff --git a/tests/test_ratchet.py b/tests/test_ratchet.py index 0113f56..0df1a8c 100644 --- a/tests/test_ratchet.py +++ b/tests/test_ratchet.py @@ -336,6 +336,12 @@ def test_missing_base_is_incomplete(self): self.assertEqual((code, output), (2, "")) self.assertIn("no merge base of HEAD and origin/missing", error) self.assertIn("fetch-depth: 0", error) + git(self.root, "checkout", "-q", "--orphan", "unrelated") + self.write("unrelated.txt", "") + self.commit() + code, _, error = call(ratchet.guard, self.root, "main") + self.assertEqual(code, 2) + self.assertIn("no merge base of HEAD and main: Git command failed.\n", error) def test_symlinked_or_malformed_committed_ratchet_is_incomplete(self): def symlink(): From 9344ed238ce59fa63f0624b1f7087adf032b79d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Sat, 21 Nov 2026 20:29:14 +0100 Subject: [PATCH 4/4] Show likely new matches, add excludes and --lower, print the accept steps A ratchet failure lists the grown kind's matches in files with uncommitted changes, and the count elsewhere; without such files, as in CI, it lists all of them. It ends with how to remove or accept them. .ub/ratchet takes `exclude GLOB` lines for vendored or generated files. `ub ratchet --update` keeps them; the guard fails when one is added. `ub ratchet --lower` lowers counts and never raises one or adds an exclude, so agents run it after removing escape hatches and the slack each removal left is gone. --- README.md | 34 +++++--- src/ub_cli/project.py | 7 +- src/ub_cli/ratchet.py | 135 ++++++++++++++++++++++------- src/ub_cli/skills/ub-mode/SKILL.md | 5 +- tests/test_ratchet.py | 65 +++++++++++--- 5 files changed, 186 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index b103171..6bdab58 100644 --- a/README.md +++ b/README.md @@ -205,21 +205,30 @@ directive does not count. Each occurrence counts, including two on one line. Symlinks are not followed. `.ub/ratchet` sits at the Git worktree root and holds one `key count` line per -kind. `ub check` runs the ratchet before coverage and fails when any count -exceeds its line, listing every current `file:line` of that kind (the file -stores counts, not locations); the other gates still run and report. Equal or -lower counts pass. Without `.ub/ratchet` the counts are report-only, and outside +kind, plus optional `exclude GLOB` lines for vendored or generated files that +should not be counted (`fnmatch` rules on the repository-relative path; `*` +crosses directories, so `exclude vendor/*` skips the whole tree). `ub check` +runs the ratchet before coverage and fails when any count exceeds its line; the +other gates still run and report. The file stores counts, not locations, so a +failure lists the kind's matches in files with uncommitted changes, the likely +new ones, and the number elsewhere; with none in changed files, as in CI, it +lists every match. It ends with how to remove or accept them. Equal or lower +counts pass. Without `.ub/ratchet` the counts are report-only, and outside a Git repository the ratchet is skipped. A malformed or symlinked `.ub/ratchet`, or a failed file listing, makes the check incomplete. `ub ratchet` runs the same comparison alone. -The counts belong to a human. After removing escape hatches, or to accept a new -one, run `ub ratchet --update` and commit the file. The managed agent -instructions tell agents never to run it or edit `.ub/` unless asked. +Raising a count or adding an exclude belongs to a human: run +`ub ratchet --update`, which writes the current counts and keeps the excludes, +and commit the file. `ub ratchet --lower` only lowers counts to the current +ones and never raises one or adds an exclude, so agents may run it after +removing escape hatches; otherwise each removal leaves room for a free new one. +The managed agent instructions tell agents to lower the counts and never to run +`--update` or edit `.ub/` unless asked. `ub ratchet --guard --base REF [--head REF]` fails when the commits since the merge base of the head (default `HEAD`) and `REF` change `.ub/check` (content -or mode), delete `.ub/ratchet`, or raise any of its counts, and when the +or mode), delete `.ub/ratchet`, raise any of its counts, or add an exclude, and when the worktree's `.ub/check` or `.ub/ratchet` differs from `HEAD`. Adding them to a repository that had none, and lowering counts, pass. Set `UB_ALLOW_UB_CHANGE=1` to accept a reviewed change. The guard exits 2 when it cannot find the merge @@ -265,8 +274,9 @@ Known limits: - A directive inside a multi-line block comment, after its first line, is missed. - Outside Python, strings and comments are not parsed: a quoted directive or a commented-out skip in JS/TS or Java counts. -- The Stop hook keeps the last 8,000 bytes of output, so a very long list of - matches can push the kind and counts out of the agent's view. +- The Stop hook keeps the last 8,000 bytes of output. When no match of a grown + kind is in a changed file, the full list is printed and can push the kind and + counts out of the agent's view. - Deleting a failing test and passing extra arguments to `./.ub/check` are not detected. - Go, Rust, and Clojure patterns are not yet counted. @@ -274,8 +284,8 @@ Known limits: | `ub ratchet` status | Meaning | | --- | --- | | 0 | No count above `.ub/ratchet`, or the guard found no loosening (or `UB_ALLOW_UB_CHANGE=1`). | -| 1 | A count grew, or the guard found `.ub/check` changed, `.ub/ratchet` deleted, a count raised, or uncommitted `.ub/` changes. | -| 2 | Usage error, a malformed or symlinked `.ub/ratchet`, a failed file listing, `--update` outside Git, or no merge base for the guard. | +| 1 | A count grew, or the guard found `.ub/check` changed, `.ub/ratchet` deleted, a count raised, an exclude added, or uncommitted `.ub/` changes. | +| 2 | Usage error, a malformed or symlinked `.ub/ratchet`, a failed file listing, `--update` or `--lower` outside Git, `--lower` without `.ub/ratchet`, or no merge base for the guard. | ## Combined gate diff --git a/src/ub_cli/project.py b/src/ub_cli/project.py index fa81c10..e96bbea 100644 --- a/src/ub_cli/project.py +++ b/src/ub_cli/project.py @@ -20,8 +20,9 @@ changes, not the committed changes in a pull request. Do not weaken the check, skip hooks, or claim success without a passing run. `.ub/ratchet` caps lint suppressions, coverage exclusions, and skipped tests; -remove the new escape hatch instead. Never run `ub ratchet --update` or edit -`.ub/` unless the user asks. +remove the new escape hatch instead. After removing escape hatches, run +`ub ratchet --lower` and commit `.ub/ratchet`. Never run `ub ratchet --update` +or otherwise edit `.ub/` unless the user asks. """ @@ -106,7 +107,7 @@ def initialize(options) -> None: top = toplevel(root) ratchet = top and ratchet_file(top) if ratchet and not ratchet.exists(): - pending[ratchet] = (render(tally(scan(top))), None) + pending[ratchet] = (render(tally(scan(top)), []), None) generated = [".ub/check"] + ([os.path.relpath(ratchet, root)] if ratchet else []) for name in ("AGENTS.md", "CLAUDE.md", ".gitignore"): path = local_file(root, name) diff --git a/src/ub_cli/ratchet.py b/src/ub_cli/ratchet.py index 302a364..57a62fb 100644 --- a/src/ub_cli/ratchet.py +++ b/src/ub_cli/ratchet.py @@ -1,6 +1,7 @@ """Count escape hatches and fail when any count grows past .ub/ratchet.""" import argparse +from fnmatch import fnmatchcase import io from itertools import accumulate import os @@ -9,6 +10,7 @@ import subprocess import sys import tokenize +from typing import NamedTuple from ub_cli.project import git, local_file, write_file @@ -16,7 +18,10 @@ RATCHET = ".ub/ratchet" CHECK = ".ub/check" OVERRIDE = "UB_ALLOW_UB_CHANGE" -HEADER = "# Escape-hatch counts. ub check fails when one grows. Only a human lowers or raises them.\n" +HEADER = ("# Escape-hatch counts; ub check fails when one grows. `ub ratchet --lower` lowers them.\n" + "# Only a human raises a count or adds an `exclude GLOB` line, with `ub ratchet --update`.\n") +ACCEPT = (" Remove the new escape hatches. To accept them instead, a human runs ub ratchet --update,\n" + f" commits {RATCHET}, and approves the raise: {OVERRIDE}=1 to push, the approval label in CI.") REGULAR = ("100644", "100755") PYTHON = (".py", ".pyi") @@ -61,11 +66,19 @@ def toplevel(root: Path) -> Path | None: return None -def scan(top: Path) -> dict[str, list[str]]: - """Each kind's `file:line` matches in the files Git tracks or would track under `top`.""" +class Baseline(NamedTuple): + counts: dict[str, int] + excludes: list[str] + + +def scan(top: Path, excludes=()) -> dict[str, list[str]]: + """Each kind's `file:line` matches in the files Git tracks or would track under `top`. + + Files matching an `excludes` glob are skipped; `*` crosses directories. + """ command = ["git", "-C", str(top), "ls-files", "-z", "-co", "--exclude-standard"] - listing = subprocess.run(command, capture_output=True) + listing = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if listing.returncode: raise ValueError(f"git ls-files failed: {listing.stderr.decode(errors='replace').strip()}") found = {key: [] for key, _, _ in RULES} @@ -73,6 +86,8 @@ def scan(top: Path) -> dict[str, list[str]]: for name in dict.fromkeys(filter(None, listing.stdout.split(b"\0"))): shown = name.decode(errors="replace") rules = [(key, pattern) for key, suffixes, pattern in RULES if shown.endswith(suffixes)] + if any(fnmatchcase(shown, glob) for glob in excludes): + continue path = top / os.fsdecode(name) # A path that resolves elsewhere passes through a symlink, which is not followed. if rules and path.is_file() and path.resolve() == path: @@ -122,20 +137,24 @@ def tally(found: dict[str, list[str]]) -> dict[str, int]: return {key: len(places) for key, places in found.items()} -def parse(text: str) -> dict[str, int]: - counts = {} +def parse(text: str) -> Baseline: + baseline = Baseline({}, []) for number, line in enumerate(text.splitlines(), 1): words = line.split() if not words or words[0].startswith("#"): continue - if len(words) != 2 or not words[1].isdigit(): - raise ValueError(f"{RATCHET} line {number} is not 'key count': {line}") - counts[words[0]] = int(words[1]) - return counts + if len(words) == 2 and words[0] == "exclude": + baseline.excludes.append(words[1]) + elif len(words) == 2 and words[1].isdigit(): + baseline.counts[words[0]] = int(words[1]) + else: + raise ValueError(f"{RATCHET} line {number} is not 'key count' or 'exclude GLOB': {line}") + return baseline -def render(counts: dict[str, int]) -> str: - return HEADER + "".join(f"{key} {counts[key]}\n" for key in sorted(counts)) +def render(counts: dict[str, int], excludes: list[str]) -> str: + return (HEADER + "".join(f"exclude {glob}\n" for glob in excludes) + + "".join(f"{key} {counts[key]}\n" for key in sorted(counts))) def grown(current: dict[str, int], baseline: dict[str, int]) -> list[tuple[str, int, int]]: @@ -161,7 +180,7 @@ def gate(root: Path) -> tuple[list[str], list[str]]: present = os.path.lexists(top / RATCHET) try: baseline = parse(ratchet_file(top).read_text()) if present else None - found = scan(top) + found = scan(top, baseline.excludes if baseline else ()) except (OSError, ValueError) as exc: if present: print("Ratchet: incomplete.") @@ -172,31 +191,81 @@ def gate(root: Path) -> tuple[list[str], list[str]]: if baseline is None: print(f"Ratchet: {sum(counts.values())} escape hatches, report only without {RATCHET}.") return [], [] - rows = grown(counts, baseline) + rows = grown(counts, baseline.counts) if not rows: - lower = any(counts.get(key, 0) < count for key, count in baseline.items()) - hint = "; a human can lower it with ub ratchet --update" if lower else "" + lower = any(counts.get(key, 0) < count for key, count in baseline.counts.items()) + hint = "; lower it with ub ratchet --lower" if lower else "" print(f"Ratchet: {sum(counts.values())} escape hatches, none above {RATCHET}{hint}.") return [], [] - # The ratchet stores counts, not locations, so every current match of a grown kind is listed. - print(f"Ratchet: {len(rows)} kinds above {RATCHET}, with every current match") + return report_growth(top, found, rows), [] + + +def report_growth(top: Path, found: dict[str, list[str]], rows) -> list[str]: + """Print each grown kind with its likely new matches. Return one failure per kind.""" + + print(f"Ratchet: {len(rows)} kinds above {RATCHET}") + recent = changed(top) failures = [] for key, now, then in rows: failures.append(f"{key}: {now} > {then}") print(f" {failures[-1]}") - print("".join(f" {place}\n" for place in found[key]), end="") - return failures, [] + shown = shown_places(found[key], recent) + print("".join(f" {place}\n" for place in shown), end="") + if len(shown) < now: + print(f" ... and {now - len(shown)} in files without uncommitted changes") + print(ACCEPT) + return failures -def update(root: Path) -> None: +def changed(top: Path) -> set[str] | None: + """Files with uncommitted changes, untracked ones included, or None when that is unknown.""" + + try: + names = (git(top, "diff", "--name-only", "-z", "HEAD") + "\0" + + git(top, "ls-files", "-z", "-o", "--exclude-standard")) + except ValueError: + return None + return set(filter(None, names.split("\0"))) + + +def shown_places(places: list[str], recent: set[str] | None) -> list[str]: + """The matches in changed files, the likely new ones; all of them when there are none. + + The ratchet stores counts, not locations, so it cannot say which match is new. + """ + + fresh = [place for place in places if place.rsplit(":", 1)[0] in (recent or ())] + return fresh or places + + +def current(root: Path) -> tuple[Path, Baseline | None, dict[str, int]]: + """The worktree root, its baseline if any, and the counts under the baseline's excludes.""" + top = toplevel(root) if top is None: - raise ValueError("ub ratchet --update needs a Git repository.") - counts = tally(scan(top)) - write_file(ratchet_file(top), render(counts)) + raise ValueError("ub ratchet --update and --lower need a Git repository.") + path = ratchet_file(top) + baseline = parse(path.read_text()) if path.exists() else None + return top, baseline, tally(scan(top, baseline.excludes if baseline else ())) + + +def update(root: Path) -> None: + top, baseline, counts = current(root) + write_file(ratchet_file(top), render(counts, baseline.excludes if baseline else [])) print(f"Wrote {top / RATCHET}: {sum(counts.values())} escape hatches.") +def lower(root: Path) -> None: + """Lower each count to the current one. Never raises a count or adds an exclude.""" + + top, baseline, counts = current(root) + if baseline is None: + raise ValueError(f"No {RATCHET} to lower; a human creates it with ub ratchet --update.") + lowered = {key: min(count, counts.get(key, 0)) for key, count in baseline.counts.items()} + write_file(ratchet_file(top), render(lowered, baseline.excludes)) + print(f"Lowered {sum(baseline.counts.values()) - sum(lowered.values())} escape hatches in {top / RATCHET}.") + + def entry(root: Path, revision: str, name: str) -> tuple[str, str] | None: """The Git mode and object id of `name` at `revision`, or None when absent.""" @@ -225,7 +294,7 @@ def uncommitted(root: Path) -> list[str]: return [name for name in (CHECK, RATCHET) if worktree_entry(root, name) != head.get(name)] -def committed_counts(root: Path, item: tuple[str, str] | None) -> dict[str, int] | None: +def committed_baseline(root: Path, item: tuple[str, str] | None) -> Baseline | None: if item is None: return None if item[0] not in REGULAR: @@ -240,12 +309,14 @@ def tampering(root: Path, start: str, head: str) -> list[str]: check = entry(root, start, CHECK) if check is not None and check != entry(root, head, CHECK): problems.append(f"{CHECK} changed") - before = committed_counts(root, entry(root, start, RATCHET)) - after = committed_counts(root, entry(root, head, RATCHET)) + before = committed_baseline(root, entry(root, start, RATCHET)) + after = committed_baseline(root, entry(root, head, RATCHET)) if before is not None and after is None: problems.append(f"{RATCHET} was deleted") elif before is not None: - problems += [f"{RATCHET} raised {key}: {then} -> {now}" for key, now, then in grown(after, before)] + problems += [f"{RATCHET} raised {key}: {then} -> {now}" + for key, now, then in grown(after.counts, before.counts)] + problems += [f"{RATCHET} added exclude {glob}" for glob in after.excludes if glob not in before.excludes] return problems @@ -282,7 +353,9 @@ def arguments(argv: list[str]) -> argparse.Namespace: parser = argparse.ArgumentParser(prog="ub ratchet", description=__doc__) parser.add_argument("--root", type=Path, default=Path.cwd()) mode = parser.add_mutually_exclusive_group() - mode.add_argument("--update", action="store_true", help=f"Write the current counts to {RATCHET}") + mode.add_argument("--update", action="store_true", + help=f"Write the current counts to {RATCHET}, raising any that grew (a human's call)") + mode.add_argument("--lower", action="store_true", help=f"Lower the counts in {RATCHET}; never raises one") mode.add_argument("--guard", action="store_true", help="Fail when commits change .ub/check, delete .ub/ratchet, or raise a count") parser.add_argument("--base", metavar="REF", help="Compare with the merge base of the head and REF (--guard)") @@ -302,8 +375,8 @@ def run(argv: list[str]) -> int: root = toplevel(options.root) or options.root.resolve() if options.guard: return guard(root, options.base, options.head or "HEAD") - if options.update: - update(root) + if options.update or options.lower: + (update if options.update else lower)(root) return 0 return check(root) except (OSError, ValueError) as exc: diff --git a/src/ub_cli/skills/ub-mode/SKILL.md b/src/ub_cli/skills/ub-mode/SKILL.md index 6bd3a06..4c64312 100644 --- a/src/ub_cli/skills/ub-mode/SKILL.md +++ b/src/ub_cli/skills/ub-mode/SKILL.md @@ -31,8 +31,9 @@ Every time you are asked to make a change follow: it. Do not weaken checks or bypass hooks. Report remaining failures, missing tools, and checks that could not finish without claiming success. * `.ub/ratchet` caps lint suppressions, coverage exclusions, and skipped tests. - When `ub check` reports a count above it, remove the new escape hatch. Never - run `ub ratchet --update` or edit `.ub/` unless the user asks. + When `ub check` reports a count above it, remove the new escape hatch. After + removing escape hatches, run `ub ratchet --lower` and commit `.ub/ratchet`. + Never run `ub ratchet --update` or otherwise edit `.ub/` unless the user asks. * Keep fixes within the requested task. This skill does not authorize unrelated cleanup, commits, or publication. diff --git a/tests/test_ratchet.py b/tests/test_ratchet.py index 0df1a8c..d46a345 100644 --- a/tests/test_ratchet.py +++ b/tests/test_ratchet.py @@ -169,7 +169,7 @@ def test_symlinks_and_unreadable_names_are_skipped(self): (self.root / "pkg").symlink_to(self.root.parent / "elsewhere") blob = git(self.root, "hash-object", "-w", str(outside)) subprocess.run([b"git", b"-C", bytes(self.root), b"update-index", b"--add", b"--cacheinfo", - b"100644," + blob.encode() + b",caf\xe9.py"], check=True) + b"100644," + blob.encode() + b",caf\xe9.py"], check=True, capture_output=True) self.assertEqual(ratchet.scan(self.root)["lint.noqa"], []) def test_outside_git_skips_and_listing_errors_are_incomplete(self): @@ -192,7 +192,7 @@ def test_without_a_ratchet_file_reports_only(self): self.assertEqual(call(ratchet.gate, self.root)[:2], (([], []), "Ratchet: 2 escape hatches, report only without .ub/ratchet.\n")) - def test_growth_fails_with_every_current_location_from_any_directory(self): + def test_growth_without_commits_lists_every_location_from_any_directory(self): self.write("t.py", "x # noqa\n") call(ratchet.update, self.root) self.write("t.py", "x # noqa\n@unittest.skip('x')\n" + "z # noqa\n" * 20) @@ -201,9 +201,45 @@ def test_growth_fails_with_every_current_location_from_any_directory(self): self.assertEqual((failures, incomplete), (["lint.noqa: 22 > 1", "skip.unittest: 1 > 0"], [])) noqa = "".join(f" {place}\n" for place in ["sub/u.py:1", "t.py:1"] + [f"t.py:{line}" for line in range(3, 23)]) - self.assertEqual(output, "Ratchet: 2 kinds above .ub/ratchet, with every current match\n" + self.assertEqual(output, "Ratchet: 2 kinds above .ub/ratchet\n" f" lint.noqa: 22 > 1\n{noqa}" - " skip.unittest: 1 > 0\n t.py:2\n") + " skip.unittest: 1 > 0\n t.py:2\n" + ratchet.ACCEPT + "\n") + + def test_growth_lists_matches_in_changed_files_first(self): + self.write("old.py", "x # noqa\n" * 3) + self.write("edited.py", "x = 1\n") + call(ratchet.update, self.root) + self.commit() + self.write("edited.py", "x = 1 # noqa\n") + self.write("new.py", "y # noqa\n") + (failures, _), output, _ = call(ratchet.gate, self.root) + self.assertEqual(failures, ["lint.noqa: 5 > 3"]) + listed = output.split(" lint.noqa: 5 > 3\n")[1].split(ratchet.ACCEPT)[0].splitlines() + self.assertEqual(sorted(listed[:2]), [" edited.py:1", " new.py:1"]) + self.assertEqual(listed[2:], [" ... and 3 in files without uncommitted changes"]) + self.commit() + _, output, _ = call(ratchet.gate, self.root) + self.assertIn(" old.py:3\n" + ratchet.ACCEPT, output) + with patch("ub_cli.ratchet.git", side_effect=ValueError): + self.assertIsNone(ratchet.changed(self.root)) + + def test_excluded_files_are_not_counted_and_lower_never_raises(self): + self.write("vendor/lib/a.py", "x # noqa\n") + self.write("src/b.py", "x # noqa\ny # noqa\n") + self.write(".ub/ratchet", "exclude vendor/*\nlint.noqa 3\nskip.js 0\nretired.kind 2\n") + self.assertEqual(ratchet.scan(self.root, ["vendor/*"])["lint.noqa"], ["src/b.py:1", "src/b.py:2"]) + self.assertEqual(call(ratchet.gate, self.root)[1], + "Ratchet: 2 escape hatches, none above .ub/ratchet; lower it with ub ratchet --lower.\n") + self.write("src/c.js", "it.only('x')\n") + _, output, _ = call(ratchet.lower, self.root) + self.assertEqual(output, f"Lowered 3 escape hatches in {self.root / '.ub/ratchet'}.\n") + self.assertEqual(ratchet.parse((self.root / ".ub/ratchet").read_text()), + ratchet.Baseline({"lint.noqa": 2, "retired.kind": 0, "skip.js": 0}, ["vendor/*"])) + call(ratchet.update, self.root) + self.assertEqual(ratchet.parse((self.root / ".ub/ratchet").read_text()).excludes, ["vendor/*"]) + (self.root / ".ub/ratchet").unlink() + with self.assertRaisesRegex(ValueError, "No .ub/ratchet to lower"): + ratchet.lower(self.root) def test_equal_and_lower_counts_pass(self): self.write("t.py", "x # noqa\n") @@ -213,12 +249,12 @@ def test_equal_and_lower_counts_pass(self): self.write(".ub/ratchet", "lint.noqa 1\nretired.kind 1\n") self.assertEqual(call(ratchet.gate, self.root)[:2], (([], []), "Ratchet: 1 escape hatches, none above .ub/ratchet; " - "a human can lower it with ub ratchet --update.\n")) + "lower it with ub ratchet --lower.\n")) def test_malformed_or_symlinked_ratchet_is_incomplete(self): self.write(".ub/ratchet", "lint.noqa many\n") (_, incomplete), _, _ = call(ratchet.gate, self.root) - self.assertEqual(incomplete, ["Ratchet: .ub/ratchet line 1 is not 'key count': lint.noqa many"]) + self.assertEqual(incomplete, ["Ratchet: .ub/ratchet line 1 is not 'key count' or 'exclude GLOB': lint.noqa many"]) (self.root / ".ub/ratchet").unlink() (self.root / ".ub/ratchet").symlink_to("missing") (_, incomplete), _, _ = call(ratchet.gate, self.root) @@ -239,14 +275,15 @@ def test_update_writes_every_kind_and_round_trips(self): result, output, _ = call(ratchet.update, self.root) text = (self.root / ".ub/ratchet").read_text() self.assertTrue(text.startswith("# ")) - counts = ratchet.parse(text) + counts = ratchet.parse(text).counts self.assertEqual(counts, {key: int(key == "lint.noqa") for key, _, _ in ratchet.PATTERNS}) self.assertEqual(list(counts), sorted(counts)) self.assertEqual(output, f"Wrote {self.root / '.ub/ratchet'}: 1 escape hatches.\n") def test_parse_skips_comments_and_rejects_malformed_lines(self): - self.assertEqual(ratchet.parse("# note\n\n lint.noqa 2\n"), {"lint.noqa": 2}) - for line in ("lint.noqa", "lint.noqa -1", "lint.noqa 1 2", "lint.noqa x"): + self.assertEqual(ratchet.parse("# note\n\n lint.noqa 2\nexclude gen/*\n"), + ratchet.Baseline({"lint.noqa": 2}, ["gen/*"])) + for line in ("lint.noqa", "lint.noqa -1", "lint.noqa 1 2", "lint.noqa x", "exclude a b"): with self.subTest(line=line), self.assertRaisesRegex(ValueError, "line 2 is not 'key count'"): ratchet.parse("# note\n" + line + "\n") @@ -256,7 +293,7 @@ def setUp(self): super().setUp() self.write(".ub/check", "#!/bin/sh\nexec ub check\n") (self.root / ".ub/check").chmod(0o755) - self.write(".ub/ratchet", "lint.noqa 1\nskip.js 2\n") + self.write(".ub/ratchet", "exclude keep/*\nlint.noqa 1\nskip.js 2\n") self.commit() git(self.root, "checkout", "-qb", "work") @@ -284,6 +321,8 @@ def test_loosening_commits_and_worktree_edits_fail(self): cases = { "raise": (lambda: self.write(".ub/ratchet", "lint.noqa 2\nskip.js 2\nskip.pytest 1\n"), True, [".ub/ratchet raised lint.noqa: 1 -> 2", ".ub/ratchet raised skip.pytest: 0 -> 1"]), + "exclude": (lambda: self.write(".ub/ratchet", "exclude keep/*\nexclude gen/*\nlint.noqa 1\nskip.js 2\n"), + True, [".ub/ratchet added exclude gen/*"]), "delete": (lambda: (self.root / ".ub/ratchet").unlink(), True, [".ub/ratchet was deleted"]), "edit": (lambda: self.write(".ub/check", "#!/bin/sh\nexit 0\n"), True, [".ub/check changed"]), "mode": (lambda: (self.root / ".ub/check").chmod(0o644), True, [".ub/check changed"]), @@ -366,8 +405,10 @@ def test_check_update_and_usage(self): self.assertEqual(self.ub("--update", cwd=self.root / "sub")[0], 0) self.assertTrue((self.root / ".ub/ratchet").is_file()) self.assertEqual(self.ub()[0], 0) + self.assertEqual(self.ub("--lower", cwd=self.root / "sub")[:2], + (0, f"Lowered 0 escape hatches in {self.root / '.ub/ratchet'}.\n")) for args in (["--guard"], ["--base", "main"], ["--head", "HEAD"], - ["--update", "--guard", "--base", "main"]): + ["--update", "--guard", "--base", "main"], ["--update", "--lower"]): with self.subTest(args=args): self.assertEqual(self.ub(*args)[0], 2) self.write("t.py", "x # noqa\n") @@ -390,4 +431,4 @@ def test_outside_git_checks_nothing_and_cannot_update(self): self.assertEqual(self.ub(cwd=Path(outside))[0], 0) code, _, error = self.ub("--update", cwd=Path(outside)) self.assertEqual(code, 2) - self.assertIn("needs a Git repository", error) + self.assertIn("need a Git repository", error)