diff --git a/.agents/skills/audit-a-repo/SKILL.md b/.agents/skills/audit-a-repo/SKILL.md index 07d623d23..b6e9ca42e 100644 --- a/.agents/skills/audit-a-repo/SKILL.md +++ b/.agents/skills/audit-a-repo/SKILL.md @@ -37,7 +37,7 @@ The audit is the fleet's measurement procedure. The failure shapes it guards aga - **Write `reports//audit.md` from `reports/_template.md`**, findings ranked most severe first, each with the `file:line` it was judged against, and quote the run stamp. The stamp is quoted because findings are a point-in-time snapshot. All of this is in `AUDIT.md` section 8. - **The hub authors the report.** A downstream repo never opens a hub pull request to write its own, which would be self-certification. Downstream context goes into issues filed against the hub instead. -- **Generate a convergence issue, never compose one**: `uv run --no-project --script spec/audit.py --issue ` emits it from live findings. An agent picking such an issue up re-runs the audit first and acts on the live result, not the pasted findings. +- **Generate a convergence issue, never compose one**: `uv run --no-project --script spec/audit.py --issue ` emits it from live findings. A finding judged by hand goes under the fixed `## Manual findings` heading that body ends with. That is the issue's one hand-written section, and regenerating replaces only the text above it (`AUDIT.md` section 8). An agent picking such an issue up re-runs the audit first and acts on the live result, not the pasted findings. - **Reconcile registry `driftNotes` in the same pass**: a resolved deviation's note is deleted, not left describing finished work. A note naming a check id is retired by a person, not by a run. All of this is in `AUDIT.md` section 8. - **Stale-versus-modified classification and the intent staleness advisory need a full hub clone with git history.** In a shallow clone the audit reports one ERROR per repo and exits non-zero, so run `git fetch --unshallow origin` in the hub checkout first. To verify one finding without history, compare against the current hub canonical on `main`, which decides current-match only. diff --git a/.claude-plugin/fleet-skills/.source-digests/audit-a-repo b/.claude-plugin/fleet-skills/.source-digests/audit-a-repo index a9f98d809..715d5f044 100644 --- a/.claude-plugin/fleet-skills/.source-digests/audit-a-repo +++ b/.claude-plugin/fleet-skills/.source-digests/audit-a-repo @@ -1 +1 @@ -b05d50ef6585a949 +a8f980ab83554509 diff --git a/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md b/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md index 07d623d23..b6e9ca42e 100644 --- a/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md +++ b/.claude-plugin/fleet-skills/skills/audit-a-repo/SKILL.md @@ -37,7 +37,7 @@ The audit is the fleet's measurement procedure. The failure shapes it guards aga - **Write `reports//audit.md` from `reports/_template.md`**, findings ranked most severe first, each with the `file:line` it was judged against, and quote the run stamp. The stamp is quoted because findings are a point-in-time snapshot. All of this is in `AUDIT.md` section 8. - **The hub authors the report.** A downstream repo never opens a hub pull request to write its own, which would be self-certification. Downstream context goes into issues filed against the hub instead. -- **Generate a convergence issue, never compose one**: `uv run --no-project --script spec/audit.py --issue ` emits it from live findings. An agent picking such an issue up re-runs the audit first and acts on the live result, not the pasted findings. +- **Generate a convergence issue, never compose one**: `uv run --no-project --script spec/audit.py --issue ` emits it from live findings. A finding judged by hand goes under the fixed `## Manual findings` heading that body ends with. That is the issue's one hand-written section, and regenerating replaces only the text above it (`AUDIT.md` section 8). An agent picking such an issue up re-runs the audit first and acts on the live result, not the pasted findings. - **Reconcile registry `driftNotes` in the same pass**: a resolved deviation's note is deleted, not left describing finished work. A note naming a check id is retired by a person, not by a run. All of this is in `AUDIT.md` section 8. - **Stale-versus-modified classification and the intent staleness advisory need a full hub clone with git history.** In a shallow clone the audit reports one ERROR per repo and exits non-zero, so run `git fetch --unshallow origin` in the hub checkout first. To verify one finding without history, compare against the current hub canonical on `main`, which decides current-match only. diff --git a/.github/skills/audit-a-repo/SKILL.md b/.github/skills/audit-a-repo/SKILL.md index 07d623d23..b6e9ca42e 100644 --- a/.github/skills/audit-a-repo/SKILL.md +++ b/.github/skills/audit-a-repo/SKILL.md @@ -37,7 +37,7 @@ The audit is the fleet's measurement procedure. The failure shapes it guards aga - **Write `reports//audit.md` from `reports/_template.md`**, findings ranked most severe first, each with the `file:line` it was judged against, and quote the run stamp. The stamp is quoted because findings are a point-in-time snapshot. All of this is in `AUDIT.md` section 8. - **The hub authors the report.** A downstream repo never opens a hub pull request to write its own, which would be self-certification. Downstream context goes into issues filed against the hub instead. -- **Generate a convergence issue, never compose one**: `uv run --no-project --script spec/audit.py --issue ` emits it from live findings. An agent picking such an issue up re-runs the audit first and acts on the live result, not the pasted findings. +- **Generate a convergence issue, never compose one**: `uv run --no-project --script spec/audit.py --issue ` emits it from live findings. A finding judged by hand goes under the fixed `## Manual findings` heading that body ends with. That is the issue's one hand-written section, and regenerating replaces only the text above it (`AUDIT.md` section 8). An agent picking such an issue up re-runs the audit first and acts on the live result, not the pasted findings. - **Reconcile registry `driftNotes` in the same pass**: a resolved deviation's note is deleted, not left describing finished work. A note naming a check id is retired by a person, not by a run. All of this is in `AUDIT.md` section 8. - **Stale-versus-modified classification and the intent staleness advisory need a full hub clone with git history.** In a shallow clone the audit reports one ERROR per repo and exits non-zero, so run `git fetch --unshallow origin` in the hub checkout first. To verify one finding without history, compare against the current hub canonical on `main`, which decides current-match only. diff --git a/AUDIT.md b/AUDIT.md index 07572fdb1..c2cfb5922 100644 --- a/AUDIT.md +++ b/AUDIT.md @@ -208,7 +208,7 @@ Write `reports//audit.md` from [`reports/_template.md`][template]. The rep A downstream repo uses its context where it is worth most. It **files findings about the hub as issues against `ptr727/ProjectTemplate`** and **applies fixes to its own repo** per section 10. Filing an issue is the opposite of self-certification, and it is how several hub defects have been found. Hub findings include bugs, conflicting sources, unclear or incomplete instructions, missing capabilities, and Copilot findings about any of them. Search open and closed issues first, then update the matching issue or file a new one. Any pull request it opens against the hub follows the standard branching model. It targets `develop`, never `main`. -**Findings are a point-in-time snapshot. Stamp them and re-verify before acting.** [`spec/audit.py`][audit-runner] prints a run stamp (`audit run | hub `) and, per repo, the exact commit it read (`@ @`). Anything derived from a run (a report, and especially an **onboarding or conformance issue**) quotes that stamp. That way a reader can tell whether it still applies. A convergence issue is generated from the audit, never composed by hand. `uv run --no-project --script spec/audit.py --issue ` emits a ready-to-file title and body from that repo's live findings (grouped into must-fix, converge, and could-not-verify). So the issue content cannot drift from what the audit actually found and regenerates as the repo changes. +**Findings are a point-in-time snapshot. Stamp them and re-verify before acting.** [`spec/audit.py`][audit-runner] prints a run stamp (`audit run | hub `) and, per repo, the exact commit it read (`@ @`). Anything derived from a run (a report, and especially an **onboarding or conformance issue**) quotes that stamp. That way a reader can tell whether it still applies. A convergence issue is generated from the audit, never composed by hand. `uv run --no-project --script spec/audit.py --issue ` emits a ready-to-file title and body from that repo's live findings (grouped into must-fix, converge, and could-not-verify). So the issue content cannot drift from what the audit actually found and regenerates as the repo changes. The one hand-written part is the last section, under the fixed `## Manual findings` heading the generated body ends with. A finding the audit judges by hand rather than detects cannot reach the generator. A per-type check from section 4 is one. Such a finding goes there with the file it was judged against. Regenerating the issue replaces only the text above that heading and keeps the section as written. **Verify a convergence before it is promoted with `--branch`.** `uv run --no-project --script spec/audit.py --branch ` reads that ref instead of the repo's registry `groundTruthBranch`. So a repo can audit its own `develop` while the work is still in flight rather than discovering the gaps after `main` has moved. The registry is not edited, and the run is still read-only. The run stamp names the override so a finding cannot be mistaken for one against ground truth. A ref that does not resolve is a single error naming it, never a baseline's worth of file-absent letters. A ref off the grammar a registry `groundTruthBranch` is held to, `GROUND_TRUTH_BRANCH_PATTERN` in [`spec/validate.py`][validate], is refused before anything is read. The run then exits `2` with one line on stderr naming the ref. diff --git a/spec/audit.py b/spec/audit.py index a88702740..5af4563f7 100755 --- a/spec/audit.py +++ b/spec/audit.py @@ -1708,22 +1708,23 @@ def contents_text(content): return base64.b64decode(content["content"]).decode("utf-8", "replace") -def read_baseline_file(slug, ground, path, alternatives=()): - """The path a baseline file was found at and its contents response, or `(path, None)`.""" +def read_baseline_file(slug, ref, path, alternatives=()): + """The path a baseline file was found at and its contents response at `ref`, a branch or a commit, or `(path, None)`.""" for candidate in (path, *alternatives): - content = gh(f"repos/{slug}/contents/{candidate}?ref={ground}", ok404=True) + content = gh(f"repos/{slug}/contents/{candidate}?ref={ref}", ok404=True) if content is not None: return candidate, content return path, None -def baseline_file_findings(slug, ground, path, alternatives, item): +def baseline_file_findings(slug, ground, path, alternatives, item, ref=None): """Read one baseline file, returning `(found, content, text, findings)` for what reading it alone owes. `found` is the path it was read at, a declared alternative included. `text` is None where the - API returned no inline content, and an empty file is an empty string. + API returned no inline content, and an empty file is an empty string. It is read at `ref`, the + audited head commit, where one is given, and a finding still names the `ground` branch. """ - found, content = read_baseline_file(slug, ground, path, alternatives) + found, content = read_baseline_file(slug, ref or ground, path, alternatives) fid = item.get("fidelity") if item else "presence" if content is None: if fid == "interface": @@ -1748,12 +1749,13 @@ def baseline_file_findings(slug, ground, path, alternatives, item): return found, content, contents_text(content), [] -def intent_trail(slug, ground, path, item, down_text, found): +def intent_trail(slug, ref, path, item, down_text, found): """`(canonical, (repo_date, hub_date, hub_sha))` where a copy possibly trails its intent canonical, else None. A last-modified comparison, since intent has no content check. A copy content-identical to the canonical, or to the hub's own file at `path` where the unit names no `reference`, is current. - `found` is the path the copy was read at, a declared alternative included. + `found` is the path the copy was read at, a declared alternative included. `ref` is the branch + or commit its last change is looked up from. """ canonical_rel, anchor = intent_ref(item, path) hub_change = hub_last_change(canonical_rel, anchor) @@ -1764,7 +1766,7 @@ def intent_trail(slug, ground, path, item, down_text, found): canon_text = canonical_current_text(rel) if rel else None if canon_text is not None and content_hash(down_text) == content_hash(canon_text): return None - commits = gh(f"repos/{slug}/commits?path={found}&sha={ground}&per_page=1") + commits = gh(f"repos/{slug}/commits?path={found}&sha={ref}&per_page=1") if not commits: return None repo_date = commits[0]["commit"]["committer"]["date"] @@ -1948,8 +1950,13 @@ def docs(self): if self.content.get(p) is not None } + @property + def ref(self): + """The head commit the tree was listed at, so a push landing mid-run cannot split the file reads across two commits.""" + return self.head["commit"]["sha"] + def read_text(self, path): - url = f"repos/{self.slug}/contents/{urllib.parse.quote(path)}?ref={self.ground}" + url = f"repos/{self.slug}/contents/{urllib.parse.quote(path)}?ref={self.ref}" return contents_text(gh(url)) def unread(self, family, path, purpose): @@ -2153,7 +2160,7 @@ def check_secrets_names(run): def check_dependabot_ecosystems(run): """An ecosystem the tree implies, github-actions for workflows and devcontainers for a .devcontainer, is declared.""" text = contents_text( - gh(f"repos/{run.slug}/contents/.github/dependabot.yml?ref={run.ground}", ok404=True) + gh(f"repos/{run.slug}/contents/.github/dependabot.yml?ref={run.ref}", ok404=True) ) if not text: return [] @@ -2166,12 +2173,12 @@ def check_dependabot_ecosystems(run): ) ] implied = {} - workflows = gh(f"repos/{run.slug}/contents/.github/workflows?ref={run.ground}", ok404=True) + workflows = gh(f"repos/{run.slug}/contents/.github/workflows?ref={run.ref}", ok404=True) if isinstance(workflows, list) and any( e["name"].endswith((".yml", ".yaml")) for e in workflows ): implied["github-actions"] = ".github/workflows/ is present" - if gh(f"repos/{run.slug}/contents/.devcontainer?ref={run.ground}", ok404=True) is not None: + if gh(f"repos/{run.slug}/contents/.devcontainer?ref={run.ref}", ok404=True) is not None: implied["devcontainers"] = ".devcontainer/ is present" return [ ( @@ -2185,7 +2192,12 @@ def check_dependabot_ecosystems(run): def check_files_presence(run, path): found, content, text, findings = baseline_file_findings( - run.slug, run.ground, path, run.alternatives.get(path, []), run.baseline[path][0] + run.slug, + run.ground, + path, + run.alternatives.get(path, []), + run.baseline[path][0], + run.ref, ) if content is not None: run.content[path] = text @@ -2199,7 +2211,7 @@ def check_files_intent(run): if path not in run.content or (item or {}).get("fidelity") != "intent": continue found = run.found[path] - trail = intent_trail(run.slug, run.ground, path, item, run.content[path], found) + trail = intent_trail(run.slug, run.ref, path, item, run.content[path], found) if trail is not None: trails[found] = trail return intent_findings(run.entry, run.ground, trails) @@ -2504,15 +2516,15 @@ def check_readme_tools(run): def check_cspell_workspace(run): """cspell.json is the one word list, so a workspace file's own cSpell list duplicates it.""" - if gh(f"repos/{run.slug}/contents/cspell.json?ref={run.ground}", ok404=True) is None: + if gh(f"repos/{run.slug}/contents/cspell.json?ref={run.ref}", ok404=True) is None: return [] findings = [] - for it in gh(f"repos/{run.slug}/contents/?ref={run.ground}", ok404=True) or []: + for it in gh(f"repos/{run.slug}/contents/?ref={run.ref}", ok404=True) or []: ws_name = it.get("name", "") if isinstance(it, dict) else "" if not ws_name.endswith(".code-workspace"): continue ws_text = contents_text( - gh(f"repos/{run.slug}/contents/{ws_name}?ref={run.ground}", ok404=True) + gh(f"repos/{run.slug}/contents/{ws_name}?ref={run.ref}", ok404=True) ) if ws_text is None: findings.append( @@ -2583,30 +2595,36 @@ def _selftest_cases(): return 0 if ok else 1 +MANUAL_HEADING = "## Manual findings" + + def render_issue(entry, findings, ground, audited_sha, run_utc, hub_sha): - """A ready-to-file convergence issue (title, body) generated from one repo's audit findings.""" + """A ready-to-file convergence issue (title, body) generated from one repo's audit findings. + + The body ends at the fixed MANUAL_HEADING, the one section written by hand, per AUDIT.md section 8. + """ name = entry["name"] types = ", ".join(declared_types(entry)) or "untyped" stamp = f"{ground}@{audited_sha[:7]}" if audited_sha else ground blocking = [(k, t) for k, t in findings if k in ("DEFECT", "LETTER")] drift = [t for k, t in findings if k == "DRIFT"] errors = [t for k, t in findings if k == "ERROR"] - title = f"Converge {name} with the hub baseline ({len(findings)} finding{'' if len(findings) == 1 else 's'})" + title = f"Converge {name} with the hub baseline ({len(findings)} detected finding{'' if len(findings) == 1 else 's'})" out = [] w = out.append # No H1, since GitHub renders the issue title as the heading. w( f"Generated from the hub audit of `{name}` ({types}). Run stamp `audit run {run_utc} | hub {hub_sha}`, " - f"against `@ {stamp}` (the format AUDIT.md section 8 says a derived artifact quotes). Regenerate with " - f"`uv run --no-project --script spec/audit.py --issue {name}`. Findings are a point-in-time snapshot - re-run the audit before acting. " + f"against `@ {stamp}` (the format AUDIT.md section 8 says a derived artifact quotes). To regenerate, run " + f"`uv run --no-project --script spec/audit.py --issue {name}` and replace only the text above `{MANUAL_HEADING}`, keeping that section as written. Findings are a point-in-time snapshot - re-run the audit before acting. " f"This lists what the audit mechanically detects. No check belonging to a project type in `spec/project-types.json` is run " f"here, and the cross-cutting dimensions are covered only in part, so the full letter and intent verdict lives in AUDIT.md section 4." ) w("") if not findings: - w("The deterministic checks are clean - nothing to converge.") - return title, "\n".join(out) + "\n" + w("The deterministic checks are clean - nothing to converge from them.") + w("") if blocking: w("## Must fix") w("") @@ -2637,6 +2655,13 @@ def render_issue(entry, findings, ground, audited_sha, run_utc, hub_sha): for t in errors: w(f"- {t}") w("") + w(MANUAL_HEADING) + w("") + w( + "Written by hand, for a finding the audit judges by hand rather than detects, such as a check " + "under a type in `spec/project-types.json`. Each one goes below this line with the file it was " + "judged against. Regenerating replaces only the text above this heading." + ) return title, "\n".join(out).rstrip() + "\n" diff --git a/spec/divergences.json b/spec/divergences.json index 346f6835b..43ca9635f 100644 --- a/spec/divergences.json +++ b/spec/divergences.json @@ -30,6 +30,9 @@ { "path": ".github/workflows/deploy-site-task.yml", "disposition": "retire", "reason": "The task is hub-hosted per docs/reusable-workflows.md \"Adopting the Type-Specific Tasks\", so it is no longer a manifest entry (spec/files.json keeps only the deploy-site.yml caller stub entry for the hugo type) and a downstream copy is retired rather than converged. The carrier is Blog, replacing its copy with the caller stub once a release carries the task.", "tracking": null }, { "path": ".github/workflows/publish-docker-readme-task.yml", "disposition": "retire", "reason": "The task is hub-hosted per docs/reusable-workflows.md \"The Docker Family\", so a downstream copy of the job graph is retired rather than converged. The carrier is VSCode-Server-DotNetCore, whose copy replaces with the caller stub in docs/reusable-workflows.md \"Adopting the Type-Specific Tasks\" once a release carries the task.", "tracking": null }, { "path": ".github/workflows/check-upstream-version-task.yml", "disposition": "retire", "reason": "The task is hub-hosted per docs/reusable-workflows.md \"The Docker Family\", so a downstream copy of the job graph is retired rather than converged. The carrier is ESPHome-NonRoot, whose check-upstream-version.yml caller and check-upstream-version-task.yml body both replace with the caller stub once a release carries the task. Its second tracker, check-upstream-dependency.yml, is a candidate to fold into the same hub task with auto-merge false, tracked as an adoption note rather than a gap here since it was never a copy of this snippet.", "tracking": null }, + { "path": ".coderabbit.yaml", "disposition": "accepted", "reason": "Rendered per repository rather than carried. repo-config/configure.sh renders .github/agent-policy.json from the repository's registry entry through scripts/agent_policy.py, sets the reviewer values derived from it in .coderabbit.yaml and .pr_agent.toml while keeping every other setting there, and its check mode compares each of the three on the default branch with that render. The policy differs by repository and the two reviewer files mix derived values with the repository's own, so no spec/files.json fidelity describes any of them, and a manifest entry would have the audit compare text the render already judges. configure.sh check is the conformance check, so the audit accepts the copy rather than reporting it as hub-hosted content to delete.", "tracking": null }, + { "path": ".github/agent-policy.json", "disposition": "accepted", "reason": "Rendered per repository rather than carried. repo-config/configure.sh renders .github/agent-policy.json from the repository's registry entry through scripts/agent_policy.py, sets the reviewer values derived from it in .coderabbit.yaml and .pr_agent.toml while keeping every other setting there, and its check mode compares each of the three on the default branch with that render. The policy differs by repository and the two reviewer files mix derived values with the repository's own, so no spec/files.json fidelity describes any of them, and a manifest entry would have the audit compare text the render already judges. configure.sh check is the conformance check, so the audit accepts the copy rather than reporting it as hub-hosted content to delete.", "tracking": null }, + { "path": ".pr_agent.toml", "disposition": "accepted", "reason": "Rendered per repository rather than carried. repo-config/configure.sh renders .github/agent-policy.json from the repository's registry entry through scripts/agent_policy.py, sets the reviewer values derived from it in .coderabbit.yaml and .pr_agent.toml while keeping every other setting there, and its check mode compares each of the three on the default branch with that render. The policy differs by repository and the two reviewer files mix derived values with the repository's own, so no spec/files.json fidelity describes any of them, and a manifest entry would have the audit compare text the render already judges. configure.sh check is the conformance check, so the audit accepts the copy rather than reporting it as hub-hosted content to delete.", "tracking": null }, { "path": ".github/workflows/run-codegen-pull-request-task.yml", "disposition": "retire", "reason": "The task is hub-hosted per docs/reusable-workflows.md \"Adopting the Type-Specific Tasks\", so a downstream copy of the job graph is retired rather than converged. A carrier replaces its copy with a codegen hook plus the caller stub once a release carries the task.", "tracking": null }, { "path": ".github/workflows/build-datebadge-task.yml", "disposition": "retire", "reason": "TODO.md \"Delete the retired byob.yarr.is last-build badge\" already settles that the badge service is deprecated and the badge itself is deleted rather than replaced, so this task is retired outright rather than hosted. The carrier is KiCadLibrary, whose deletion here is the same deletion that TODO.md entry already tracks for its badge job, not a separate migration.", "tracking": null } ] diff --git a/tests/test_audit.py b/tests/test_audit.py index 236be2682..fd158035d 100755 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -22,7 +22,8 @@ "hasDevelop": False, } CARRIED = {"pyproject.toml", "tests/test_a.py"} -HEAD = {"commit": {"sha": "c0ffee", "commit": {"tree": {"sha": "feed"}}}} +HEAD_SHA = "c0ffee" +HEAD = {"commit": {"sha": HEAD_SHA, "commit": {"tree": {"sha": "feed"}}}} CODECOV = { "path": "codecov.yml", "alternatives": [".codecov.yml"], @@ -34,7 +35,8 @@ class FakeGh: """The REST reads audit_repo makes, answered for a repository carrying exactly `tree`. An unanticipated read fails the test rather than answering. A guessed answer could steer - audit_repo past the loop under test while still reading as a pass. + audit_repo past the loop under test while still reading as a pass. A path in `moved` is one a + push deleted after the tree was listed, so it resolves at the head commit and nowhere else. """ def __init__( @@ -43,11 +45,13 @@ def __init__( modes: dict[str, str] | None = None, unread: frozenset[str] = frozenset(), texts: dict[str, str] | None = None, + moved: frozenset[str] = frozenset(), ) -> None: self.tree = tree self.modes = modes or {} self.unread = unread self.texts = texts or {} + self.moved = moved self.paths: list[str] = [] def __call__(self, path: str, ok404: bool = False) -> Any: @@ -69,7 +73,7 @@ def __call__(self, path: str, ok404: bool = False) -> Any: return {"tree": blobs, "truncated": False} if base.startswith(f"repos/{SLUG}/contents/"): name = base.split("/contents/", 1)[1] - if name in self.unread: + if name in self.unread or (name in self.moved and path != f"{base}?ref={HEAD_SHA}"): if ok404: return None raise RuntimeError(f"gh api {path}: HTTP 404") @@ -87,12 +91,13 @@ def run_audit( unread: frozenset[str] = frozenset(), hub: frozenset[str] = frozenset(), texts: dict[str, str] | None = None, + moved: frozenset[str] = frozenset(), ) -> tuple[list[tuple[str, str]], FakeGh]: """Audit a Python repository carrying `tree`, where a test module makes codecov.yml owed. The hub's tracked paths come from a fetch of its origin. Answering them with `hub` keeps the - run offline and leaves the checkout the suite runs in untouched. The repo-owned trees are the - shipped declaration, so a test reads the exclusion the real audit applies. + run offline and leaves the checkout the suite runs in untouched. The repo-owned trees and the + gap ledger are the shipped declarations, so a test reads the exclusions the real audit applies. """ spec = { "registry": {"repos": [ENTRY], "defaults": {}}, @@ -102,8 +107,9 @@ def run_audit( "baseline": [CODECOV], "repoOwnedTrees": audit.load("spec/files.json")["repoOwnedTrees"], }, + "divergences": audit.load("spec/divergences.json"), } - fake = FakeGh(tree, modes, unread, texts) + fake = FakeGh(tree, modes, unread, texts, moved) with ( mock.patch.object(audit, "gh", fake), mock.patch.object(audit, "hub_tracked", lambda rev=None: hub), @@ -123,7 +129,7 @@ class AuditRepoAlternativesCase(unittest.TestCase): def test_a_repository_holding_only_the_alternative_carries_the_file(self) -> None: findings, fake = run_audit(CARRIED | {".codecov.yml"}) - self.assertIn(f"repos/{SLUG}/contents/.codecov.yml?ref=main", fake.paths) + self.assertIn(f"repos/{SLUG}/contents/.codecov.yml?ref={HEAD_SHA}", fake.paths) absent = [text for _, text in findings if text.startswith("file: codecov.yml")] self.assertEqual(absent, []) @@ -147,7 +153,7 @@ class AuditRepoNamingCase(unittest.TestCase): """audit_repo hands the tree it read, modes included, to the file-naming and secret-stem checks. Each check's own cases are covered by tests/test_audit_helpers.py, so what this adds is the call - site: the modes reaching the file-naming check, and its shebang read going to the audited branch. + site: the modes reaching the file-naming check, and its shebang read going to the audited head. """ def naming_findings(self, findings: list[tuple[str, str]]) -> list[str]: @@ -175,7 +181,7 @@ def test_each_non_conforming_shape_is_reported(self) -> None: } findings, fake = run_audit(tree, {"bin/Run_Backup": "100755"}) - self.assertIn(f"repos/{SLUG}/contents/bin/Run_Backup?ref=main", fake.paths) + self.assertIn(f"repos/{SLUG}/contents/bin/Run_Backup?ref={HEAD_SHA}", fake.paths) self.assertEqual( self.naming_findings(findings), [ @@ -199,7 +205,7 @@ def test_each_non_conforming_shape_is_reported(self) -> None: ) def test_a_bare_secrets_directory_is_read_from_the_tracked_files_naming_it(self) -> None: - """The issue's constructed case: nothing under secrets/ is tracked, so the audited branch's files are read.""" + """The issue's constructed case: nothing under secrets/ is tracked, so the audited head's files are read.""" texts = { ".gitignore": "secrets/\n", ".vscode/launch.json": ( @@ -208,7 +214,7 @@ def test_a_bare_secrets_directory_is_read_from_the_tracked_files_naming_it(self) } findings, fake = run_audit(CARRIED | {".codecov.yml"} | set(texts), texts=texts) - self.assertIn(f"repos/{SLUG}/contents/.vscode/launch.json?ref=main", fake.paths) + self.assertIn(f"repos/{SLUG}/contents/.vscode/launch.json?ref={HEAD_SHA}", fake.paths) self.assertEqual( self.naming_findings(findings), [ @@ -234,6 +240,42 @@ def test_a_failed_shebang_read_raises_rather_than_reading_as_undecided(self) -> run_audit(tree, {"bin/Run_Backup": "100755"}, frozenset({"bin/Run_Backup"})) +class AuditRepoHeadCommitCase(unittest.TestCase): + """audit_repo reads content at the head commit it listed the tree at, not at the branch name. + + A push landing between the two reads would otherwise answer a listed path with a 404. A read + that treats a 404 as a failure would then turn the whole repository's result into one ERROR. + """ + + def test_a_path_deleted_after_the_tree_was_listed_is_still_judged(self) -> None: + tree = CARRIED | {".codecov.yml", "bin/Run_Backup"} + findings, fake = run_audit( + tree, {"bin/Run_Backup": "100755"}, moved=frozenset({"bin/Run_Backup", ".codecov.yml"}) + ) + + self.assertEqual([kind for kind, _ in findings if kind == "ERROR"], []) + self.assertIn(f"repos/{SLUG}/contents/bin/Run_Backup?ref={HEAD_SHA}", fake.paths) + self.assertTrue( + any("bin/Run_Backup (an executable with no shebang)" in text for _, text in findings), + findings, + ) + self.assertEqual([text for _, text in findings if text.startswith("file: codecov.yml")], []) + + def test_every_content_read_names_the_head_commit(self) -> None: + _, fake = run_audit(CARRIED | {".codecov.yml", "cspell.json", ".github/dependabot.yml"}) + + contents = [p for p in fake.paths if "/contents/" in p or "/commits?" in p] + self.assertTrue(contents) + self.assertEqual( + [ + p + for p in contents + if not p.endswith((f"ref={HEAD_SHA}", f"sha={HEAD_SHA}&per_page=1")) + ], + [], + ) + + class AuditRepoHubOnlyCase(unittest.TestCase): """audit_repo leaves a carrier's own test module out of the hub-only check. @@ -260,6 +302,15 @@ def test_a_hub_only_path_outside_tests_is_still_reported(self) -> None: any(text.startswith("hub-only: tools/hub_tool.py ") for text in hub_only), hub_only ) + def test_the_rendered_reviewer_configs_are_not_reported(self) -> None: + """The hub renders these per repository and repo-config/configure.sh check judges them.""" + rendered = {".coderabbit.yaml", ".github/agent-policy.json", ".pr_agent.toml"} + findings, _ = run_audit( + CARRIED | {".codecov.yml"} | rendered, hub=self.HUB | frozenset(rendered) + ) + + self.assertEqual(self.hub_only_findings(findings), []) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_audit_helpers.py b/tests/test_audit_helpers.py index 104d202fb..e9fa8dd4f 100755 --- a/tests/test_audit_helpers.py +++ b/tests/test_audit_helpers.py @@ -1513,15 +1513,28 @@ def test_render_issue_grouping(self) -> None: et, eb = audit.render_issue(fe, [], "main", "abc1234", "2026-01-01T00:00:00Z", "hub123") msg = "issue: render_issue grouping/title/empty behavior" self.assertIn("Widget", it, msg) - self.assertIn("(3 findings)", it, msg) + self.assertIn("(3 detected findings)", it, msg) self.assertIn("## Must fix", ib, msg) self.assertIn("**LETTER** file: X absent", ib, msg) self.assertIn("## Converge", ib, msg) self.assertIn("verbatim: Y differs", ib, msg) self.assertIn("## Could not verify", ib, msg) - self.assertIn("(0 findings)", et, msg) + self.assertIn("(0 detected findings)", et, msg) self.assertIn("nothing to converge", eb, msg) + def test_render_issue_ends_at_the_manual_findings_section(self) -> None: + """Both bodies end in the one hand-written section, so regenerating can keep it, per AUDIT.md section 8.""" + fe = {"name": "Widget", "types": ["python"]} + for findings in ([], [("DRIFT", "verbatim: Y differs"), ("ERROR", "gh failed")]): + with self.subTest(findings=len(findings)): + _, body = audit.render_issue( + fe, findings, "main", "abc1234", "2026-01-01T00:00:00Z", "hub123" + ) + headings = [line for line in body.splitlines() if line.startswith("## ")] + self.assertEqual(headings[-1], audit.MANUAL_HEADING) + self.assertEqual(headings.count(audit.MANUAL_HEADING), 1) + self.assertIn(f"replace only the text above `{audit.MANUAL_HEADING}`", body) + def test_title_and_intro_mirror(self) -> None: r_md = "# Widget \n\nDoes widget things.\n\n## Build\n" h_md = "# Widget\n\nDoes widget things.\n\n## Release History\n" @@ -2965,6 +2978,7 @@ def test_baseline_file_findings_neither(self) -> None: def intent_run(baseline: dict[str, Any], content: dict[str, str], notes: list[str]) -> Any: """A non-hub Run holding `content` as read, for check_files_intent.""" run = audit.Run({"name": "Widget", "driftNotes": notes}, {}, "o/r", "main", {}, None, None) + run.head = {"commit": {"sha": "c0ffee"}} run.__dict__["baseline"] = {p: (item, set(), set()) for p, item in baseline.items()} run.content.update(content) run.found.update({p: p for p in content}) @@ -3090,7 +3104,7 @@ def fake(ep: str, ok404: bool = False) -> Any: mock.patch.object(audit, "gh", fake), ): findings = audit.check_files_intent(run) - self.assertEqual(asked, ["repos/o/r/commits?path=.codecov.yml&sha=main&per_page=1"]) + self.assertEqual(asked, ["repos/o/r/commits?path=.codecov.yml&sha=c0ffee&per_page=1"]) self.assertEqual([t.split(" ", 2)[1] for _, t in findings], want) def test_the_anchor_is_read_only_from_an_intent_ref(self) -> None: @@ -5496,10 +5510,11 @@ def gh(path: str, ok404: bool = False) -> Any: def test_an_unparsed_dependabot_file_is_one_finding(self) -> None: run = audit.Run({"name": "Widget"}, {}, "o/r", "main", {}, None, None) + run.head = {"commit": {"sha": "c0ffee"}} bad = {"encoding": "base64", "content": base64.b64encode(b"updates:\n - [\n").decode()} def gh(path: str, ok404: bool = False) -> Any: - return bad if path.endswith("dependabot.yml?ref=main") else None + return bad if path.endswith("dependabot.yml?ref=c0ffee") else None with mock.patch.object(audit, "gh", gh): got = audit.check_dependabot_ecosystems(run)