diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 99e5a860e..8174210e5 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -1,5 +1,6 @@ -# The two trees below are what scripts/build_dist.py generates from .agents/skills/ and CI holds current. +# The first two trees below are what scripts/build_dist.py generates from .agents/skills/ and CI holds current. # A finding in either therefore belongs at its source, and a review of every copy is one finding three times. +# The third is a tree spec/files.json carries verbatim, which scripts/agent_policy.py requires every repository's file to skip. reviews: # Auto review covers only the default branch unless a base is listed here, each entry a regex. # The default branch stays included whatever is listed. @@ -13,6 +14,7 @@ reviews: path_filters: - "!.github/skills/**" - "!.claude-plugin/fleet-skills/**" + - "!lib/fleet/sh/**" # Canonical prose is linted for style in CI and read whole by the local review pass. # A review comment on it therefore earns its place only by naming something false or unfollowable. path_instructions: diff --git a/.pr_agent.toml b/.pr_agent.toml index 996ee6a8d..e5273d2dd 100644 --- a/.pr_agent.toml +++ b/.pr_agent.toml @@ -1,7 +1,8 @@ -# The two trees below are what scripts/build_dist.py generates from .agents/skills/ and CI holds current. +# The first two trees below are what scripts/build_dist.py generates from .agents/skills/ and CI holds current. # A finding in either therefore belongs at its source, and a review of every copy is one finding three times. +# The third is a tree spec/files.json carries verbatim, which scripts/agent_policy.py requires every repository's file to skip. [ignore] -glob = ['.github/skills/**', '.claude-plugin/fleet-skills/**'] +glob = ['.github/skills/**', '.claude-plugin/fleet-skills/**', 'lib/fleet/sh/**'] [review_agent] # A crash claimed against a name the build accepts was disproven by running the build. diff --git a/docs/pr-reviewer-reference.md b/docs/pr-reviewer-reference.md index 1710eeb97..7a86ee917 100644 --- a/docs/pr-reviewer-reference.md +++ b/docs/pr-reviewer-reference.md @@ -64,7 +64,7 @@ The formal review body was empty. All useful state lived in inline comments, so ### Generated Mirrors -`.github/skills/` and `.claude-plugin/fleet-skills/` are the trees `scripts/build_dist.py` generates from `.agents/skills/`, and CI holds them current. So a finding in either belongs at its source, and a review of every copy is one finding three times. Two committed files tell CodeRabbit and Qodo to skip them. Copilot's exclusion is a repository setting this account does not have, so `.github/copilot-instructions.md` asks instead. +`.github/skills/` and `.claude-plugin/fleet-skills/` are the trees `scripts/build_dist.py` generates from `.agents/skills/`, and CI holds them current. So a finding in either belongs at its source, and a review of every copy is one finding three times. Two committed files tell CodeRabbit and Qodo to skip them. A fleet repository carries `.github/skills/` byte for byte, so the `.coderabbit.yaml` and `.pr_agent.toml` that `repo-config/configure.sh` renders there skip it too. They skip every other tree `spec/files.json` carries verbatim as well. Copilot's exclusion is a repository setting this account does not have, so `.github/copilot-instructions.md` asks instead. - **CodeRabbit** reads [`reviews.path_filters`][coderabbit-config] from `.coderabbit.yaml` at the repository root, where a pattern prefixed with `!` excludes. - **Qodo** reads [its configuration][qodo-config] from `.pr_agent.toml` at the root of the default branch, so the file binds only once it is promoted to `main`. Its [`[ignore]` glob list][qodo-ignore] names the paths to skip. diff --git a/repo-config/README.md b/repo-config/README.md index bc89595ac..2d0f60ff4 100644 --- a/repo-config/README.md +++ b/repo-config/README.md @@ -109,7 +109,7 @@ The fleet-standard general settings live in [`settings.json`][settings-json] and `scripts/agent_policy.py` renders each repository's `.github/agent-policy.json` from `spec/agent-policy.default.json` and the registry entry. An entry may carry an optional `agentPolicy` with a `review.bots` object holding any subset of the fields of `copilot`, `coderabbit`, and `qodo`. Each bot's object is the default bot merged shallowly with the override. The `guard` section cannot be declared, since the workflow model alone decides it. `spec/validate.py` runs the renderer for every entry that declares one, so a malformed override fails CI. -The same render drives the bot-side settings. Copilot's ruleset rule follows the render, as the Rulesets section states. CodeRabbit's `reviews.auto_review.enabled` and `base_branches` in `.coderabbit.yaml` follow it, and so does Qodo's `config.disable_auto_feedback` in `.pr_agent.toml`. The same file always sets `auto_pause_after_reviewed_commits` to `0`. That is because a repository's file replaces CodeRabbit's central and UI settings unless it sets `inheritance: true`, so CodeRabbit's default pause would apply otherwise. CodeRabbit's automatic review always includes the default branch, so an automatic CodeRabbit whose `bases` lack `@default` is refused. Qodo's automatic review covers every pull request. An automatic Qodo whose `bases` miss `main` or `develop` is therefore refused. CodeRabbit's `base_branches` search where a policy base matches whole. So each base is written as `^(?:base)$`, unless it already starts with `^` and ends with an unescaped `$`. +The same render drives the bot-side settings. Copilot's ruleset rule follows the render, as the Rulesets section states. CodeRabbit's `reviews.auto_review.enabled` and `base_branches` in `.coderabbit.yaml` follow it, and so does Qodo's `config.disable_auto_feedback` in `.pr_agent.toml`. The same file always sets `auto_pause_after_reviewed_commits` to `0`. That is because a repository's file replaces CodeRabbit's central and UI settings unless it sets `inheritance: true`, so CodeRabbit's default pause would apply otherwise. Both files also always skip each tree `spec/files.json` carries verbatim, such as `.github/skills/`. CodeRabbit's `reviews.path_filters` holds `!.github/skills/**`, and Qodo's `ignore.glob` holds `.github/skills/**`. Such a tree is the hub's text byte for byte. So a finding on it belongs at the hub's source, not on a carrier's pull request. Each entry is added beside any the repository lists, and only its absence is drift. CodeRabbit's automatic review always includes the default branch, so an automatic CodeRabbit whose `bases` lack `@default` is refused. Qodo's automatic review covers every pull request. An automatic Qodo whose `bases` miss `main` or `develop` is therefore refused. CodeRabbit's `base_branches` search where a policy base matches whole. So each base is written as `^(?:base)$`, unless it already starts with `^` and ends with an unescaped `$`. `repo-config/configure.sh apply owner/repo --checkout ` writes the three files into a local checkout of that repository. It touches only the keys above in the two bot files, keeps every other key and comment, and creates an absent file. It refuses a checkout whose `origin` is another repository, and a path that is not the work tree's top level. `apply` plans the files with `write --dry-run` before its first API write, so a checkout that refuses stops the run with nothing applied. It never stages or commits, so the caller commits the files through the ordinary pull request flow. Without `--checkout`, `apply` writes no policy files and says so. diff --git a/scripts/README.md b/scripts/README.md index a7831013c..76e1fa11c 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -474,7 +474,7 @@ uv run --no-project --script scripts/agent_policy.py write --registry registry/r uv run --no-project --script scripts/agent_policy.py check --registry registry/repos.json --name Fixture --model release --repo acme/widget --ref main ``` -`facts` is the read-only view of the bot settings `write` applies and of where `rulesets` places the Copilot rule. It prints whether the Copilot ruleset rule belongs on `main` and on `develop`, CodeRabbit's `enabled`, `base_branches` and `auto_pause_after_reviewed_commits`, and Qodo's `disable_auto_feedback`. `rulesets` writes `main.json` and `develop.json` into `--out-dir`, composed from the hub's `repo-config/` payloads the model selects. Each is its source payload with the Copilot rule placed where `facts` says, in the shape the `main` source carries. Each payload carrying the required status check rule drops it where the entry declares `pullRequestCheck: false`. `write` refuses unless the checkout is a work tree's top level whose `origin` is the named repository. `render` also refuses an automatic Qodo that misses `main` or `develop`. CodeRabbit's `base_branches` are written as `^(?:base)$` unless already anchored. It writes the policy file whole and sets only those keys in `.coderabbit.yaml` and `.pr_agent.toml`, keeping everything else. An existing file keeps its own line endings. A new file is written CRLF where its `.editorconfig` files set `end_of_line = crlf` for it, and LF otherwise. Those files are read up the directory tree as an editor reads them, until one sets `root = true`. It plans all three files before writing any, so one refusal leaves the checkout untouched. It prints `wrote` or `unchanged` per file and never stages or commits. `--dry-run` plans only and prints `would write` or `unchanged`. `check` reads the three files through the contents API and prints `ok` or `FAIL` per assertion. It exits `0` when clean and `1` on a refusal, drift or a missing file. It exits `2` when the command could not run or a file could not be read. The YAML, TOML and EditorConfig libraries are imported only by `write` and `check`, so `render`, `facts` and `rulesets` run on the standard library. +`facts` is the read-only view of the bot settings `write` applies and of where `rulesets` places the Copilot rule. It prints whether the Copilot ruleset rule belongs on `main` and on `develop`, CodeRabbit's `enabled`, `base_branches`, `auto_pause_after_reviewed_commits` and `path_filters`, and Qodo's `disable_auto_feedback` and `ignore_glob`. `rulesets` writes `main.json` and `develop.json` into `--out-dir`, composed from the hub's `repo-config/` payloads the model selects. Each is its source payload with the Copilot rule placed where `facts` says, in the shape the `main` source carries. Each payload carrying the required status check rule drops it where the entry declares `pullRequestCheck: false`. `write` refuses unless the checkout is a work tree's top level whose `origin` is the named repository. `render` also refuses an automatic Qodo that misses `main` or `develop`. CodeRabbit's `base_branches` are written as `^(?:base)$` unless already anchored. It writes the policy file whole and sets only those keys in `.coderabbit.yaml` and `.pr_agent.toml`, keeping everything else. The two exclusion lists gain each required entry they lack and keep the repository's own, and `check` fails only a required entry that is missing. An existing file keeps its own line endings. A new file is written CRLF where its `.editorconfig` files set `end_of_line = crlf` for it, and LF otherwise. Those files are read up the directory tree as an editor reads them, until one sets `root = true`. It plans all three files before writing any, so one refusal leaves the checkout untouched. It prints `wrote` or `unchanged` per file and never stages or commits. `--dry-run` plans only and prints `would write` or `unchanged`. `check` reads the three files through the contents API and prints `ok` or `FAIL` per assertion. It exits `0` when clean and `1` on a refusal, drift or a missing file. It exits `2` when the command could not run or a file could not be read. The YAML, TOML and EditorConfig libraries are imported only by `write` and `check`, so `render`, `facts` and `rulesets` run on the standard library. ## `central_config.py` diff --git a/scripts/agent_policy.py b/scripts/agent_policy.py index 2c71a6229..04cae4c14 100755 --- a/scripts/agent_policy.py +++ b/scripts/agent_policy.py @@ -24,6 +24,7 @@ import argparse import base64 import binascii +import copy import json import subprocess import sys @@ -43,6 +44,7 @@ TOML_PATH = ".pr_agent.toml" MODELS = ("release", "operational") CONFIG_DIR = Path(__file__).resolve().parents[1] / "repo-config" +MANIFEST_PATH = Path(__file__).resolve().parents[1] / "spec" / "files.json" class Refusal(ValueError): @@ -137,24 +139,43 @@ def serialize(rendered: dict[str, Any]) -> str: return json.dumps(rendered, indent=4) + "\n" +def carried_globs(manifest_path: Path = MANIFEST_PATH) -> list[str]: + """A glob per tree spec/files.json carries verbatim, which a carrier's reviewers skip. + + Such a tree is the hub's text byte for byte, so a finding on it belongs at the hub's source. + Every such tree is listed whatever its appliesTo, since skipping a path a repository lacks is harmless. + """ + trees = json.loads(manifest_path.read_text(encoding="utf-8"))["trees"] + return [f"{tree['target']}/**" for tree in trees if tree["fidelity"] == "verbatim-tree"] + + +def copilot_rule(rendered: dict[str, Any]) -> dict[str, bool]: + """Whether the Copilot ruleset rule belongs on `main` and on `develop` under a rendered policy.""" + copilot = policy_lib.parse(rendered, "rendered policy", fallback=False).bot("copilot") + auto = copilot.trigger == "auto" + return { + "main": auto and copilot.covers("main", "main"), + "develop": auto and copilot.covers("develop", "main"), + } + + def facts(rendered: dict[str, Any]) -> dict[str, Any]: """The settings the bots and the Copilot ruleset rule take from a rendered policy.""" parsed = policy_lib.parse(rendered, "rendered policy", fallback=False) - copilot = parsed.bot("copilot") - auto = copilot.trigger == "auto" - default = "main" crab = parsed.bot("coderabbit") + globs = carried_globs() return { - "copilotRule": { - "main": auto and copilot.covers("main", default), - "develop": auto and copilot.covers("develop", default), - }, + "copilotRule": copilot_rule(rendered), "coderabbit": { "enabled": crab.trigger == "auto", "base_branches": [anchored(b) for b in crab.bases if b != policy_lib.DEFAULT_BASE], "auto_pause_after_reviewed_commits": 0, + "path_filters": [f"!{glob}" for glob in globs], + }, + "qodo": { + "disable_auto_feedback": parsed.bot("qodo").trigger != "auto", + "ignore_glob": globs, }, - "qodo": {"disable_auto_feedback": parsed.bot("qodo").trigger != "auto"}, } @@ -178,7 +199,7 @@ def rulesets( branch: json.loads(path.read_text(encoding="utf-8")) for branch, path in sources.items() } copilot = [r for r in payloads["main"]["rules"] if r.get("type") == "copilot_code_review"] - wanted = facts(render(registry_data, name, model))["copilotRule"] + wanted = copilot_rule(render(registry_data, name, model)) if not copilot and any(wanted.values()): raise Refusal( f"{name}: the policy wants a Copilot rule, and {sources['main']} carries none to copy" @@ -255,6 +276,37 @@ def lf_text(path: Path) -> str | None: return None if text is None else text.replace("\r\n", "\n") +def take_tail_comment(seq: Any) -> Any: + """Detach and return the comment hanging off a block list's last item, or None. + + A comment after a block list hangs off that item, so an item appended after it would move the comment above itself. + """ + return seq.ca.items.pop(len(seq) - 1, None) if len(seq) else None + + +def extend_keeping_comments(seq: Any, items: list[Any]) -> None: + """Append `items` to a block list, keeping each comment where the reader left it. + + An end-of-line comment stays on its own item, and a comment on the lines after the list stays before the next key. + """ + held = take_tail_comment(seq) + last = len(seq) - 1 + seq.extend(items) + if held is None: + return + token = held[0] + if token is None or not token.value.startswith("#"): + seq.ca.items[len(seq) - 1] = held + return + eol, _, rest = token.value.partition("\n") + token.value = eol + "\n" + seq.ca.items[last] = held + if rest.strip(): + after = copy.copy(token) + after.value = "\n" + rest + seq.ca.items[len(seq) - 1] = [after, None, None, None] + + def set_base_branches(node: Any, items: list[str]) -> None: """Make node['base_branches'] hold `items`, double-quoted, keeping the comment that follows the list.""" from ruamel.yaml.comments import CommentedSeq @@ -265,8 +317,7 @@ def set_base_branches(node: Any, items: list[str]) -> None: if not isinstance(seq, CommentedSeq): node["base_branches"] = CommentedSeq(quoted) return - # A comment after a block list hangs off the list's last item, so replacing the list would drop it. - held = seq.ca.items.pop(len(seq) - 1, None) if len(seq) else None + held = take_tail_comment(seq) del seq[:] seq.extend(quoted) if held is None: @@ -290,6 +341,18 @@ def set_base_branches(node: Any, items: list[str]) -> None: node.ca.items["base_branches"] = [None, None, token, None] +def missing(got: Any, required: list[str]) -> list[str] | None: + """The required entries `got` lacks, or None where `got` is not a list at all. + + A repository may list entries of its own, so only the required ones are asserted. + """ + if got is None: + return list(required) + if not isinstance(got, list): + return None + return [item for item in required if item not in got] + + def exactly(got: Any, want: bool | int) -> bool: """Whether `got` is `want` in value and type, so YAML's `false` never reads as a pause of 0.""" if isinstance(want, bool): @@ -300,8 +363,9 @@ def exactly(got: Any, want: bool | int) -> bool: def plan_yaml(path: Path, want: dict[str, Any]) -> str | None: """The new .coderabbit.yaml text, or None where it already holds the wanted values. - Only reviews.auto_review.enabled, base_branches and auto_pause_after_reviewed_commits are set. - So every other key and comment stays. + Only reviews.auto_review.enabled, base_branches and auto_pause_after_reviewed_commits are set, + and reviews.path_filters gains any required exclusion it lacks. + So every other key, list entry and comment stays. """ from io import StringIO @@ -328,11 +392,15 @@ def plan_yaml(path: Path, want: dict[str, Any]) -> str | None: node = node[key] if not isinstance(node, dict): raise Refusal(f"{path}: {key} is not a mapping") + reviews = doc["reviews"] + filters_absent = missing(reviews.get("path_filters"), want["path_filters"]) + if filters_absent is None: + raise Refusal(f"{path}: reviews.path_filters is not a list") branches = list(want["base_branches"]) pause = want["auto_pause_after_reviewed_commits"] enabled_ok = exactly(node.get("enabled"), want["enabled"]) pause_ok = exactly(node.get("auto_pause_after_reviewed_commits"), pause) - same = enabled_ok and pause_ok and node.get("base_branches") == branches + same = enabled_ok and pause_ok and node.get("base_branches") == branches and not filters_absent if existing is not None and same: return None if not enabled_ok: @@ -341,13 +409,25 @@ def plan_yaml(path: Path, want: dict[str, Any]) -> str | None: set_base_branches(node, branches) if not pause_ok: node["auto_pause_after_reviewed_commits"] = pause + if filters_absent: + from ruamel.yaml.comments import CommentedSeq + from ruamel.yaml.scalarstring import DoubleQuotedScalarString + + if reviews.get("path_filters") is None: + reviews["path_filters"] = CommentedSeq() + extend_keeping_comments( + reviews["path_filters"], [DoubleQuotedScalarString(item) for item in filters_absent] + ) out = StringIO() yaml.dump(doc, out) return out.getvalue() def plan_toml(path: Path, want: dict[str, Any]) -> str | None: - """The new .pr_agent.toml text, or None where it already holds the wanted value.""" + """The new .pr_agent.toml text, or None where it already holds the wanted values. + + Only config.disable_auto_feedback is set, and ignore.glob gains any required glob it lacks. + """ import tomlkit from tomlkit.exceptions import TOMLKitError @@ -361,10 +441,24 @@ def plan_toml(path: Path, want: dict[str, Any]) -> str | None: config = doc["config"] if not isinstance(config, dict): raise Refusal(f"{path}: config is not a table") + ignore = doc.get("ignore") + if ignore is not None and not isinstance(ignore, dict): + raise Refusal(f"{path}: ignore is not a table") + globs_absent = missing(None if ignore is None else ignore.get("glob"), want["ignore_glob"]) + if globs_absent is None: + raise Refusal(f"{path}: ignore.glob is not a list") value = want["disable_auto_feedback"] - if existing is not None and exactly(config.get("disable_auto_feedback"), value): + feedback_ok = exactly(config.get("disable_auto_feedback"), value) + if existing is not None and feedback_ok and not globs_absent: return None - config["disable_auto_feedback"] = value + if not feedback_ok: + config["disable_auto_feedback"] = value + if globs_absent: + if ignore is None: + doc["ignore"] = ignore = tomlkit.table() + if ignore.get("glob") is None: + ignore["glob"] = tomlkit.array() + ignore["glob"].extend(globs_absent) return tomlkit.dumps(doc) @@ -529,6 +623,9 @@ def judge(text: str) -> list[tuple[bool, str]]: enabled_ok = exactly(auto.get("enabled"), want["enabled"]) branches_ok = isinstance(branches, list) and set(branches) == set(want["base_branches"]) pause_ok = exactly(auto.get("auto_pause_after_reviewed_commits"), pause) + filters_absent = missing( + ((doc or {}).get("reviews") or {}).get("path_filters"), want["path_filters"] + ) return [ (enabled_ok, f"{YAML_PATH} reviews.auto_review.enabled is {want['enabled']}"), ( @@ -539,6 +636,10 @@ def judge(text: str) -> list[tuple[bool, str]]: pause_ok, f"{YAML_PATH} reviews.auto_review.auto_pause_after_reviewed_commits is {pause}", ), + ( + filters_absent == [], + f"{YAML_PATH} reviews.path_filters includes {want['path_filters']}", + ), ] return judge @@ -554,7 +655,13 @@ def judge(text: str) -> list[tuple[bool, str]]: except tomllib.TOMLDecodeError: return [(False, f"{TOML_PATH} does not parse as TOML")] got = (doc.get("config") or {}).get("disable_auto_feedback") - return [(exactly(got, want["disable_auto_feedback"]), msg)] + ignore = doc.get("ignore") + table = ignore is None or isinstance(ignore, dict) + globs_ok = table and missing((ignore or {}).get("glob"), want["ignore_glob"]) == [] + return [ + (exactly(got, want["disable_auto_feedback"]), msg), + (globs_ok, f"{TOML_PATH} ignore.glob includes {want['ignore_glob']}"), + ] return judge diff --git a/tests/test_agent_policy.py b/tests/test_agent_policy.py index 21b40efe1..94427d190 100755 --- a/tests/test_agent_policy.py +++ b/tests/test_agent_policy.py @@ -17,6 +17,7 @@ import subprocess import sys import tempfile +import tomllib import unittest from collections.abc import Mapping from pathlib import Path @@ -115,8 +116,12 @@ def test_default_facts(self) -> None: "enabled": True, "base_branches": ["^develop$"], "auto_pause_after_reviewed_commits": 0, + "path_filters": ["!.github/skills/**", "!lib/fleet/sh/**"], + }, + "qodo": { + "disable_auto_feedback": False, + "ignore_glob": [".github/skills/**", "lib/fleet/sh/**"], }, - "qodo": {"disable_auto_feedback": False}, }, ) @@ -138,9 +143,16 @@ def test_non_auto_bots_map_to_their_settings(self) -> None: "enabled": False, "base_branches": ["^release$"], "auto_pause_after_reviewed_commits": 0, + "path_filters": ["!.github/skills/**", "!lib/fleet/sh/**"], + }, + ) + self.assertEqual( + got["qodo"], + { + "disable_auto_feedback": True, + "ignore_glob": [".github/skills/**", "lib/fleet/sh/**"], }, ) - self.assertEqual(got["qodo"], {"disable_auto_feedback": True}) class WriteCase(unittest.TestCase): @@ -331,8 +343,13 @@ def test_a_malformed_yaml_file_is_refused_by_the_dry_run_too(self) -> None: """ -def want(enabled: bool, branches: list[str]) -> dict[str, object]: - return {"enabled": enabled, "base_branches": branches, "auto_pause_after_reviewed_commits": 0} +def want(enabled: bool, branches: list[str], filters: list[str] | None = None) -> dict[str, object]: + return { + "enabled": enabled, + "base_branches": branches, + "auto_pause_after_reviewed_commits": 0, + "path_filters": ["!docs/**"] if filters is None else filters, + } class YamlPreservationCase(unittest.TestCase): @@ -396,6 +413,152 @@ def test_an_enabled_flip_keeps_the_trailing_comment(self) -> None: self.assertEqual(got, HUB_SHAPED.replace("enabled: true #", "enabled: false #")) +QODO_GOOD = "[ignore]\nglob = ['.github/skills/**', 'lib/fleet/sh/**']\n\n[config]\ndisable_auto_feedback = false\n" + + +class CarriedExclusionCase(unittest.TestCase): + """Each rendered reviewer config skips the carried Skills tree, keeping the repository's own entries.""" + + SKILLS = "!.github/skills/**" + + def plan_yaml(self, text: str) -> str | None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / ".coderabbit.yaml" + path.write_text(text, encoding="utf-8") + return agent_policy.plan_yaml(path, want(True, ["^develop$"], [self.SKILLS])) + + def plan_toml(self, text: str | None) -> str | None: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / ".pr_agent.toml" + if text is not None: + path.write_text(text, encoding="utf-8") + wanted = {"disable_auto_feedback": False, "ignore_glob": [".github/skills/**"]} + return agent_policy.plan_toml(path, wanted) + + def test_a_yaml_filter_is_appended_after_the_repository_s_own(self) -> None: + got = self.plan_yaml(HUB_SHAPED) + assert got is not None + filters = agent_policy_yaml_load(got)["reviews"]["path_filters"] + self.assertEqual(filters, ["!docs/**", self.SKILLS]) + + def test_a_yaml_with_no_filters_gains_the_list(self) -> None: + got = self.plan_yaml( + "reviews:\n auto_review:\n enabled: true\n base_branches:\n" + ' - "^develop$"\n auto_pause_after_reviewed_commits: 0\n' + ) + assert got is not None + self.assertEqual(agent_policy_yaml_load(got)["reviews"]["path_filters"], [self.SKILLS]) + + def test_a_yaml_already_holding_the_filter_plans_nothing(self) -> None: + text = HUB_SHAPED.replace( + ' - "!docs/**"\n', f' - "!docs/**"\n - "{self.SKILLS}"\n' + ) + self.assertIsNone(self.plan_yaml(text)) + + def test_a_yaml_filter_that_is_not_a_list_is_refused(self) -> None: + with self.assertRaises(agent_policy.Refusal): + self.plan_yaml("reviews:\n path_filters: '!docs/**'\n") + + def test_a_toml_glob_is_appended_after_the_repository_s_own(self) -> None: + got = self.plan_toml( + "[ignore]\nglob = ['docs/**']\n\n[config]\ndisable_auto_feedback = false\n" + ) + assert got is not None + self.assertEqual(tomllib.loads(got)["ignore"]["glob"], ["docs/**", ".github/skills/**"]) + + def test_a_toml_with_no_ignore_table_gains_one(self) -> None: + got = self.plan_toml("[config]\ndisable_auto_feedback = false\n") + assert got is not None + doc = tomllib.loads(got) + self.assertEqual(doc["ignore"]["glob"], [".github/skills/**"]) + self.assertIs(doc["config"]["disable_auto_feedback"], False) + + def test_a_toml_already_holding_the_glob_plans_nothing(self) -> None: + self.assertIsNone(self.plan_toml(QODO_GOOD)) + + def test_a_toml_glob_that_is_not_a_list_is_refused(self) -> None: + with self.assertRaises(agent_policy.Refusal): + self.plan_toml("[ignore]\nglob = 'docs/**'\n") + + def test_a_comment_after_the_yaml_filters_stays_before_the_next_key(self) -> None: + tail = " # Explains the next key.\n path_instructions: []\n" + got = self.plan_yaml('reviews:\n path_filters:\n - "!docs/**"\n' + tail) + assert got is not None + self.assertIn(f' - "!docs/**"\n - "{self.SKILLS}"\n' + tail, got) + + def test_an_end_of_line_comment_stays_on_its_own_filter(self) -> None: + tail = " # Explains the next key.\n path_instructions: []\n" + got = self.plan_yaml('reviews:\n path_filters:\n - "!docs/**" # generated\n' + tail) + assert got is not None + self.assertIn(f' - "!docs/**" # generated\n - "{self.SKILLS}"\n' + tail, got) + + def test_a_toml_ignore_that_is_not_a_table_is_refused(self) -> None: + with self.assertRaises(agent_policy.Refusal): + self.plan_toml("ignore = 'docs/**'\n") + + def test_check_reports_a_malformed_ignore_as_drift(self) -> None: + rendered = agent_policy.render(None, "Fixture", "release") + want = agent_policy.facts(rendered)["qodo"] + globs = repr(want["ignore_glob"]) + for ignore in ("ignore = 'x'\n", f"ignore = {globs}\n", f"[[ignore]]\nglob = {globs}\n"): + with self.subTest(ignore=ignore): + text = ignore + "[config]\ndisable_auto_feedback = false\n" + got = agent_policy.judge_toml(want)(text) + self.assertEqual([ok for ok, _ in got], [True, False]) + + def test_rulesets_need_no_manifest(self) -> None: + with mock.patch.object(agent_policy, "carried_globs", side_effect=AssertionError("read")): + agent_policy.rulesets(None, "Fixture", "release") + + def test_the_globs_are_the_manifest_s_verbatim_trees(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + manifest = Path(tmp) / "files.json" + manifest.write_text( + json.dumps( + { + "trees": [ + {"target": "a/b", "fidelity": "verbatim-tree"}, + {"target": "c", "fidelity": "intent"}, + {"target": "d", "fidelity": "verbatim-tree", "appliesTo": ["x"]}, + ] + } + ), + encoding="utf-8", + ) + self.assertEqual(agent_policy.carried_globs(manifest), ["a/b/**", "d/**"]) + + def test_the_hub_s_own_files_hold_every_required_exclusion(self) -> None: + rendered = agent_policy.render(None, "Fixture", "release") + files = { + ".github/agent-policy.json": agent_policy.serialize(rendered), + ".coderabbit.yaml": (ROOT / ".coderabbit.yaml").read_text(encoding="utf-8"), + ".pr_agent.toml": (ROOT / ".pr_agent.toml").read_text(encoding="utf-8"), + } + got = agent_policy.check(rendered, lambda path: files[path]) + lists = [r.msg for r in got if "path_filters" in r.msg or "ignore.glob" in r.msg] + self.assertEqual(len(lists), 2) + self.assertEqual([m for m in lists if not next(r.ok for r in got if r.msg == m)], []) + + def test_check_fails_each_file_missing_an_exclusion(self) -> None: + rendered = agent_policy.render(None, "Fixture", "release") + files = { + ".github/agent-policy.json": agent_policy.serialize(rendered), + ".coderabbit.yaml": ( + "reviews:\n auto_review:\n enabled: true\n base_branches: ['^develop$']\n" + " auto_pause_after_reviewed_commits: 0\n path_filters: ['!docs/**']\n" + ), + ".pr_agent.toml": "[config]\ndisable_auto_feedback = false\n", + } + failed = [r.msg for r in agent_policy.check(rendered, lambda path: files[path]) if not r.ok] + self.assertEqual( + failed, + [ + ".coderabbit.yaml reviews.path_filters includes ['!.github/skills/**', '!lib/fleet/sh/**']", + ".pr_agent.toml ignore.glob includes ['.github/skills/**', 'lib/fleet/sh/**']", + ], + ) + + def agent_policy_yaml_load(text: str) -> dict[str, dict[str, dict[str, object]]]: from ruamel.yaml import YAML @@ -410,8 +573,9 @@ def setUp(self) -> None: ".coderabbit.yaml": ( "reviews:\n auto_review:\n enabled: true\n base_branches:\n - ^develop$\n" " auto_pause_after_reviewed_commits: 0\n" + " path_filters:\n - '!.github/skills/**'\n - '!lib/fleet/sh/**'\n" ), - ".pr_agent.toml": "[config]\ndisable_auto_feedback = false\n", + ".pr_agent.toml": QODO_GOOD, } def run_check(self, files: Mapping[str, str | None | Exception]) -> list[agent_policy.Result]: @@ -433,7 +597,7 @@ def test_drift_in_each_file_fails(self) -> None: drifted = copy.deepcopy(self.files) drifted[".github/agent-policy.json"] = "{}" drifted[".coderabbit.yaml"] = drifted[".coderabbit.yaml"].replace("^develop$", "^dev$") - drifted[".pr_agent.toml"] = "[config]\ndisable_auto_feedback = true\n" + drifted[".pr_agent.toml"] = QODO_GOOD.replace("= false", "= true") self.assertEqual(len(self.failures(drifted)), 3) def test_base_branches_compare_as_a_set(self) -> None: @@ -444,7 +608,7 @@ def test_base_branches_compare_as_a_set(self) -> None: files[".github/agent-policy.json"] = agent_policy.serialize(rendered) files[".coderabbit.yaml"] = ( "reviews:\n auto_review:\n enabled: true\n base_branches: ['^b$', '^a$']\n" - " auto_pause_after_reviewed_commits: 0\n" + " auto_pause_after_reviewed_commits: 0\n path_filters: ['!.github/skills/**', '!lib/fleet/sh/**']\n" ) got = agent_policy.check(rendered, lambda path: files[path]) self.assertTrue(all(r.ok for r in got), got) @@ -458,15 +622,17 @@ def test_a_coderabbit_file_that_pauses_fails(self) -> None: with self.subTest(pause=pause): files = dict(self.files) files[".coderabbit.yaml"] = ( - "reviews:\n auto_review:\n enabled: true\n base_branches:\n - ^develop$\n" - + pause + "reviews:\n path_filters: ['!.github/skills/**', '!lib/fleet/sh/**']\n auto_review:\n" + " enabled: true\n base_branches:\n - ^develop$\n" + pause ) (msg,) = self.failures(files) self.assertIn("auto_pause_after_reviewed_commits is 0", msg) def test_an_absent_qodo_key_fails(self) -> None: files = dict(self.files) - files[".pr_agent.toml"] = "[config]\nmodel = 'x'\n" + files[".pr_agent.toml"] = ( + "[ignore]\nglob = ['.github/skills/**', 'lib/fleet/sh/**']\n[config]\nmodel = 'x'\n" + ) self.assertEqual(len(self.failures(files)), 1) def test_a_missing_file_fails_naming_the_fix(self) -> None: @@ -615,8 +781,9 @@ def good(self) -> dict[str, str | None | Exception]: ".coderabbit.yaml": ( "reviews:\n auto_review:\n enabled: true\n base_branches: ['^develop$']\n" " auto_pause_after_reviewed_commits: 0\n" + " path_filters:\n - '!.github/skills/**'\n - '!lib/fleet/sh/**'\n" ), - ".pr_agent.toml": "[config]\ndisable_auto_feedback = false\n", + ".pr_agent.toml": QODO_GOOD, } def test_exit_codes(self) -> None: