From e2838080aed9cc408d849073c1067214fcf00dd0 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:47:01 +0800 Subject: [PATCH 1/2] fix(review): preserve complete repository guidance in OCR --- .github/workflows/README.md | 24 +- .github/workflows/ci.yml | 2 - .opencodereview/review-rules.generated.md | 246 +++++++++++++++++ .opencodereview/review-rules.md | 2 +- .opencodereview/rule.json | 2 +- AGENTS.md | 3 + Makefile | 7 +- harness/review_guidelines.py | 213 +++++++++++++++ review-guidelines.lock.json | 7 +- scripts/review_guidelines.py | 147 +---------- tests/test_review_guidelines.py | 306 ++++++++++++++++++++++ 11 files changed, 804 insertions(+), 155 deletions(-) create mode 100644 .opencodereview/review-rules.generated.md create mode 100644 harness/review_guidelines.py create mode 100644 tests/test_review_guidelines.py diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 8651ebb62..b18a6835b 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -6,13 +6,33 @@ Three jobs run independently: | Job | Coverage | | --- | --- | -| Tests and static checks | `make ci-tests`: naming, lint, the complete Python suite, Node UI/native-adapter tests and the fixture smoke test | +| Tests and static checks | `make ci-tests`: review guidance, naming, lint, the complete Python suite, Node UI/native-adapter tests and the fixture smoke test | | Installation and packaging | Base installation and CLI language checks, sdist/pip installation, wheel smoke checks and all existing optional installation profiles | | Rendered reference and report checks | Chromium reference capture, report interactions and Web Search visual checks | The Python suite uses two workers with `--dist loadfile`, keeping each test file in one process. Slow-test durations appear in the job log. Local `make ci` remains serial by default; use `make ci PYTEST_ARGS='-n 2 --dist loadfile --durations=20'` for the same test scheduling. -The checks job also verifies the pinned shared review guide and synchronization tool against `review-guidelines.lock.json`, and confirms that OCR loads the shared guide alongside its built-in rules. This offline integrity check needs no cross-repository credentials. Use `uv run --frozen python scripts/review_guidelines.py check --source ` to also compare the files with their recorded source commit. Shared requirements are maintained in `lexmount/ai-template-py`; Browser Eval's review supplement remains in `.opencodereview/review-rules.md`. +`make review-check` runs inside both `make ci-tests` and local `make ci`. The version 2 `review-guidelines.lock.json` pins only the shared policy text in `docs/references/review-guidelines.md`, using a full merged commit from `lexmount/ai-template-py` and a SHA-256 checksum. Maintenance logic in `harness/review_guidelines.py` is ordinary repository code, covered by the default Python test suite; `scripts/review_guidelines.py` is its command entry point. + +OCR reads `.opencodereview/review-rules.generated.md`, containing the complete shared guide and Browser Eval's supplement from `.opencodereview/review-rules.md`, alongside its built-in rules. The supplement explicitly points to `AGENTS.md` and `CONTRIBUTING.md`. OCR selects the first matching rule, so adding another rule does not combine their contents. Verification checks each reachable route and rejects a route that drops shared guidance, local requirements or built-in rules. + +After editing the local supplement, regenerate the review entry and check it: + +```sh +uv run --frozen python scripts/review_guidelines.py render +make review-check +``` + +To update shared policy, use a trusted template checkout containing the selected merged commit: + +```sh +uv run --frozen python scripts/review_guidelines.py sync --source --ref . +uv run --frozen python scripts/review_guidelines.py check --source +``` + +Synchronization updates the shared guide, generated entry and source lock; it preserves local requirements and executable code. Targets must already configure the generated review entry. Standard HTTPS and SSH remote spellings are accepted under any remote name. The configured URL identifies the intended source; use a trusted checkout because offline checks do not authenticate GitHub. The ordinary check verifies local checksums and composition without network access; `--source` additionally compares bytes with the recorded Git commit. + +Batch updates validate all destinations first, then process repositories sequentially. Complete files are staged on the destination filesystem and replaced atomically, with the lock last. A replacement failure can leave mixed versions in the current repository, which verification rejects; retrying the same source revision repairs it. Earlier completed repositories retain their updates. Synchronization does not commit or push changes. The existing `Python 3.11` status succeeds only when all three jobs succeed. A failed, cancelled or skipped job fails that status. New commits cancel obsolete CI runs for the same pull request. Main and tag runs each have a unique concurrency group, so a newer run cannot replace an earlier pending run. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a9f94279..6af3ab95f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,8 +34,6 @@ jobs: node-version: "22" cache: npm - run: make setup-test - - name: Verify shared review guidance - run: uv run --frozen --no-sync python scripts/review_guidelines.py check - run: make ci-tests PYTEST_ARGS='-n 2 --dist loadfile --durations=20' package: diff --git a/.opencodereview/review-rules.generated.md b/.opencodereview/review-rules.generated.md new file mode 100644 index 000000000..086659bb1 --- /dev/null +++ b/.opencodereview/review-rules.generated.md @@ -0,0 +1,246 @@ + + +# Review Guidelines + +The canonical version of this document lives in `lexmount/ai-template-py` at +`docs/references/review-guidelines.md`. Consumer repositories synchronize their +copies with `scripts/review_guidelines.py` and pin the source revision in +`review-guidelines.lock.json`. Change the canonical document rather than editing +a synchronized copy. + +OCR's official rules remain the foundation. This document adds shared review, +scope, and feedback requirements. Read the repository's local review supplement +for its domain requirements. Use the review language required by the user or +repository; preserve code identifiers, commands, schema values, and product names. + +## Establish the review basis + +Read the task goal, PR description, linked issues and plans, user agreements, +acceptance criteria, and available validation results. Read all top-level +conversation comments, formal review bodies, inline threads, and replies. Earlier +reviews provide evidence and the status of earlier findings; they do not replace +an independent assessment of the current candidate. + +Confirm the target branch and current head. Read the complete net diff from their +actual merge base to head, together with all unmerged commits. A `synchronize` +event or triggering commit starts a review; it does not redefine the PR as only +that increment. Inspect every changed file assigned by the tool, using other +files to establish impact. A complete PR review must cover the full net diff, not +infer scope from the title. Correct a stale checkpoint before reviewing; if the +correct diff is unavailable, report the input problem rather than attributing +existing target-branch changes to this PR. + +Follow the repository entry points to the architecture, interface, code-style, +security, and deployment guidance relevant to the affected components. Read local +supplements and linked component documents where applicable. Concrete product +constraints belong in those sources rather than a shared product checklist. +Consult existing code, callers, history, and upstream sources to establish impact. +Reading more code does not expand this PR's responsibility for fixing it. + +## Decide whether a finding belongs to this PR + +Each finding must meet both conditions: + +1. Identify the specific change that introduces, triggers, or worsens the problem, + or the agreed task requirement that remains unimplemented. A new path can + trigger a defect in old code. Merely finding a defect in the same file or call + chain does not make it part of this PR. +2. Ground the finding in a code path, reproduction, test, or explicit contract. + For behavior defects, explain a reachable trigger and its consequences, + including error paths and untrusted inputs, and account for existing validation + and caller constraints. For a mandatory-rule violation, cite the applicable + rule and the changed location that violates it. Do not present an unproven + runtime failure as its consequence. + +Keep proposed fixes proportionate to the problem and preserve correct behavior. +Do not attach surrounding cleanup, a global redesign, or new product requirements. +A confirmed defect remains reportable when its exact fix is not yet known. + +Mandatory official and repository rules still apply to violations introduced or +worsened by the change. Preferences such as "prefer" or "where practical" allow +contextual choices; a different preference is not itself a defect. Explain the +conflicting rules, responsibilities, resource ownership, or maintenance cost +behind a design finding. File length or a tidier alternative alone does not +justify a rewrite. + +Keep independent historical defects out of this PR's fix list; identify their +separate ownership when follow-up is needed. A material validation gap must name +the affected scenario and the evidence needed. Missing command output alone does +not establish a code defect. Investigate a suspected regression against its +history and current reachable paths before reporting it as confirmed. + +## Required checks + +Apply these questions to the current changes and affected behavior. Use the +evidence and ownership conditions above when reporting findings or requesting fixes. + +1. **Goal and approach.** What real problem does the PR solve, which user scenarios + does it affect, and what behavior should change or remain unchanged? Does the + description match the existing code? Is the approach necessary, and does it + implement the whole goal? +2. **Acceptance criteria.** Are all success criteria covered? Has a review with no + findings been mistaken for verification that the requirements are met? +3. **Repository requirements.** Does the change follow the repository entry points, + project overview, architecture sources, and language and code-style guidance? +4. **Architecture boundaries.** Does the change preserve dependency direction, + module responsibilities, data flow, and ownership? Trace the actual producers + and consumers through callers, state, branches, configuration, caches, + asynchronous work, and errors. Where identities, sessions, tasks, or resources + are involved, do concurrency, cancellation, and cleanup respect their ownership + and permission boundaries? +5. **Simplicity.** Is this the simplest implementation that meets the goal? Does it + add unnecessary state, configuration, abstractions, or dependencies? +6. **Regression and compatibility.** Along affected call paths, do existing correct + features, default configurations, old data, and recovery scenarios still work? + Does the change introduce a bug or break an existing agreement? When replacing + an entry point, removing code, or changing an interface, test the replacement + against the original supported scenarios, not just whether the new entry point + runs. An intentional behavior change needs an explicit requirement and any + necessary migration arrangements. +7. **Reuse and maintainability.** Are the responsibilities, names, and locations of + modules, interfaces, classes, and functions clear? Are files becoming too large + to keep those responsibilities clear? Who owns state and resources, and is the + same rule implemented in several places? Prefer existing shared capabilities; + logic used by several real callers belongs at a suitable shared boundary rather + than in a PR-specific copy. Another instance of an already supported kind should + extend its existing owner through data, configuration, or a registry when that + contract supports it, rather than require scattered instance-specific branches. + Abstractions should express stable responsibilities and simplify callers and + tests. Use classes and composition when state, lifecycle, or a replaceable + protocol needs encapsulation; keep simple stateless logic as functions. Do not + require object-oriented design, inheritance, or a framework for hypothetical + needs. A design finding must identify a concrete maintenance cost or error risk, + the responsibility or constraint to restore, and the smallest fix when known. + Personal style alone is not grounds for rewriting code. +8. **Necessity of each file.** Is every assigned changed file relevant and necessary + to the goal? Flag scope creep and unrelated changes to another owner's logic. + Explain how each defect was introduced or triggered by this PR, including + regressions caused by its fixes. Inspect affected shared paths and similar + instances of a confirmed defect so the fix covers the same problem within the + affected scope. Search for duplicated rules, obsolete concepts, adjacent + implementations, and conflicting sources of truth as needed. Independent old + defects that the change does not trigger remain separate work. +9. **Robustness and error handling.** Does error handling follow the repository's + fail-fast requirements and the recovery behavior allowed by the product? Are + errors swallowed, required inputs hidden by defaults, or mandatory steps + bypassed? Can failures be traced to their cause? For external writes, files, and + resources, examine partial success, timeouts after an operation has taken + effect, retries, interruption, rollback, and cleanup together. Error handling + must not cause duplicate operations, lose original data or committed results, + or delete resources needed for recovery. +10. **Validation coverage.** Do validation commands match the change's risks? Tests + should follow user scenarios and behavior contracts, covering existing correct + behavior, new behavior, accepted and rejected cases, and relevant failures + rather than repeating the implementation. Do tests run in the default + collection? Do mocks hide real interface changes, or results depend on local + machine configuration? Do regression cases run by default? Use real + producer/consumer contracts. Inspect commands and results for the reviewed + revision; when permitted, run focused reproductions and passing controls. + When packaging or distribution is affected, verify the installed package as + well. Type, format, syntax, and other static checks do not establish runtime + correctness. Choose verification appropriate to the affected behavior; do not + add redundant tests or demand unrelated end-to-end runs for documentation-only + changes. +11. **Historical regressions.** When migrating, rewriting, or restoring old code, + defaults, delays, fallbacks, special cases, or test semantics, ask: "Did this + behavior exist before? Was it removed because it caused a problem? Does that + reason still apply?" Consult Git history when needed. For a suspected revival, + check the current reachable paths, the reason for the original fix, and the + validation evidence. Report a confirmed return of broken behavior; do not + present suspicion as an established defect. +12. **Upstream capabilities.** For framework or provider behavior, have the locked + version and current official documentation, APIs, and release notes been + checked, with upstream source consulted where needed? Does the change use + official lifecycle hooks and extension points where suitable? If a custom + adapter works around an upstream limitation, is the gap reproducible, is the + workaround confined to the protocol boundary, and does it have behavior tests? +13. **Human approval boundaries.** Do tool permissions, user authorization, and the + actual operations agree? High-risk operations must respect required human + approval; unrelated approval steps should not repeatedly interrupt reversible, + low-risk actions. + +`review` assesses the implementation and change risks. `verify` determines whether +the agreed success criteria have been met. A review with no findings does not +replace necessary acceptance checks. + +## Priority levels + +First establish that the finding is valid and belongs to this PR. Then classify +its actual impact and urgency: + +| Level | Criteria | +| --- | --- | +| P0: urgent, critical | Widespread loss of core service, major irrecoverable data loss, or a severe breach of security boundaries requiring immediate action. A security or data concern is not automatically P0. | +| P1: high priority | Broken primary functionality, a critical user journey, or a compatibility contract; or substantial security, data, or resource risk. The impact falls short of P0 but warrants priority repair. | +| P2: normal priority | Lower or localized impact, with evidence of a functional, boundary, maintainability, validation, or applicable mandatory-rule defect. Personal preference is still not a defect. | + +Label each finding P0, P1, or P2 and explain the classification. Preserve the tool's +field protocol: if it only provides `severity`, use `critical` for P0, `high` for +P1, and `medium` or `low` for P2 according to impact, with the P level in the +comment text. Severity and blocking status are separate judgments. All three +levels are blocking by default under this shared policy; exceptions require an +explicit agreement. + +## Output and feedback handling + +Follow the review tool's result structure and the priority definitions above. +Report all valid findings within scope, sorted by severity, without a fixed count +limit. Combine findings with the same root cause. Place inline comments at changed +locations allowed by the tool; old code may still supply root-cause evidence. Each +finding should state its relationship to this PR, evidence or applicable rule, +impact, and the behavior or constraint to restore. Give the smallest correction +when it is known. + +Valid in-scope findings, including P2 and findings from either official or local +rules, block merging by default. Mark a finding non-blocking only when the user +or repository maintainer has explicitly agreed to that exception, and cite the +agreement. + +Apply the same judgment to feedback on the PR. Fix valid findings owned by this +PR, check the current behavior for already-fixed findings, explain why rejected +findings do not hold, and leave unrelated old defects to their own tasks. Read +replies as well as thread roots. A valid finding does not make its suggested fix +correct: do not delete correct test expectations or change agreed requirements +merely to eliminate a comment. + +Keep summaries and execution records out of inline findings. The rules do not +themselves authorize a model to publish comments. With no findings, return the +empty result required by the tool protocol. When a summary is requested, lead with +"pass", "conditional pass", or "fail" in the required review language, then state +the covered paths, evidence-backed residual risks, and unverified items. Do not +invent risks or repeat the checklist. Use full URLs or `owner/repo#number` for +cross-repository references; verify the repository, title, relevant revision, and +merge state. Distinguish a tested pair of revisions, an unmerged dependency, and +a defect in the current candidate. + +## Re-review and completion + +The first pass covers the assigned net diff and reports confirmed findings +promptly, without saving some for later rounds. Use independent or parallel +reviewers for distinct risks when the host supports them, authorization permits +it, and they improve coverage. Re-review may focus on unresolved +findings, fixes, and their effects, while retaining the same task goal and full +PR scope. Follow any explicit requirement for a fresh review of the whole current +candidate. Previous approvals or findings do not substitute for checking the +current changes. + +Missed findings may be added with newly confirmed evidence and a clear +relationship to this PR. That evidence may come from code unchanged since the +previous review; a new commit is not required. Reopening a handled finding needs +evidence that the defect remains or that its fix caused a regression. + +Touching more files during a fix does not require cleaning up every old problem +in those files. The work can close when valid in-scope findings are resolved and +necessary verification passes. Add task requirements only when the user or +repository maintainer explicitly changes the goal. + + +--- + +# Browser Eval review supplement + +Follow the repository review constraints in `AGENTS.md` and `CONTRIBUTING.md`. The following requirements belong to Browser Eval and supplement the shared criteria in `docs/references/review-guidelines.md` and OCR's built-in rules. + +## Repository checks + +Keep provider execution and reporting in the harness; use benchmark-owned definitions and scoring. Trace scored answers to native evidence. Verify populations, timing and certification against the selected track contract. Preserve frozen evidence and report targets, keep private run data outside Git, and check report views agree with their evidence. diff --git a/.opencodereview/review-rules.md b/.opencodereview/review-rules.md index a87ea6377..df6ee9f59 100644 --- a/.opencodereview/review-rules.md +++ b/.opencodereview/review-rules.md @@ -1,6 +1,6 @@ # Browser Eval review supplement -Read `docs/references/review-guidelines.md` for shared review criteria. The following requirements belong to Browser Eval and supplement the pinned common standard and OCR's built-in rules. +Follow the repository review constraints in `AGENTS.md` and `CONTRIBUTING.md`. The following requirements belong to Browser Eval and supplement the shared criteria in `docs/references/review-guidelines.md` and OCR's built-in rules. ## Repository checks diff --git a/.opencodereview/rule.json b/.opencodereview/rule.json index 89b2460ea..c62aa1ca4 100644 --- a/.opencodereview/rule.json +++ b/.opencodereview/rule.json @@ -2,7 +2,7 @@ "rules": [ { "path": "**", - "rule": "docs/references/review-guidelines.md", + "rule": ".opencodereview/review-rules.generated.md", "merge_system_rule": true } ] diff --git a/AGENTS.md b/AGENTS.md index 0f385c0ba..dd53b9003 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,6 +4,9 @@ Use [Shared Review Guidelines](docs/references/review-guidelines.md) and the [repository supplement](.opencodereview/review-rules.md). The shared guide is generated from the commit recorded in `review-guidelines.lock.json`; change common requirements in `lexmount/ai-template-py` and synchronize the copy. +OCR reads `.opencodereview/review-rules.generated.md`, which contains both documents +in full. The source lock covers shared policy text; repository maintenance logic +lives in `harness/review_guidelines.py` behind the thin script entry point. # Benchmark ownership diff --git a/Makefile b/Makefile index bc99107c6..c49310c50 100644 --- a/Makefile +++ b/Makefile @@ -58,8 +58,11 @@ fixture-smoke: runtime-check test: test-python test-ui test-native-adapters -.PHONY: ci-tests -ci-tests: naming-check lint-check test fixture-smoke +.PHONY: review-check ci-tests +review-check: runtime-check + $(PY) scripts/review_guidelines.py check + +ci-tests: review-check naming-check lint-check test fixture-smoke ci: ci-tests package-check diff --git a/harness/review_guidelines.py b/harness/review_guidelines.py new file mode 100644 index 000000000..b0b6e1793 --- /dev/null +++ b/harness/review_guidelines.py @@ -0,0 +1,213 @@ +"""Publish pinned shared guidance through a complete repository review entry.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +import sys +from tempfile import TemporaryDirectory +from urllib.parse import urlsplit + +REPOSITORY = "lexmount/ai-template-py" +GUIDE = "docs/references/review-guidelines.md" +SUPPLEMENT = ".opencodereview/review-rules.md" +ENTRY = ".opencodereview/review-rules.generated.md" +LOCK = "review-guidelines.lock.json" + + +def git(root: Path, *args: str) -> bytes: + return subprocess.run( + ["git", "-C", str(root), *args], check=True, capture_output=True, + ).stdout + + +def repository_root(path: Path) -> Path: + return Path(git(path, "rev-parse", "--show-toplevel").decode().strip()).resolve() + + +def has_source_remote(root: Path) -> bool: + for name in git(root, "remote").decode().splitlines(): + url = git(root, "remote", "get-url", name).decode().strip().rstrip("/").lower() + if url.startswith("git@github.com:"): + repository = url.removeprefix("git@github.com:") + else: + parsed = urlsplit(url) + if parsed.scheme not in {"https", "ssh"} or parsed.hostname != "github.com": + continue + repository = parsed.path.lstrip("/") + if repository.removesuffix(".git") == REPOSITORY: + return True + return False + + +def managed_path(root: Path, relative: str) -> Path: + name = Path(relative) + if name.is_absolute() or ".." in name.parts: + raise ValueError("Review files must remain inside the repository") + path = root / name + if path.exists() and not path.is_file(): + raise ValueError(f"Managed destination must be a file: {relative}") + for candidate in (path, *path.parents): + if candidate == root: + break + if candidate.is_symlink(): + raise ValueError(f"Managed paths must not be symlinks: {relative}") + if candidate != path and candidate.exists() and not candidate.is_dir(): + raise ValueError(f"Managed parent must be a directory: {relative}") + return path + + +def digest(content: bytes) -> str: + return hashlib.sha256(content).hexdigest() + + +def source_guide(source: Path, revision: str) -> bytes: + if not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError("Use a full 40-character source commit, not a moving ref") + if not has_source_remote(source): + raise ValueError(f"Configure a source checkout remote for {REPOSITORY}") + if git(source, "cat-file", "-t", revision).strip() != b"commit": + raise ValueError("The source revision must identify a commit") + content = git(source, "show", f"{revision}:{GUIDE}") + if not content.strip(): + raise ValueError("The shared guide must not be empty") + return content + + +def compose(guide: bytes, supplement: bytes) -> bytes: + if not supplement.strip(): + raise ValueError("The repository review supplement must not be empty") + header = f"\n\n" + return header.encode() + guide + b"\n\n---\n\n" + supplement + + +def check_routing(root: Path, guide: bytes, supplement: bytes, entry: bytes) -> None: + config = json.loads(managed_path(root, ".opencodereview/rule.json").read_text()) + rules = config.get("rules") if isinstance(config, dict) else None + if not isinstance(rules, list): + raise ValueError("OCR rules must be a list") + for rule in rules: + if (isinstance(rule, dict) and rule.get("rule", "") == "" + and rule.get("merge_system_rule", False) is False): + continue + if not isinstance(rule, dict) or not isinstance(rule.get("path"), str): + raise ValueError("Each OCR rule must declare a path") + if rule.get("merge_system_rule") is not True: + raise ValueError("Every reachable OCR route must retain built-in rules") + rule_path = rule.get("rule") + if not isinstance(rule_path, str): + raise ValueError("Each OCR rule must name its complete review entry") + is_file = ( + "\n" not in rule_path and " " not in rule_path + and Path(rule_path).suffix.lower() in {".md", ".txt", ".markdown"} + ) + if is_file: + body = entry if rule_path == ENTRY else managed_path(root, rule_path).read_bytes() + else: + body = rule_path.encode() + if guide not in body or supplement not in body: + raise ValueError("Every reachable OCR route must include shared and local guidance") + # OCR uses the first matching rule; a catch-all makes later entries unreachable. + if rule["path"] == "**": + return + raise ValueError("OCR needs a catch-all route for the complete review entry") + + +def pinned_guide(root: Path, source: Path | None = None) -> bytes: + lock = json.loads(managed_path(root, LOCK).read_text()) + if not isinstance(lock, dict) or lock.get("version") != 2 or lock.get("repository") != REPOSITORY: + raise ValueError("Unsupported review source lock") + revision = lock.get("revision") + if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError("The source lock must pin a full commit") + if not isinstance(lock.get("files"), dict) or set(lock["files"]) != {GUIDE}: + raise ValueError("The source lock must cover exactly the shared guide") + guide = managed_path(root, GUIDE).read_bytes() + if not guide.strip() or digest(guide) != lock["files"][GUIDE]: + raise ValueError("Local drift in the shared guide; synchronize from the source") + if source is not None and guide != source_guide(source, revision): + raise ValueError(f"Source mismatch at {revision}: {GUIDE}") + return guide + + +def check(root: Path, source: Path | None = None) -> None: + guide = pinned_guide(root, source) + supplement = managed_path(root, SUPPLEMENT).read_bytes() + entry = compose(guide, supplement) + if managed_path(root, ENTRY).read_bytes() != entry: + raise ValueError("Review entry is stale; run scripts/review_guidelines.py render") + check_routing(root, guide, supplement, entry) + print(f"Review guidance verified: {root}") + + +def install(root: Path, payloads: dict[str, bytes]) -> None: + with TemporaryDirectory(prefix=".review-guidelines-", dir=root) as directory: + staged = Path(directory) + for path, content in payloads.items(): + (staged / Path(path).name).write_bytes(content) + # Each replacement is atomic; the source lock is published last. + for path in payloads: + destination = managed_path(root, path) + destination.parent.mkdir(parents=True, exist_ok=True) + (staged / Path(path).name).replace(destination) + + +def render(root: Path) -> None: + guide = pinned_guide(root) + supplement = managed_path(root, SUPPLEMENT).read_bytes() + entry = compose(guide, supplement) + check_routing(root, guide, supplement, entry) + install(root, {ENTRY: entry}) + check(root) + + +def sync(source: Path, revision: str, targets: list[Path]) -> None: + guide = source_guide(source, revision) + lock = { + "version": 2, "repository": REPOSITORY, "revision": revision, + "files": {GUIDE: digest(guide)}, + } + prepared = [] + for root in targets: + if root == source: + raise ValueError("Edit the canonical source directly; do not sync over it") + supplement = managed_path(root, SUPPLEMENT).read_bytes() + entry = compose(guide, supplement) + payloads = {GUIDE: guide, ENTRY: entry, LOCK: (json.dumps(lock, indent=2) + "\n").encode()} + for path in payloads: + managed_path(root, path) + check_routing(root, guide, supplement, entry) + prepared.append((root, payloads)) + for root, payloads in prepared: + install(root, payloads) + check(root, source) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + verify = commands.add_parser("check", help="Check the pinned guide and complete OCR entry") + verify.add_argument("--source", type=Path, help="Also compare the pinned source commit") + commands.add_parser("render", help="Regenerate the OCR entry after editing local requirements") + update = commands.add_parser("sync", help="Update guidance in opted-in repository checkouts") + update.add_argument("--source", type=Path, required=True) + update.add_argument("--ref", required=True, help="Full merged source commit") + update.add_argument("targets", nargs="+", type=Path) + args = parser.parse_args() + try: + if args.command == "sync": + sync(repository_root(args.source), args.ref, [repository_root(p) for p in args.targets]) + else: + root = repository_root(Path.cwd()) + if args.command == "render": + render(root) + else: + check(root, repository_root(args.source) if args.source else None) + except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as exc: + print(f"Review guidance error: {exc}", file=sys.stderr) + return 1 + return 0 diff --git a/review-guidelines.lock.json b/review-guidelines.lock.json index 740ee2263..c16c4bfe4 100644 --- a/review-guidelines.lock.json +++ b/review-guidelines.lock.json @@ -1,9 +1,8 @@ { - "version": 1, + "version": 2, "repository": "lexmount/ai-template-py", - "revision": "6188715448dfc3f54e721715fd5147daac5b400e", + "revision": "df1228126c32ccf2c7cdff15b2bc46fa3af519fe", "files": { - "docs/references/review-guidelines.md": "8eb5da2e3a6a7ea9766bb4131b1d1cc9e6191a49fde8f745bd6148196ced51e1", - "scripts/review_guidelines.py": "c38b6d5d229d875393ed7514d00e11365b98c0c58c4279115c49bd18ace0eaf7" + "docs/references/review-guidelines.md": "8eb5da2e3a6a7ea9766bb4131b1d1cc9e6191a49fde8f745bd6148196ced51e1" } } diff --git a/scripts/review_guidelines.py b/scripts/review_guidelines.py index d9a27a47f..e544fbaac 100644 --- a/scripts/review_guidelines.py +++ b/scripts/review_guidelines.py @@ -1,149 +1,10 @@ -"""Synchronize pinned review guidance and verify its local integrity.""" +"""Synchronize shared guidance and generate the repository's complete OCR entry.""" -from __future__ import annotations - -import argparse -import hashlib -import json -from pathlib import Path -import re -import subprocess import sys -from tempfile import TemporaryDirectory - - -REPOSITORY = "lexmount/ai-template-py" -FILES = ("docs/references/review-guidelines.md", "scripts/review_guidelines.py") -LOCK = "review-guidelines.lock.json" - - -def git(root: Path, *args: str) -> bytes: - return subprocess.run( - ["git", "-C", str(root), *args], check=True, capture_output=True - ).stdout - - -def is_source(root: Path) -> bool: - remote = git(root, "remote", "get-url", "origin").decode().strip() - return remote.removesuffix(".git") in ( - f"git@github.com:{REPOSITORY}", - f"https://github.com/{REPOSITORY}", - ) - - -def managed_path(root: Path, relative: str) -> Path: - path = root / relative - if path.exists() and not path.is_file(): - raise ValueError(f"Managed destination must be a file: {path}") - for candidate in (path, *path.parents): - if candidate == root: - break - if candidate.is_symlink(): - raise ValueError(f"Managed paths must not be symlinks: {candidate}") - if candidate != path and candidate.exists() and not candidate.is_dir(): - raise ValueError(f"Managed parent must be a directory: {candidate}") - return path - - -def digest(content: bytes) -> str: - return hashlib.sha256(content).hexdigest() - - -def source_files(source: Path, revision: str) -> dict[str, bytes]: - if not re.fullmatch(r"[0-9a-f]{40}", revision): - raise ValueError("Use a full 40-character source commit, not a moving ref") - if not is_source(source): - raise ValueError(f"Source origin must be {REPOSITORY}") - if git(source, "cat-file", "-t", revision).strip() != b"commit": - raise ValueError("The source revision must identify a commit") - return {path: git(source, "show", f"{revision}:{path}") for path in FILES} - - -def check_routing(root: Path) -> None: - config_path = root / ".opencodereview/rule.json" - if not config_path.exists(): - raise ValueError("Missing .opencodereview/rule.json") - rules = json.loads(config_path.read_text())["rules"] - if rules != [{"path": "**", "rule": FILES[0], "merge_system_rule": True}]: - raise ValueError("OCR must load the shared guide and retain built-in rules") - - -def check(root: Path, source: Path | None = None) -> None: - lock_path = managed_path(root, LOCK) - if not lock_path.exists(): - if not is_source(root): - raise ValueError(f"Missing {LOCK}; synchronize from {REPOSITORY}") - for path in FILES: - if not managed_path(root, path).read_bytes().strip(): - raise ValueError(f"Empty source file: {path}") - else: - lock = json.loads(lock_path.read_text()) - if lock.get("repository") != REPOSITORY or lock.get("version") != 1: - raise ValueError("Unsupported review source lock") - revision = lock["revision"] - if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision): - raise ValueError("The source lock must pin a full commit") - if set(lock["files"]) != set(FILES): - raise ValueError("The lock must cover the guide and synchronization tool") - upstream = source_files(source, revision) if source is not None else None - for path in FILES: - local = managed_path(root, path).read_bytes() - if digest(local) != lock["files"][path]: - raise ValueError(f"Local drift: {path}; synchronize, do not edit the copy") - if upstream is not None and local != upstream[path]: - raise ValueError(f"Source mismatch at {revision}: {path}") - check_routing(root) - print(f"Review guidance verified: {root}") - - -def sync(source: Path, revision: str, targets: list[Path]) -> None: - contents = source_files(source, revision) - lock = { - "version": 1, - "repository": REPOSITORY, - "revision": revision, - "files": {path: digest(data) for path, data in contents.items()}, - } - payloads = {**contents, LOCK: (json.dumps(lock, indent=2) + "\n").encode()} - # Validate every destination before changing any of them. - for root in targets: - if is_source(root): - raise ValueError("Edit the canonical source directly; do not sync over it") - for path in payloads: - managed_path(root, path) - check_routing(root) - for root in targets: - with TemporaryDirectory(prefix=".review-guidelines-", dir=root) as directory: - staged = Path(directory) - for path, data in payloads.items(): - (staged / Path(path).name).write_bytes(data) - # Replace complete files on the same filesystem, publishing the lock last. - for path in payloads: - destination = managed_path(root, path) - destination.parent.mkdir(parents=True, exist_ok=True) - (staged / Path(path).name).replace(destination) - check(root, source) - +from pathlib import Path -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - commands = parser.add_subparsers(dest="command", required=True) - verify = commands.add_parser("check", help="Check the pinned local files offline") - verify.add_argument("--source", type=Path, help="Also compare the pinned Git source") - update = commands.add_parser("sync", help="Update one or more repository checkouts") - update.add_argument("--source", type=Path, required=True) - update.add_argument("--ref", required=True, help="Full source commit") - update.add_argument("targets", nargs="+", type=Path) - args = parser.parse_args() - try: - if args.command == "check": - check(Path.cwd().resolve(), args.source.resolve() if args.source else None) - else: - sync(args.source.resolve(), args.ref, [p.resolve() for p in args.targets]) - except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as exc: - print(f"Review guidance error: {exc}", file=sys.stderr) - return 1 - return 0 +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from harness.review_guidelines import main if __name__ == "__main__": diff --git a/tests/test_review_guidelines.py b/tests/test_review_guidelines.py new file mode 100644 index 000000000..038e3fa5d --- /dev/null +++ b/tests/test_review_guidelines.py @@ -0,0 +1,306 @@ +"""Contracts for complete OCR inputs, pinned updates and local verification.""" + +import errno +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +from harness import review_guidelines as review + +ROOT = Path(__file__).resolve().parents[1] +SCRIPT = ROOT / "scripts/review_guidelines.py" + + +def git(root, *args): + return subprocess.check_output(["git", "-C", str(root), *args]).decode().strip() + + +def repository(root, source=False): + root.mkdir() + git(root, "init", "-qb", "main") + git(root, "config", "user.name", "Test") + git(root, "config", "user.email", "test@example.invalid") + if source: + git(root, "remote", "add", "origin", "https://github.com/lexmount/ai-template-py.git") + return root + + +def consumer(root): + repository(root) + (root / ".opencodereview").mkdir() + (root / review.SUPPLEMENT).write_text("# Local checks\nKeep native scoring evidence.\n") + (root / ".opencodereview/rule.json").write_text(json.dumps({"rules": [{ + "path": "**", "rule": review.ENTRY, "merge_system_rule": True, + }]})) + return root + + +def command(root, *args): + return subprocess.run( + [sys.executable, str(SCRIPT), *map(str, args)], cwd=root, + capture_output=True, text=True, + ) + + +@pytest.fixture +def repos(tmp_path): + source = repository(tmp_path / "source", source=True) + (source / "docs/references").mkdir(parents=True) + (source / review.GUIDE).write_text("# Shared criteria\nPreserve existing supported behavior.\n") + git(source, "add", ".") + git(source, "commit", "-qm", "initial shared requirements") + revision = git(source, "rev-parse", "HEAD") + target = consumer(tmp_path / "target") + review.sync(source, revision, [target]) + return source, target, revision + + +def test_repository_entry_contains_complete_shared_and_local_requirements(): + review.check(ROOT) + shared = (ROOT / review.GUIDE).read_bytes() + local = (ROOT / review.SUPPLEMENT).read_bytes() + entry = (ROOT / review.ENTRY).read_bytes() + assert entry.count(shared) == 1 + assert entry.count(local) == 1 + + +def test_sync_uses_committed_policy_and_preserves_local_code_and_requirements(repos): + source, target, revision = repos + expected = (target / review.GUIDE).read_bytes() + (source / review.GUIDE).write_text("uncommitted requirement") + (source / "scripts").mkdir() + (source / "scripts/review_guidelines.py").write_text("upstream tool") + (target / "scripts").mkdir() + tool = target / "scripts/review_guidelines.py" + tool.write_text("repository-owned tool") + local = (target / review.SUPPLEMENT).read_bytes() + review.sync(source, revision, [target]) + assert (target / review.GUIDE).read_bytes() == expected + assert (target / review.SUPPLEMENT).read_bytes() == local + assert tool.read_text() == "repository-owned tool" + review.check(target, source) + + +@pytest.mark.parametrize("path", [review.GUIDE, review.SUPPLEMENT, review.ENTRY]) +def test_check_rejects_changed_inputs_without_rewriting_them(repos, path): + _, target, _ = repos + changed = (target / path).read_bytes() + b"\nNew requirement.\n" + (target / path).write_bytes(changed) + result = command(target, "check") + assert result.returncode != 0 + assert (target / path).read_bytes() == changed + + +def test_render_updates_local_requirements_without_rewriting_source_lock(repos): + _, target, _ = repos + lock = (target / review.LOCK).read_bytes() + shared = (target / review.GUIDE).read_bytes() + local = b"# Revised local criteria\nReview evidence and ownership together.\n" + (target / review.SUPPLEMENT).write_bytes(local) + assert command(target, "render").returncode == 0 + assert local in (target / review.ENTRY).read_bytes() + assert (target / review.GUIDE).read_bytes() == shared + assert (target / review.LOCK).read_bytes() == lock + assert command(target, "check").returncode == 0 + + +def test_render_cannot_hide_drift_in_the_pinned_shared_guide(repos): + _, target, _ = repos + before = (target / review.ENTRY).read_bytes() + (target / review.GUIDE).write_text("edited local copy") + assert command(target, "render").returncode != 0 + assert (target / review.ENTRY).read_bytes() == before + + +@pytest.mark.parametrize("change", ["repository", "revision", "files", "version", "checksum", "shape"]) +def test_invalid_source_lock_is_rejected(repos, change): + _, target, _ = repos + lock = json.loads((target / review.LOCK).read_text()) + if change == "repository": + lock["repository"] = "another/repository" + elif change == "revision": + lock["revision"] = "main" + elif change == "files": + lock["files"] = {} + elif change == "version": + lock["version"] = 1 + elif change == "checksum": + lock["files"][review.GUIDE] = "0" * 64 + else: + lock = [] + (target / review.LOCK).write_text(json.dumps(lock)) + assert command(target, "check").returncode != 0 + + +def test_missing_lock_is_rejected(repos): + _, target, _ = repos + (target / review.LOCK).unlink() + assert command(target, "check").returncode != 0 + + +def test_check_resolves_the_repository_from_a_nested_directory(repos): + source, target, _ = repos + nested = target / "scripts/nested" + nested.mkdir(parents=True) + result = command(nested, "check", "--source", source) + assert result.returncode == 0, result.stderr + assert str(target) in result.stdout + + +@pytest.mark.parametrize("url", [ + "git@github.com:lexmount/ai-template-py.git", + "ssh://git@github.com/lexmount/ai-template-py.git", + "https://github.com/LEXMOUNT/AI-TEMPLATE-PY.git/", +]) +def test_source_checkout_accepts_standard_remote_urls_and_other_remote_names(repos, url): + source, target, _ = repos + git(source, "remote", "rename", "origin", "upstream") + git(source, "remote", "set-url", "upstream", url) + result = command(target, "check", "--source", source) + assert result.returncode == 0, result.stderr + + +def test_missing_source_remote_has_a_clear_error(repos): + source, target, _ = repos + git(source, "remote", "remove", "origin") + result = command(target, "check", "--source", source) + assert result.returncode != 0 + assert "Configure a source checkout remote" in result.stderr + assert "Traceback" not in result.stderr + + +def test_source_comparison_rejects_a_relabelled_revision(repos): + source, target, _ = repos + (source / review.GUIDE).write_text("# Changed requirements\n") + git(source, "add", review.GUIDE) + git(source, "commit", "-qm", "change requirements") + lock = json.loads((target / review.LOCK).read_text()) + lock["revision"] = git(source, "rev-parse", "HEAD") + (target / review.LOCK).write_text(json.dumps(lock)) + assert command(target, "check").returncode == 0 + result = command(target, "check", "--source", source) + assert result.returncode != 0 + assert "Source mismatch" in result.stderr + + +@pytest.mark.parametrize("revision", ["main", "a" * 40]) +def test_unavailable_or_moving_source_revision_leaves_the_target_unchanged(repos, revision): + source, target, _ = repos + before = {path: (target / path).read_bytes() for path in [review.GUIDE, review.ENTRY, review.LOCK]} + assert command(target, "sync", "--source", source, "--ref", revision, target).returncode != 0 + assert {path: (target / path).read_bytes() for path in before} == before + + +def test_git_tree_is_not_accepted_as_a_source_commit(repos): + source, target, _ = repos + result = command(target, "sync", "--source", source, "--ref", git(source, "write-tree"), target) + assert result.returncode != 0 + assert "must identify a commit" in result.stderr + + +@pytest.mark.parametrize("mode", ["disabled_builtin", "missing_fallback", "shadowed"]) +def test_incomplete_effective_ocr_routes_are_rejected(repos, mode): + _, target, _ = repos + fallback = {"path": "**", "rule": review.ENTRY, "merge_system_rule": True} + rules = [dict(fallback)] + if mode == "disabled_builtin": + rules[0]["merge_system_rule"] = False + elif mode == "missing_fallback": + rules[0]["path"] = "**/*.py" + else: + rules.insert(0, {"path": "**/*.py", "rule": review.SUPPLEMENT, "merge_system_rule": True}) + (target / ".opencodereview/rule.json").write_text(json.dumps({"rules": rules})) + assert command(target, "check").returncode != 0 + + +def test_additional_rules_follow_ocr_first_match_behavior(repos): + source, target, revision = repos + rules = [ + {"path": "**", "rule": "", "merge_system_rule": False}, + {"path": "**/*.py", "rule": review.ENTRY, "merge_system_rule": True}, + {"path": "**", "rule": review.ENTRY, "merge_system_rule": True}, + {"path": "**", "rule": review.SUPPLEMENT, "merge_system_rule": True}, + ] + (target / ".opencodereview/rule.json").write_text(json.dumps({"rules": rules})) + review.sync(source, revision, [target]) + assert command(target, "check").returncode == 0 + + +def test_inline_rules_preserve_complete_guidance(repos): + _, target, _ = repos + body = (target / review.ENTRY).read_text() + config = {"rules": [{"path": "**", "rule": body, "merge_system_rule": True}]} + (target / ".opencodereview/rule.json").write_text(json.dumps(config)) + assert command(target, "check").returncode == 0 + + +def test_invalid_later_target_is_rejected_before_any_changes(repos, tmp_path): + source, target, revision = repos + other = consumer(tmp_path / "other") + (other / "docs").write_text("not a directory") + before = (target / review.LOCK).read_bytes() + with pytest.raises(ValueError, match="must be a directory"): + review.sync(source, revision, [target, other]) + assert (target / review.LOCK).read_bytes() == before + assert not (other / review.LOCK).exists() + + +def test_symlinked_managed_paths_cannot_overwrite_external_files(repos, tmp_path): + source, target, revision = repos + external = tmp_path / "external.md" + external.write_text("external content") + (target / review.GUIDE).unlink() + (target / review.GUIDE).symlink_to(external) + with pytest.raises(ValueError, match="symlinks"): + review.sync(source, revision, [target]) + assert external.read_text() == "external content" + + +def test_failed_staging_preserves_the_existing_files(repos, monkeypatch): + source, target, revision = repos + paths = [review.GUIDE, review.ENTRY, review.LOCK] + before = {path: (target / path).read_bytes() for path in paths} + write = Path.write_bytes + + def fail(path, data): + if path.name == Path(review.ENTRY).name: + write(path, data[:5]) + raise OSError(errno.ENOSPC, "No space left") + return write(path, data) + + with monkeypatch.context() as patch: + patch.setattr(Path, "write_bytes", fail) + with pytest.raises(OSError, match="No space left"): + review.sync(source, revision, [target]) + assert {path: (target / path).read_bytes() for path in paths} == before + review.check(target, source) + + +def test_partial_batch_failure_is_detected_and_retry_repairs_it(repos, tmp_path, monkeypatch): + source, target, revision = repos + other = consumer(tmp_path / "other") + review.sync(source, revision, [other]) + (source / review.GUIDE).write_text("# Updated policy\nA newly agreed criterion.\n") + git(source, "add", review.GUIDE) + git(source, "commit", "-qm", "update shared policy") + updated = git(source, "rev-parse", "HEAD") + replace = Path.replace + + def fail(path, destination): + if destination == other / review.ENTRY: + raise OSError("simulated replacement failure") + return replace(path, destination) + + with monkeypatch.context() as patch: + patch.setattr(Path, "replace", fail) + with pytest.raises(OSError, match="simulated replacement failure"): + review.sync(source, updated, [target, other]) + review.check(target, source) + assert (other / review.GUIDE).read_bytes() == (target / review.GUIDE).read_bytes() + with pytest.raises(ValueError, match="Local drift"): + review.check(other) + review.sync(source, updated, [target, other]) + review.check(other, source) From 403736dc37e8f53e35fa700ea456b4d7ad537bb5 Mon Sep 17 00:00:00 2001 From: lanyue-llk <270302213+lanyue-llk@users.noreply.github.com> Date: Thu, 29 Oct 2026 17:30:03 +0700 Subject: [PATCH 2/2] fix(review): keep the local supplement in the synchronized guide Replace the forked review tool, generated OCR entry and v2 lock with the shared tool from lexmount/ai-template-py, which now preserves a repository supplement after a marker at the end of the synchronized guide. OCR loads one file per rule, so the guide it already reads now carries both the shared criteria and Browser Eval's requirements, with no generated copy. The lock pins the unmerged source branch commit; re-pin to the merged commit once the ai-template-py change lands. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/README.md | 22 +- .opencodereview/review-rules.generated.md | 246 ----------------- .opencodereview/review-rules.md | 7 - .opencodereview/rule.json | 2 +- AGENTS.md | 12 +- docs/references/review-guidelines.md | 18 +- harness/review_guidelines.py | 213 --------------- review-guidelines.lock.json | 7 +- scripts/review_guidelines.py | 180 ++++++++++++- tests/test_review_guidelines.py | 306 ---------------------- 10 files changed, 202 insertions(+), 811 deletions(-) delete mode 100644 .opencodereview/review-rules.generated.md delete mode 100644 .opencodereview/review-rules.md delete mode 100644 harness/review_guidelines.py delete mode 100644 tests/test_review_guidelines.py diff --git a/.github/workflows/README.md b/.github/workflows/README.md index b18a6835b..7821d66f9 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -12,27 +12,7 @@ Three jobs run independently: The Python suite uses two workers with `--dist loadfile`, keeping each test file in one process. Slow-test durations appear in the job log. Local `make ci` remains serial by default; use `make ci PYTEST_ARGS='-n 2 --dist loadfile --durations=20'` for the same test scheduling. -`make review-check` runs inside both `make ci-tests` and local `make ci`. The version 2 `review-guidelines.lock.json` pins only the shared policy text in `docs/references/review-guidelines.md`, using a full merged commit from `lexmount/ai-template-py` and a SHA-256 checksum. Maintenance logic in `harness/review_guidelines.py` is ordinary repository code, covered by the default Python test suite; `scripts/review_guidelines.py` is its command entry point. - -OCR reads `.opencodereview/review-rules.generated.md`, containing the complete shared guide and Browser Eval's supplement from `.opencodereview/review-rules.md`, alongside its built-in rules. The supplement explicitly points to `AGENTS.md` and `CONTRIBUTING.md`. OCR selects the first matching rule, so adding another rule does not combine their contents. Verification checks each reachable route and rejects a route that drops shared guidance, local requirements or built-in rules. - -After editing the local supplement, regenerate the review entry and check it: - -```sh -uv run --frozen python scripts/review_guidelines.py render -make review-check -``` - -To update shared policy, use a trusted template checkout containing the selected merged commit: - -```sh -uv run --frozen python scripts/review_guidelines.py sync --source --ref . -uv run --frozen python scripts/review_guidelines.py check --source -``` - -Synchronization updates the shared guide, generated entry and source lock; it preserves local requirements and executable code. Targets must already configure the generated review entry. Standard HTTPS and SSH remote spellings are accepted under any remote name. The configured URL identifies the intended source; use a trusted checkout because offline checks do not authenticate GitHub. The ordinary check verifies local checksums and composition without network access; `--source` additionally compares bytes with the recorded Git commit. - -Batch updates validate all destinations first, then process repositories sequentially. Complete files are staged on the destination filesystem and replaced atomically, with the lock last. A replacement failure can leave mixed versions in the current repository, which verification rejects; retrying the same source revision repairs it. Earlier completed repositories retain their updates. Synchronization does not commit or push changes. +`make review-check`, part of both `make ci-tests` and local `make ci`, verifies the pinned shared review guide and synchronization tool against `review-guidelines.lock.json`, and confirms that OCR loads the guide alongside its built-in rules. This offline integrity check needs no cross-repository credentials. Use `uv run --frozen python scripts/review_guidelines.py check --source ` to also compare the files with their recorded source commit. Shared requirements are maintained in `lexmount/ai-template-py`; Browser Eval's review supplement is the section after the repository supplement marker at the end of `docs/references/review-guidelines.md`; the lock covers only the text before it, and synchronization preserves it. The existing `Python 3.11` status succeeds only when all three jobs succeed. A failed, cancelled or skipped job fails that status. New commits cancel obsolete CI runs for the same pull request. Main and tag runs each have a unique concurrency group, so a newer run cannot replace an earlier pending run. diff --git a/.opencodereview/review-rules.generated.md b/.opencodereview/review-rules.generated.md deleted file mode 100644 index 086659bb1..000000000 --- a/.opencodereview/review-rules.generated.md +++ /dev/null @@ -1,246 +0,0 @@ - - -# Review Guidelines - -The canonical version of this document lives in `lexmount/ai-template-py` at -`docs/references/review-guidelines.md`. Consumer repositories synchronize their -copies with `scripts/review_guidelines.py` and pin the source revision in -`review-guidelines.lock.json`. Change the canonical document rather than editing -a synchronized copy. - -OCR's official rules remain the foundation. This document adds shared review, -scope, and feedback requirements. Read the repository's local review supplement -for its domain requirements. Use the review language required by the user or -repository; preserve code identifiers, commands, schema values, and product names. - -## Establish the review basis - -Read the task goal, PR description, linked issues and plans, user agreements, -acceptance criteria, and available validation results. Read all top-level -conversation comments, formal review bodies, inline threads, and replies. Earlier -reviews provide evidence and the status of earlier findings; they do not replace -an independent assessment of the current candidate. - -Confirm the target branch and current head. Read the complete net diff from their -actual merge base to head, together with all unmerged commits. A `synchronize` -event or triggering commit starts a review; it does not redefine the PR as only -that increment. Inspect every changed file assigned by the tool, using other -files to establish impact. A complete PR review must cover the full net diff, not -infer scope from the title. Correct a stale checkpoint before reviewing; if the -correct diff is unavailable, report the input problem rather than attributing -existing target-branch changes to this PR. - -Follow the repository entry points to the architecture, interface, code-style, -security, and deployment guidance relevant to the affected components. Read local -supplements and linked component documents where applicable. Concrete product -constraints belong in those sources rather than a shared product checklist. -Consult existing code, callers, history, and upstream sources to establish impact. -Reading more code does not expand this PR's responsibility for fixing it. - -## Decide whether a finding belongs to this PR - -Each finding must meet both conditions: - -1. Identify the specific change that introduces, triggers, or worsens the problem, - or the agreed task requirement that remains unimplemented. A new path can - trigger a defect in old code. Merely finding a defect in the same file or call - chain does not make it part of this PR. -2. Ground the finding in a code path, reproduction, test, or explicit contract. - For behavior defects, explain a reachable trigger and its consequences, - including error paths and untrusted inputs, and account for existing validation - and caller constraints. For a mandatory-rule violation, cite the applicable - rule and the changed location that violates it. Do not present an unproven - runtime failure as its consequence. - -Keep proposed fixes proportionate to the problem and preserve correct behavior. -Do not attach surrounding cleanup, a global redesign, or new product requirements. -A confirmed defect remains reportable when its exact fix is not yet known. - -Mandatory official and repository rules still apply to violations introduced or -worsened by the change. Preferences such as "prefer" or "where practical" allow -contextual choices; a different preference is not itself a defect. Explain the -conflicting rules, responsibilities, resource ownership, or maintenance cost -behind a design finding. File length or a tidier alternative alone does not -justify a rewrite. - -Keep independent historical defects out of this PR's fix list; identify their -separate ownership when follow-up is needed. A material validation gap must name -the affected scenario and the evidence needed. Missing command output alone does -not establish a code defect. Investigate a suspected regression against its -history and current reachable paths before reporting it as confirmed. - -## Required checks - -Apply these questions to the current changes and affected behavior. Use the -evidence and ownership conditions above when reporting findings or requesting fixes. - -1. **Goal and approach.** What real problem does the PR solve, which user scenarios - does it affect, and what behavior should change or remain unchanged? Does the - description match the existing code? Is the approach necessary, and does it - implement the whole goal? -2. **Acceptance criteria.** Are all success criteria covered? Has a review with no - findings been mistaken for verification that the requirements are met? -3. **Repository requirements.** Does the change follow the repository entry points, - project overview, architecture sources, and language and code-style guidance? -4. **Architecture boundaries.** Does the change preserve dependency direction, - module responsibilities, data flow, and ownership? Trace the actual producers - and consumers through callers, state, branches, configuration, caches, - asynchronous work, and errors. Where identities, sessions, tasks, or resources - are involved, do concurrency, cancellation, and cleanup respect their ownership - and permission boundaries? -5. **Simplicity.** Is this the simplest implementation that meets the goal? Does it - add unnecessary state, configuration, abstractions, or dependencies? -6. **Regression and compatibility.** Along affected call paths, do existing correct - features, default configurations, old data, and recovery scenarios still work? - Does the change introduce a bug or break an existing agreement? When replacing - an entry point, removing code, or changing an interface, test the replacement - against the original supported scenarios, not just whether the new entry point - runs. An intentional behavior change needs an explicit requirement and any - necessary migration arrangements. -7. **Reuse and maintainability.** Are the responsibilities, names, and locations of - modules, interfaces, classes, and functions clear? Are files becoming too large - to keep those responsibilities clear? Who owns state and resources, and is the - same rule implemented in several places? Prefer existing shared capabilities; - logic used by several real callers belongs at a suitable shared boundary rather - than in a PR-specific copy. Another instance of an already supported kind should - extend its existing owner through data, configuration, or a registry when that - contract supports it, rather than require scattered instance-specific branches. - Abstractions should express stable responsibilities and simplify callers and - tests. Use classes and composition when state, lifecycle, or a replaceable - protocol needs encapsulation; keep simple stateless logic as functions. Do not - require object-oriented design, inheritance, or a framework for hypothetical - needs. A design finding must identify a concrete maintenance cost or error risk, - the responsibility or constraint to restore, and the smallest fix when known. - Personal style alone is not grounds for rewriting code. -8. **Necessity of each file.** Is every assigned changed file relevant and necessary - to the goal? Flag scope creep and unrelated changes to another owner's logic. - Explain how each defect was introduced or triggered by this PR, including - regressions caused by its fixes. Inspect affected shared paths and similar - instances of a confirmed defect so the fix covers the same problem within the - affected scope. Search for duplicated rules, obsolete concepts, adjacent - implementations, and conflicting sources of truth as needed. Independent old - defects that the change does not trigger remain separate work. -9. **Robustness and error handling.** Does error handling follow the repository's - fail-fast requirements and the recovery behavior allowed by the product? Are - errors swallowed, required inputs hidden by defaults, or mandatory steps - bypassed? Can failures be traced to their cause? For external writes, files, and - resources, examine partial success, timeouts after an operation has taken - effect, retries, interruption, rollback, and cleanup together. Error handling - must not cause duplicate operations, lose original data or committed results, - or delete resources needed for recovery. -10. **Validation coverage.** Do validation commands match the change's risks? Tests - should follow user scenarios and behavior contracts, covering existing correct - behavior, new behavior, accepted and rejected cases, and relevant failures - rather than repeating the implementation. Do tests run in the default - collection? Do mocks hide real interface changes, or results depend on local - machine configuration? Do regression cases run by default? Use real - producer/consumer contracts. Inspect commands and results for the reviewed - revision; when permitted, run focused reproductions and passing controls. - When packaging or distribution is affected, verify the installed package as - well. Type, format, syntax, and other static checks do not establish runtime - correctness. Choose verification appropriate to the affected behavior; do not - add redundant tests or demand unrelated end-to-end runs for documentation-only - changes. -11. **Historical regressions.** When migrating, rewriting, or restoring old code, - defaults, delays, fallbacks, special cases, or test semantics, ask: "Did this - behavior exist before? Was it removed because it caused a problem? Does that - reason still apply?" Consult Git history when needed. For a suspected revival, - check the current reachable paths, the reason for the original fix, and the - validation evidence. Report a confirmed return of broken behavior; do not - present suspicion as an established defect. -12. **Upstream capabilities.** For framework or provider behavior, have the locked - version and current official documentation, APIs, and release notes been - checked, with upstream source consulted where needed? Does the change use - official lifecycle hooks and extension points where suitable? If a custom - adapter works around an upstream limitation, is the gap reproducible, is the - workaround confined to the protocol boundary, and does it have behavior tests? -13. **Human approval boundaries.** Do tool permissions, user authorization, and the - actual operations agree? High-risk operations must respect required human - approval; unrelated approval steps should not repeatedly interrupt reversible, - low-risk actions. - -`review` assesses the implementation and change risks. `verify` determines whether -the agreed success criteria have been met. A review with no findings does not -replace necessary acceptance checks. - -## Priority levels - -First establish that the finding is valid and belongs to this PR. Then classify -its actual impact and urgency: - -| Level | Criteria | -| --- | --- | -| P0: urgent, critical | Widespread loss of core service, major irrecoverable data loss, or a severe breach of security boundaries requiring immediate action. A security or data concern is not automatically P0. | -| P1: high priority | Broken primary functionality, a critical user journey, or a compatibility contract; or substantial security, data, or resource risk. The impact falls short of P0 but warrants priority repair. | -| P2: normal priority | Lower or localized impact, with evidence of a functional, boundary, maintainability, validation, or applicable mandatory-rule defect. Personal preference is still not a defect. | - -Label each finding P0, P1, or P2 and explain the classification. Preserve the tool's -field protocol: if it only provides `severity`, use `critical` for P0, `high` for -P1, and `medium` or `low` for P2 according to impact, with the P level in the -comment text. Severity and blocking status are separate judgments. All three -levels are blocking by default under this shared policy; exceptions require an -explicit agreement. - -## Output and feedback handling - -Follow the review tool's result structure and the priority definitions above. -Report all valid findings within scope, sorted by severity, without a fixed count -limit. Combine findings with the same root cause. Place inline comments at changed -locations allowed by the tool; old code may still supply root-cause evidence. Each -finding should state its relationship to this PR, evidence or applicable rule, -impact, and the behavior or constraint to restore. Give the smallest correction -when it is known. - -Valid in-scope findings, including P2 and findings from either official or local -rules, block merging by default. Mark a finding non-blocking only when the user -or repository maintainer has explicitly agreed to that exception, and cite the -agreement. - -Apply the same judgment to feedback on the PR. Fix valid findings owned by this -PR, check the current behavior for already-fixed findings, explain why rejected -findings do not hold, and leave unrelated old defects to their own tasks. Read -replies as well as thread roots. A valid finding does not make its suggested fix -correct: do not delete correct test expectations or change agreed requirements -merely to eliminate a comment. - -Keep summaries and execution records out of inline findings. The rules do not -themselves authorize a model to publish comments. With no findings, return the -empty result required by the tool protocol. When a summary is requested, lead with -"pass", "conditional pass", or "fail" in the required review language, then state -the covered paths, evidence-backed residual risks, and unverified items. Do not -invent risks or repeat the checklist. Use full URLs or `owner/repo#number` for -cross-repository references; verify the repository, title, relevant revision, and -merge state. Distinguish a tested pair of revisions, an unmerged dependency, and -a defect in the current candidate. - -## Re-review and completion - -The first pass covers the assigned net diff and reports confirmed findings -promptly, without saving some for later rounds. Use independent or parallel -reviewers for distinct risks when the host supports them, authorization permits -it, and they improve coverage. Re-review may focus on unresolved -findings, fixes, and their effects, while retaining the same task goal and full -PR scope. Follow any explicit requirement for a fresh review of the whole current -candidate. Previous approvals or findings do not substitute for checking the -current changes. - -Missed findings may be added with newly confirmed evidence and a clear -relationship to this PR. That evidence may come from code unchanged since the -previous review; a new commit is not required. Reopening a handled finding needs -evidence that the defect remains or that its fix caused a regression. - -Touching more files during a fix does not require cleaning up every old problem -in those files. The work can close when valid in-scope findings are resolved and -necessary verification passes. Add task requirements only when the user or -repository maintainer explicitly changes the goal. - - ---- - -# Browser Eval review supplement - -Follow the repository review constraints in `AGENTS.md` and `CONTRIBUTING.md`. The following requirements belong to Browser Eval and supplement the shared criteria in `docs/references/review-guidelines.md` and OCR's built-in rules. - -## Repository checks - -Keep provider execution and reporting in the harness; use benchmark-owned definitions and scoring. Trace scored answers to native evidence. Verify populations, timing and certification against the selected track contract. Preserve frozen evidence and report targets, keep private run data outside Git, and check report views agree with their evidence. diff --git a/.opencodereview/review-rules.md b/.opencodereview/review-rules.md deleted file mode 100644 index df6ee9f59..000000000 --- a/.opencodereview/review-rules.md +++ /dev/null @@ -1,7 +0,0 @@ -# Browser Eval review supplement - -Follow the repository review constraints in `AGENTS.md` and `CONTRIBUTING.md`. The following requirements belong to Browser Eval and supplement the shared criteria in `docs/references/review-guidelines.md` and OCR's built-in rules. - -## Repository checks - -Keep provider execution and reporting in the harness; use benchmark-owned definitions and scoring. Trace scored answers to native evidence. Verify populations, timing and certification against the selected track contract. Preserve frozen evidence and report targets, keep private run data outside Git, and check report views agree with their evidence. diff --git a/.opencodereview/rule.json b/.opencodereview/rule.json index c62aa1ca4..89b2460ea 100644 --- a/.opencodereview/rule.json +++ b/.opencodereview/rule.json @@ -2,7 +2,7 @@ "rules": [ { "path": "**", - "rule": ".opencodereview/review-rules.generated.md", + "rule": "docs/references/review-guidelines.md", "merge_system_rule": true } ] diff --git a/AGENTS.md b/AGENTS.md index dd53b9003..52a9cd095 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,10 @@ # Code review -Use [Shared Review Guidelines](docs/references/review-guidelines.md) and the -[repository supplement](.opencodereview/review-rules.md). The shared guide is -generated from the commit recorded in `review-guidelines.lock.json`; change -common requirements in `lexmount/ai-template-py` and synchronize the copy. -OCR reads `.opencodereview/review-rules.generated.md`, which contains both documents -in full. The source lock covers shared policy text; repository maintenance logic -lives in `harness/review_guidelines.py` behind the thin script entry point. +Use [Review Guidelines](docs/references/review-guidelines.md). Its shared text and +`scripts/review_guidelines.py` are synchronized from the commit recorded in +`review-guidelines.lock.json`; change them in `lexmount/ai-template-py`. Browser +Eval's own requirements follow the repository supplement marker at the end of the +guide and are edited here. # Benchmark ownership diff --git a/docs/references/review-guidelines.md b/docs/references/review-guidelines.md index 8dfe288b9..a12f5affe 100644 --- a/docs/references/review-guidelines.md +++ b/docs/references/review-guidelines.md @@ -4,11 +4,13 @@ The canonical version of this document lives in `lexmount/ai-template-py` at `docs/references/review-guidelines.md`. Consumer repositories synchronize their copies with `scripts/review_guidelines.py` and pin the source revision in `review-guidelines.lock.json`. Change the canonical document rather than editing -a synchronized copy. +a synchronized copy. A consumer adds its own requirements only after the +repository review supplement marker at the end of its copy; synchronization +preserves that section. OCR's official rules remain the foundation. This document adds shared review, -scope, and feedback requirements. Read the repository's local review supplement -for its domain requirements. Use the review language required by the user or +scope, and feedback requirements. The repository supplement at the end of this +document, when present, adds the consumer's domain requirements and entry points. Use the review language required by the user or repository; preserve code identifiers, commands, schema values, and product names. ## Establish the review basis @@ -231,3 +233,13 @@ Touching more files during a fix does not require cleaning up every old problem in those files. The work can close when valid in-scope findings are resolved and necessary verification passes. Add task requirements only when the user or repository maintainer explicitly changes the goal. + + + +## Browser Eval review supplement + +Follow the repository review constraints in `AGENTS.md` and `CONTRIBUTING.md`. The following requirements belong to Browser Eval and supplement the shared criteria above and OCR's built-in rules. + +### Repository checks + +Keep provider execution and reporting in the harness; use benchmark-owned definitions and scoring. Trace scored answers to native evidence. Verify populations, timing and certification against the selected track contract. Preserve frozen evidence and report targets, keep private run data outside Git, and check report views agree with their evidence. diff --git a/harness/review_guidelines.py b/harness/review_guidelines.py deleted file mode 100644 index b0b6e1793..000000000 --- a/harness/review_guidelines.py +++ /dev/null @@ -1,213 +0,0 @@ -"""Publish pinned shared guidance through a complete repository review entry.""" - -from __future__ import annotations - -import argparse -import hashlib -import json -from pathlib import Path -import re -import subprocess -import sys -from tempfile import TemporaryDirectory -from urllib.parse import urlsplit - -REPOSITORY = "lexmount/ai-template-py" -GUIDE = "docs/references/review-guidelines.md" -SUPPLEMENT = ".opencodereview/review-rules.md" -ENTRY = ".opencodereview/review-rules.generated.md" -LOCK = "review-guidelines.lock.json" - - -def git(root: Path, *args: str) -> bytes: - return subprocess.run( - ["git", "-C", str(root), *args], check=True, capture_output=True, - ).stdout - - -def repository_root(path: Path) -> Path: - return Path(git(path, "rev-parse", "--show-toplevel").decode().strip()).resolve() - - -def has_source_remote(root: Path) -> bool: - for name in git(root, "remote").decode().splitlines(): - url = git(root, "remote", "get-url", name).decode().strip().rstrip("/").lower() - if url.startswith("git@github.com:"): - repository = url.removeprefix("git@github.com:") - else: - parsed = urlsplit(url) - if parsed.scheme not in {"https", "ssh"} or parsed.hostname != "github.com": - continue - repository = parsed.path.lstrip("/") - if repository.removesuffix(".git") == REPOSITORY: - return True - return False - - -def managed_path(root: Path, relative: str) -> Path: - name = Path(relative) - if name.is_absolute() or ".." in name.parts: - raise ValueError("Review files must remain inside the repository") - path = root / name - if path.exists() and not path.is_file(): - raise ValueError(f"Managed destination must be a file: {relative}") - for candidate in (path, *path.parents): - if candidate == root: - break - if candidate.is_symlink(): - raise ValueError(f"Managed paths must not be symlinks: {relative}") - if candidate != path and candidate.exists() and not candidate.is_dir(): - raise ValueError(f"Managed parent must be a directory: {relative}") - return path - - -def digest(content: bytes) -> str: - return hashlib.sha256(content).hexdigest() - - -def source_guide(source: Path, revision: str) -> bytes: - if not re.fullmatch(r"[0-9a-f]{40}", revision): - raise ValueError("Use a full 40-character source commit, not a moving ref") - if not has_source_remote(source): - raise ValueError(f"Configure a source checkout remote for {REPOSITORY}") - if git(source, "cat-file", "-t", revision).strip() != b"commit": - raise ValueError("The source revision must identify a commit") - content = git(source, "show", f"{revision}:{GUIDE}") - if not content.strip(): - raise ValueError("The shared guide must not be empty") - return content - - -def compose(guide: bytes, supplement: bytes) -> bytes: - if not supplement.strip(): - raise ValueError("The repository review supplement must not be empty") - header = f"\n\n" - return header.encode() + guide + b"\n\n---\n\n" + supplement - - -def check_routing(root: Path, guide: bytes, supplement: bytes, entry: bytes) -> None: - config = json.loads(managed_path(root, ".opencodereview/rule.json").read_text()) - rules = config.get("rules") if isinstance(config, dict) else None - if not isinstance(rules, list): - raise ValueError("OCR rules must be a list") - for rule in rules: - if (isinstance(rule, dict) and rule.get("rule", "") == "" - and rule.get("merge_system_rule", False) is False): - continue - if not isinstance(rule, dict) or not isinstance(rule.get("path"), str): - raise ValueError("Each OCR rule must declare a path") - if rule.get("merge_system_rule") is not True: - raise ValueError("Every reachable OCR route must retain built-in rules") - rule_path = rule.get("rule") - if not isinstance(rule_path, str): - raise ValueError("Each OCR rule must name its complete review entry") - is_file = ( - "\n" not in rule_path and " " not in rule_path - and Path(rule_path).suffix.lower() in {".md", ".txt", ".markdown"} - ) - if is_file: - body = entry if rule_path == ENTRY else managed_path(root, rule_path).read_bytes() - else: - body = rule_path.encode() - if guide not in body or supplement not in body: - raise ValueError("Every reachable OCR route must include shared and local guidance") - # OCR uses the first matching rule; a catch-all makes later entries unreachable. - if rule["path"] == "**": - return - raise ValueError("OCR needs a catch-all route for the complete review entry") - - -def pinned_guide(root: Path, source: Path | None = None) -> bytes: - lock = json.loads(managed_path(root, LOCK).read_text()) - if not isinstance(lock, dict) or lock.get("version") != 2 or lock.get("repository") != REPOSITORY: - raise ValueError("Unsupported review source lock") - revision = lock.get("revision") - if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision): - raise ValueError("The source lock must pin a full commit") - if not isinstance(lock.get("files"), dict) or set(lock["files"]) != {GUIDE}: - raise ValueError("The source lock must cover exactly the shared guide") - guide = managed_path(root, GUIDE).read_bytes() - if not guide.strip() or digest(guide) != lock["files"][GUIDE]: - raise ValueError("Local drift in the shared guide; synchronize from the source") - if source is not None and guide != source_guide(source, revision): - raise ValueError(f"Source mismatch at {revision}: {GUIDE}") - return guide - - -def check(root: Path, source: Path | None = None) -> None: - guide = pinned_guide(root, source) - supplement = managed_path(root, SUPPLEMENT).read_bytes() - entry = compose(guide, supplement) - if managed_path(root, ENTRY).read_bytes() != entry: - raise ValueError("Review entry is stale; run scripts/review_guidelines.py render") - check_routing(root, guide, supplement, entry) - print(f"Review guidance verified: {root}") - - -def install(root: Path, payloads: dict[str, bytes]) -> None: - with TemporaryDirectory(prefix=".review-guidelines-", dir=root) as directory: - staged = Path(directory) - for path, content in payloads.items(): - (staged / Path(path).name).write_bytes(content) - # Each replacement is atomic; the source lock is published last. - for path in payloads: - destination = managed_path(root, path) - destination.parent.mkdir(parents=True, exist_ok=True) - (staged / Path(path).name).replace(destination) - - -def render(root: Path) -> None: - guide = pinned_guide(root) - supplement = managed_path(root, SUPPLEMENT).read_bytes() - entry = compose(guide, supplement) - check_routing(root, guide, supplement, entry) - install(root, {ENTRY: entry}) - check(root) - - -def sync(source: Path, revision: str, targets: list[Path]) -> None: - guide = source_guide(source, revision) - lock = { - "version": 2, "repository": REPOSITORY, "revision": revision, - "files": {GUIDE: digest(guide)}, - } - prepared = [] - for root in targets: - if root == source: - raise ValueError("Edit the canonical source directly; do not sync over it") - supplement = managed_path(root, SUPPLEMENT).read_bytes() - entry = compose(guide, supplement) - payloads = {GUIDE: guide, ENTRY: entry, LOCK: (json.dumps(lock, indent=2) + "\n").encode()} - for path in payloads: - managed_path(root, path) - check_routing(root, guide, supplement, entry) - prepared.append((root, payloads)) - for root, payloads in prepared: - install(root, payloads) - check(root, source) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - commands = parser.add_subparsers(dest="command", required=True) - verify = commands.add_parser("check", help="Check the pinned guide and complete OCR entry") - verify.add_argument("--source", type=Path, help="Also compare the pinned source commit") - commands.add_parser("render", help="Regenerate the OCR entry after editing local requirements") - update = commands.add_parser("sync", help="Update guidance in opted-in repository checkouts") - update.add_argument("--source", type=Path, required=True) - update.add_argument("--ref", required=True, help="Full merged source commit") - update.add_argument("targets", nargs="+", type=Path) - args = parser.parse_args() - try: - if args.command == "sync": - sync(repository_root(args.source), args.ref, [repository_root(p) for p in args.targets]) - else: - root = repository_root(Path.cwd()) - if args.command == "render": - render(root) - else: - check(root, repository_root(args.source) if args.source else None) - except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as exc: - print(f"Review guidance error: {exc}", file=sys.stderr) - return 1 - return 0 diff --git a/review-guidelines.lock.json b/review-guidelines.lock.json index c16c4bfe4..295f3c790 100644 --- a/review-guidelines.lock.json +++ b/review-guidelines.lock.json @@ -1,8 +1,9 @@ { - "version": 2, + "version": 1, "repository": "lexmount/ai-template-py", - "revision": "df1228126c32ccf2c7cdff15b2bc46fa3af519fe", + "revision": "984b8d5319ab3f87b13c2aae38ea9a7c795a3adf", "files": { - "docs/references/review-guidelines.md": "8eb5da2e3a6a7ea9766bb4131b1d1cc9e6191a49fde8f745bd6148196ced51e1" + "docs/references/review-guidelines.md": "98f93a11aefd1e003a778d889a77d9283b49ea786d7db3c38ed04005561cba06", + "scripts/review_guidelines.py": "6732c01ba592f098f32f76bad3ad5bde7d23002fc70a9acde2b16a48f6c0f96c" } } diff --git a/scripts/review_guidelines.py b/scripts/review_guidelines.py index e544fbaac..a0c9e0de5 100644 --- a/scripts/review_guidelines.py +++ b/scripts/review_guidelines.py @@ -1,10 +1,182 @@ -"""Synchronize shared guidance and generate the repository's complete OCR entry.""" +"""Synchronize pinned review guidance and verify its local integrity.""" -import sys +from __future__ import annotations + +import argparse +import hashlib +import json from pathlib import Path +import re +import subprocess +import sys +from tempfile import TemporaryDirectory + + +REPOSITORY = "lexmount/ai-template-py" +FILES = ("docs/references/review-guidelines.md", "scripts/review_guidelines.py") +LOCK = "review-guidelines.lock.json" +# A consumer's copy of the guide may end with its own requirements after this +# line. The lock and source comparison cover only the shared text above it. +SUPPLEMENT = b"" + + +def git(root: Path, *args: str) -> bytes: + return subprocess.run( + ["git", "-C", str(root), *args], check=True, capture_output=True + ).stdout + + +def repository_root(path: Path) -> Path: + return Path(git(path, "rev-parse", "--show-toplevel").decode().strip()).resolve() + + +def is_source(root: Path) -> bool: + remote = git(root, "remote", "get-url", "origin").decode().strip().rstrip("/") + remote = remote.removesuffix(".git").replace("ssh://git@github.com/", "git@github.com:") + return remote in ( + f"git@github.com:{REPOSITORY}", + f"https://github.com/{REPOSITORY}", + ) + + +def shared_part(path: str, content: bytes) -> bytes: + if path != FILES[0]: + return content + shared, marker, _ = content.partition(SUPPLEMENT) + # Blank lines before the marker separate the sections and are not shared text. + return shared.rstrip(b"\n") + b"\n" if marker else shared + + +def local_part(path: str, content: bytes) -> bytes: + index = content.find(SUPPLEMENT) if path == FILES[0] else -1 + return b"" if index < 0 else b"\n" + content[index:] + + +def managed_path(root: Path, relative: str) -> Path: + path = root / relative + if path.exists() and not path.is_file(): + raise ValueError(f"Managed destination must be a file: {path}") + for candidate in (path, *path.parents): + if candidate == root: + break + if candidate.is_symlink(): + raise ValueError(f"Managed paths must not be symlinks: {candidate}") + if candidate != path and candidate.exists() and not candidate.is_dir(): + raise ValueError(f"Managed parent must be a directory: {candidate}") + return path + + +def digest(content: bytes) -> str: + return hashlib.sha256(content).hexdigest() + + +def source_files(source: Path, revision: str) -> dict[str, bytes]: + if not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError("Use a full 40-character source commit, not a moving ref") + if not is_source(source): + raise ValueError(f"Source origin must be {REPOSITORY}") + if git(source, "cat-file", "-t", revision).strip() != b"commit": + raise ValueError("The source revision must identify a commit") + contents = {path: git(source, "show", f"{revision}:{path}") for path in FILES} + if local_part(FILES[0], contents[FILES[0]]): + raise ValueError("The canonical guide must not contain a repository supplement") + return contents + + +def check_routing(root: Path) -> None: + config_path = root / ".opencodereview/rule.json" + if not config_path.exists(): + raise ValueError("Missing .opencodereview/rule.json") + rules = json.loads(config_path.read_text())["rules"] + if rules != [{"path": "**", "rule": FILES[0], "merge_system_rule": True}]: + raise ValueError("OCR must load the shared guide and retain built-in rules") + + +def check(root: Path, source: Path | None = None) -> None: + lock_path = managed_path(root, LOCK) + if not lock_path.exists(): + if not is_source(root): + raise ValueError(f"Missing {LOCK}; synchronize from {REPOSITORY}") + for path in FILES: + content = managed_path(root, path).read_bytes() + if not content.strip(): + raise ValueError(f"Empty source file: {path}") + if local_part(path, content): + raise ValueError("The canonical guide must not contain a repository supplement") + else: + lock = json.loads(lock_path.read_text()) + if lock.get("repository") != REPOSITORY or lock.get("version") != 1: + raise ValueError("Unsupported review source lock") + revision = lock["revision"] + if not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{40}", revision): + raise ValueError("The source lock must pin a full commit") + if set(lock["files"]) != set(FILES): + raise ValueError("The lock must cover the guide and synchronization tool") + upstream = source_files(source, revision) if source is not None else None + for path in FILES: + local = shared_part(path, managed_path(root, path).read_bytes()) + if digest(local) != lock["files"][path]: + raise ValueError(f"Local drift: {path}; synchronize, do not edit the copy") + if upstream is not None and local != upstream[path]: + raise ValueError(f"Source mismatch at {revision}: {path}") + check_routing(root) + print(f"Review guidance verified: {root}") + + +def sync(source: Path, revision: str, targets: list[Path]) -> None: + contents = source_files(source, revision) + lock = { + "version": 1, + "repository": REPOSITORY, + "revision": revision, + "files": {path: digest(data) for path, data in contents.items()}, + } + prepared = [] + # Validate every destination before writing; repositories are then updated in turn. + for root in targets: + if is_source(root): + raise ValueError("Edit the canonical source directly; do not sync over it") + payloads = {**contents, LOCK: (json.dumps(lock, indent=2) + "\n").encode()} + for path in payloads: + managed_path(root, path) + guide = root / FILES[0] + if guide.exists(): + payloads[FILES[0]] += local_part(FILES[0], guide.read_bytes()) + check_routing(root) + prepared.append((root, payloads)) + for root, payloads in prepared: + with TemporaryDirectory(prefix=".review-guidelines-", dir=root) as directory: + staged = Path(directory) + for path, data in payloads.items(): + (staged / Path(path).name).write_bytes(data) + # Replace complete files on the same filesystem, publishing the lock last. + for path in payloads: + destination = managed_path(root, path) + destination.parent.mkdir(parents=True, exist_ok=True) + (staged / Path(path).name).replace(destination) + check(root, source) + -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from harness.review_guidelines import main +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + verify = commands.add_parser("check", help="Check the pinned local files offline") + verify.add_argument("--source", type=Path, help="Also compare the pinned Git source") + update = commands.add_parser("sync", help="Update one or more repository checkouts") + update.add_argument("--source", type=Path, required=True) + update.add_argument("--ref", required=True, help="Full source commit") + update.add_argument("targets", nargs="+", type=Path) + args = parser.parse_args() + try: + if args.command == "check": + source = repository_root(args.source) if args.source else None + check(repository_root(Path.cwd()), source) + else: + sync(repository_root(args.source), args.ref, [repository_root(p) for p in args.targets]) + except (OSError, ValueError, KeyError, TypeError, subprocess.CalledProcessError) as exc: + print(f"Review guidance error: {exc}", file=sys.stderr) + return 1 + return 0 if __name__ == "__main__": diff --git a/tests/test_review_guidelines.py b/tests/test_review_guidelines.py deleted file mode 100644 index 038e3fa5d..000000000 --- a/tests/test_review_guidelines.py +++ /dev/null @@ -1,306 +0,0 @@ -"""Contracts for complete OCR inputs, pinned updates and local verification.""" - -import errno -import json -from pathlib import Path -import subprocess -import sys - -import pytest - -from harness import review_guidelines as review - -ROOT = Path(__file__).resolve().parents[1] -SCRIPT = ROOT / "scripts/review_guidelines.py" - - -def git(root, *args): - return subprocess.check_output(["git", "-C", str(root), *args]).decode().strip() - - -def repository(root, source=False): - root.mkdir() - git(root, "init", "-qb", "main") - git(root, "config", "user.name", "Test") - git(root, "config", "user.email", "test@example.invalid") - if source: - git(root, "remote", "add", "origin", "https://github.com/lexmount/ai-template-py.git") - return root - - -def consumer(root): - repository(root) - (root / ".opencodereview").mkdir() - (root / review.SUPPLEMENT).write_text("# Local checks\nKeep native scoring evidence.\n") - (root / ".opencodereview/rule.json").write_text(json.dumps({"rules": [{ - "path": "**", "rule": review.ENTRY, "merge_system_rule": True, - }]})) - return root - - -def command(root, *args): - return subprocess.run( - [sys.executable, str(SCRIPT), *map(str, args)], cwd=root, - capture_output=True, text=True, - ) - - -@pytest.fixture -def repos(tmp_path): - source = repository(tmp_path / "source", source=True) - (source / "docs/references").mkdir(parents=True) - (source / review.GUIDE).write_text("# Shared criteria\nPreserve existing supported behavior.\n") - git(source, "add", ".") - git(source, "commit", "-qm", "initial shared requirements") - revision = git(source, "rev-parse", "HEAD") - target = consumer(tmp_path / "target") - review.sync(source, revision, [target]) - return source, target, revision - - -def test_repository_entry_contains_complete_shared_and_local_requirements(): - review.check(ROOT) - shared = (ROOT / review.GUIDE).read_bytes() - local = (ROOT / review.SUPPLEMENT).read_bytes() - entry = (ROOT / review.ENTRY).read_bytes() - assert entry.count(shared) == 1 - assert entry.count(local) == 1 - - -def test_sync_uses_committed_policy_and_preserves_local_code_and_requirements(repos): - source, target, revision = repos - expected = (target / review.GUIDE).read_bytes() - (source / review.GUIDE).write_text("uncommitted requirement") - (source / "scripts").mkdir() - (source / "scripts/review_guidelines.py").write_text("upstream tool") - (target / "scripts").mkdir() - tool = target / "scripts/review_guidelines.py" - tool.write_text("repository-owned tool") - local = (target / review.SUPPLEMENT).read_bytes() - review.sync(source, revision, [target]) - assert (target / review.GUIDE).read_bytes() == expected - assert (target / review.SUPPLEMENT).read_bytes() == local - assert tool.read_text() == "repository-owned tool" - review.check(target, source) - - -@pytest.mark.parametrize("path", [review.GUIDE, review.SUPPLEMENT, review.ENTRY]) -def test_check_rejects_changed_inputs_without_rewriting_them(repos, path): - _, target, _ = repos - changed = (target / path).read_bytes() + b"\nNew requirement.\n" - (target / path).write_bytes(changed) - result = command(target, "check") - assert result.returncode != 0 - assert (target / path).read_bytes() == changed - - -def test_render_updates_local_requirements_without_rewriting_source_lock(repos): - _, target, _ = repos - lock = (target / review.LOCK).read_bytes() - shared = (target / review.GUIDE).read_bytes() - local = b"# Revised local criteria\nReview evidence and ownership together.\n" - (target / review.SUPPLEMENT).write_bytes(local) - assert command(target, "render").returncode == 0 - assert local in (target / review.ENTRY).read_bytes() - assert (target / review.GUIDE).read_bytes() == shared - assert (target / review.LOCK).read_bytes() == lock - assert command(target, "check").returncode == 0 - - -def test_render_cannot_hide_drift_in_the_pinned_shared_guide(repos): - _, target, _ = repos - before = (target / review.ENTRY).read_bytes() - (target / review.GUIDE).write_text("edited local copy") - assert command(target, "render").returncode != 0 - assert (target / review.ENTRY).read_bytes() == before - - -@pytest.mark.parametrize("change", ["repository", "revision", "files", "version", "checksum", "shape"]) -def test_invalid_source_lock_is_rejected(repos, change): - _, target, _ = repos - lock = json.loads((target / review.LOCK).read_text()) - if change == "repository": - lock["repository"] = "another/repository" - elif change == "revision": - lock["revision"] = "main" - elif change == "files": - lock["files"] = {} - elif change == "version": - lock["version"] = 1 - elif change == "checksum": - lock["files"][review.GUIDE] = "0" * 64 - else: - lock = [] - (target / review.LOCK).write_text(json.dumps(lock)) - assert command(target, "check").returncode != 0 - - -def test_missing_lock_is_rejected(repos): - _, target, _ = repos - (target / review.LOCK).unlink() - assert command(target, "check").returncode != 0 - - -def test_check_resolves_the_repository_from_a_nested_directory(repos): - source, target, _ = repos - nested = target / "scripts/nested" - nested.mkdir(parents=True) - result = command(nested, "check", "--source", source) - assert result.returncode == 0, result.stderr - assert str(target) in result.stdout - - -@pytest.mark.parametrize("url", [ - "git@github.com:lexmount/ai-template-py.git", - "ssh://git@github.com/lexmount/ai-template-py.git", - "https://github.com/LEXMOUNT/AI-TEMPLATE-PY.git/", -]) -def test_source_checkout_accepts_standard_remote_urls_and_other_remote_names(repos, url): - source, target, _ = repos - git(source, "remote", "rename", "origin", "upstream") - git(source, "remote", "set-url", "upstream", url) - result = command(target, "check", "--source", source) - assert result.returncode == 0, result.stderr - - -def test_missing_source_remote_has_a_clear_error(repos): - source, target, _ = repos - git(source, "remote", "remove", "origin") - result = command(target, "check", "--source", source) - assert result.returncode != 0 - assert "Configure a source checkout remote" in result.stderr - assert "Traceback" not in result.stderr - - -def test_source_comparison_rejects_a_relabelled_revision(repos): - source, target, _ = repos - (source / review.GUIDE).write_text("# Changed requirements\n") - git(source, "add", review.GUIDE) - git(source, "commit", "-qm", "change requirements") - lock = json.loads((target / review.LOCK).read_text()) - lock["revision"] = git(source, "rev-parse", "HEAD") - (target / review.LOCK).write_text(json.dumps(lock)) - assert command(target, "check").returncode == 0 - result = command(target, "check", "--source", source) - assert result.returncode != 0 - assert "Source mismatch" in result.stderr - - -@pytest.mark.parametrize("revision", ["main", "a" * 40]) -def test_unavailable_or_moving_source_revision_leaves_the_target_unchanged(repos, revision): - source, target, _ = repos - before = {path: (target / path).read_bytes() for path in [review.GUIDE, review.ENTRY, review.LOCK]} - assert command(target, "sync", "--source", source, "--ref", revision, target).returncode != 0 - assert {path: (target / path).read_bytes() for path in before} == before - - -def test_git_tree_is_not_accepted_as_a_source_commit(repos): - source, target, _ = repos - result = command(target, "sync", "--source", source, "--ref", git(source, "write-tree"), target) - assert result.returncode != 0 - assert "must identify a commit" in result.stderr - - -@pytest.mark.parametrize("mode", ["disabled_builtin", "missing_fallback", "shadowed"]) -def test_incomplete_effective_ocr_routes_are_rejected(repos, mode): - _, target, _ = repos - fallback = {"path": "**", "rule": review.ENTRY, "merge_system_rule": True} - rules = [dict(fallback)] - if mode == "disabled_builtin": - rules[0]["merge_system_rule"] = False - elif mode == "missing_fallback": - rules[0]["path"] = "**/*.py" - else: - rules.insert(0, {"path": "**/*.py", "rule": review.SUPPLEMENT, "merge_system_rule": True}) - (target / ".opencodereview/rule.json").write_text(json.dumps({"rules": rules})) - assert command(target, "check").returncode != 0 - - -def test_additional_rules_follow_ocr_first_match_behavior(repos): - source, target, revision = repos - rules = [ - {"path": "**", "rule": "", "merge_system_rule": False}, - {"path": "**/*.py", "rule": review.ENTRY, "merge_system_rule": True}, - {"path": "**", "rule": review.ENTRY, "merge_system_rule": True}, - {"path": "**", "rule": review.SUPPLEMENT, "merge_system_rule": True}, - ] - (target / ".opencodereview/rule.json").write_text(json.dumps({"rules": rules})) - review.sync(source, revision, [target]) - assert command(target, "check").returncode == 0 - - -def test_inline_rules_preserve_complete_guidance(repos): - _, target, _ = repos - body = (target / review.ENTRY).read_text() - config = {"rules": [{"path": "**", "rule": body, "merge_system_rule": True}]} - (target / ".opencodereview/rule.json").write_text(json.dumps(config)) - assert command(target, "check").returncode == 0 - - -def test_invalid_later_target_is_rejected_before_any_changes(repos, tmp_path): - source, target, revision = repos - other = consumer(tmp_path / "other") - (other / "docs").write_text("not a directory") - before = (target / review.LOCK).read_bytes() - with pytest.raises(ValueError, match="must be a directory"): - review.sync(source, revision, [target, other]) - assert (target / review.LOCK).read_bytes() == before - assert not (other / review.LOCK).exists() - - -def test_symlinked_managed_paths_cannot_overwrite_external_files(repos, tmp_path): - source, target, revision = repos - external = tmp_path / "external.md" - external.write_text("external content") - (target / review.GUIDE).unlink() - (target / review.GUIDE).symlink_to(external) - with pytest.raises(ValueError, match="symlinks"): - review.sync(source, revision, [target]) - assert external.read_text() == "external content" - - -def test_failed_staging_preserves_the_existing_files(repos, monkeypatch): - source, target, revision = repos - paths = [review.GUIDE, review.ENTRY, review.LOCK] - before = {path: (target / path).read_bytes() for path in paths} - write = Path.write_bytes - - def fail(path, data): - if path.name == Path(review.ENTRY).name: - write(path, data[:5]) - raise OSError(errno.ENOSPC, "No space left") - return write(path, data) - - with monkeypatch.context() as patch: - patch.setattr(Path, "write_bytes", fail) - with pytest.raises(OSError, match="No space left"): - review.sync(source, revision, [target]) - assert {path: (target / path).read_bytes() for path in paths} == before - review.check(target, source) - - -def test_partial_batch_failure_is_detected_and_retry_repairs_it(repos, tmp_path, monkeypatch): - source, target, revision = repos - other = consumer(tmp_path / "other") - review.sync(source, revision, [other]) - (source / review.GUIDE).write_text("# Updated policy\nA newly agreed criterion.\n") - git(source, "add", review.GUIDE) - git(source, "commit", "-qm", "update shared policy") - updated = git(source, "rev-parse", "HEAD") - replace = Path.replace - - def fail(path, destination): - if destination == other / review.ENTRY: - raise OSError("simulated replacement failure") - return replace(path, destination) - - with monkeypatch.context() as patch: - patch.setattr(Path, "replace", fail) - with pytest.raises(OSError, match="simulated replacement failure"): - review.sync(source, updated, [target, other]) - review.check(target, source) - assert (other / review.GUIDE).read_bytes() == (target / review.GUIDE).read_bytes() - with pytest.raises(ValueError, match="Local drift"): - review.check(other) - review.sync(source, updated, [target, other]) - review.check(other, source)