diff --git a/PLANS.md b/PLANS.md index ecc5b3e7..53d89b2c 100644 --- a/PLANS.md +++ b/PLANS.md @@ -1,5 +1,112 @@ # Execution Plans +## Active Plan: Toolkit 0.16.2 — incremental review efficiency, Runner compatibility and CI deduplication + +plan_schema_version: 2 +Status: active +Release classification: release-required +Target release: 0.16.2 +Next development marker: 0.17.0 +Last Updated: 2026-12-02 + +### Goal + +Reduce repeated native OCR model work with verifiable incremental reuse, measure preparation and MCP costs, and qualify CI deduplication on protected PRs. + +### Plan Origin + +plan_mode_approved + +### Requested Scope + +Deliver [#368](https://github.com/xeonvs/open-code-review-toolkit/issues/368), [#364](https://github.com/xeonvs/open-code-review-toolkit/issues/364) and [#370](https://github.com/xeonvs/open-code-review-toolkit/issues/370) through one implementation draft targeting dev, then prepare the signed release PR. + +### Requirement Traceability + +| Requirement | Outcome | Queue | Status | +| --- | --- | --- | --- | +| REQ-001 | One linked implementation draft and milestone | WQ-01 | done | +| REQ-002 | Exact immutable read/search replay and native token measurements | WQ-02 | done | +| REQ-003 | Separate preflight, preparation and MCP measurements | WQ-03 | done | +| REQ-004 | Hosted CI qualification and resource cleanup | WQ-04 | done | +| REQ-006 | Restore review and posting for ordinary GitLab Runner checkouts with externalized Git configuration | WQ-06 | done | +| REQ-005 | Verified promotion, TestPyPI preview and signed release candidate | WQ-05 | pending | + +### Explicit Non-Goals + +Stable publication requires separate authorization. Workflow credentials and private review material stay outside test fixtures. + +### Constraints + +Reuse evidence for identical inputs and environments. Publish only synthetic cases and anonymous aggregates. Preserve existing replay budgets, DLP, attestation, fork isolation and required check identities. + +### Inputs And Sources + +[#368](https://github.com/xeonvs/open-code-review-toolkit/issues/368), [#364](https://github.com/xeonvs/open-code-review-toolkit/issues/364), [#370](https://github.com/xeonvs/open-code-review-toolkit/issues/370), the native qualification manifest, development and release guides, existing telemetry, provider check rules and [#366](https://github.com/xeonvs/open-code-review-toolkit/pull/366). + +### User Decisions And Answers + +Patch release 0.16.2, one draft to dev, and final cleanup. The maintainer subsequently waived the disposable hosted repository and fork exercise. Preserve the current required triggers and track the outstanding hosted proof in #364. Use the existing native executable for local qualification. + +### Completed Baseline State + +Protected dev incorporates the preceding release workflow repair. The reported token count is an observation from one review. Milestone v0.16.2 tracks the original two issues and the urgent Runner compatibility report. + +### Current Work Queue + +| Item | Work and exit evidence | Requirements | Status | +| --- | --- | --- | --- | +| WQ-01 | Push signed plan and create the linked draft. | REQ-001 | done | +| WQ-02 | Qualify UTF-8/line/body truncation and 99/100/101 matches, PCRE and exclusions. Compare baseline, repeat and control for usage, groups and expected finding. | REQ-002 | done | +| WQ-03 | Measure cold/warm preflight, preparation through first request, evidence construction and repeated query. Attribute time, RSS, Git work and bytes; optimize only measured costs. | REQ-003 | done | +| WQ-04 | Verify existing route evidence for fork, draft and advisory intervals. The maintainer waived the new remote fixture. Keep unqualified trigger changes pending in #364. | REQ-004 | done | +| WQ-06 | Qualify ordinary Runner-managed config includes in GitLab review and posting while retaining immutable coverage, ignored-path and credential boundaries. | REQ-006 | done | +| WQ-05 | Review each logical change and aggregate diff. Merge ready dev PR, promote dev, verify development publication, prepare release PR and request permission. | REQ-005 | pending | + +### Locked Decisions + +Observed native bytes and immutable dependencies determine reuse. Unknown outputs or unavailable proof cause a fresh review of the affected group. Gate changes to protected check behavior on hosted proof. + +### Verification + +Compare equivalent synthetic reviews with one controlled change. Report measured input/output/cached tokens and tool activity when available. Compare first and repeated requests on the same revision and verify evidence identity after optimization. Verify hosted merge eligibility and clean up before handoff. + +### Latest Validation Results + +2026-12-02: #369 opened as a draft with both issue links. Synthetic follow-up against the same revisions and model with filtering disabled used 41,390 input plus output tokens compared with 83,606 on the previous release, and retained the known finding. Default-filter candidate baseline and follow-up qualified and carried the same finding. Installed-path measurements used a local development adapter; released executable binding remains unchanged. The collector reduced full tree listings from five to two with identical evidence and bootstrap bytes. The local preflight and MCP measurements are reported separately in #368. + +On the same synthetic MR range, review and post succeeded with and without a Runner include on 0.16.0. On 0.16.1 only the include case failed before OCR. With the correction, installed OCR reviewed the selected change and posting reported the tracked ignored file as incomplete coverage. The checkout config was unchanged. This used a local HTTPS forge fixture. + +Existing protected fork and draft runs corroborate distinct Actions and CodeQL app checks. After required checks passed, two prior merges took 17 s and 23 s, including cases with pending advisory runners. Required workflow triggers remain unchanged. No remote test infrastructure was created. + +### Risks And Recovery + +Keep broad checks for uncertain CI events. Continue independent work when hosted access is unavailable. Use existing data first, isolate new model runs to synthetic fixtures, and remove temporary materials after retaining sanitized results. + +### Resume Point + +WQ-05: finish aggregate verification and obtain passing protected dev checks, then promote, verify TestPyPI and prepare the signed release PR. Keep #364 open for the outstanding hosted proof. + +### Plan Fidelity Check + +REQ-001 through REQ-006 cover the three issues, native and hosted acceptance, measurements, cleanup, promotion and the authorization boundary. + +### Reconciliation Check + +Use dev and the issue milestone as the development baseline. Keep open issues tracked through the release receipt. + +### Closure Gate + +Require applicable protected checks, completed qualification, measured results, cleanup, verified TestPyPI development artifacts and the signed release candidate. + +### Post-Close Delivery + +Stable publishing, tag, immutable Release, registry verification and issue closure follow explicit owner authorization. + +### Handoff Notes + +Preserve the exact reviewed commits and report unverified scenarios explicitly. + ## Recently Completed - [x] 2026-12-01: Completed Toolkit 0.16.1 — contributor intake and incremental review; [full archived plan](docs/engineering/execution_history/plans/2026-12-01-toolkit-0-16-1-contributor-intake-and-incremental-review.md). diff --git a/changelog.d/368.bugfix.md b/changelog.d/368.bugfix.md new file mode 100644 index 00000000..45fe7802 --- /dev/null +++ b/changelog.d/368.bugfix.md @@ -0,0 +1 @@ +Qualify bounded truncated reads, capped searches, PCRE and supported exclusion pathspecs for local incremental review. Reuse unchanged groups after verifying the native-visible result against immutable Git inputs. diff --git a/changelog.d/370.bugfix.md b/changelog.d/370.bugfix.md new file mode 100644 index 00000000..87980326 --- /dev/null +++ b/changelog.d/370.bugfix.md @@ -0,0 +1 @@ +Restore ordinary GitLab merge request reviews and posting on Runner checkouts with an external Git configuration include. Qualify the immutable diff using a private Git view that omits the external configuration and preserves tracked-file exclusion checks. diff --git a/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml b/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml index 31192278..5c7c4908 100644 --- a/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml +++ b/docs/codex/ENGINEERING_WORKFLOW_STATE.yaml @@ -32,7 +32,7 @@ plan_archive_indexes: - docs/engineering/execution_history/README.md - docs/engineering/README.md - docs/README.md -active_plan: null +active_plan: PLANS.md runtime_agent_config_managed: true instruction_contract_version: 3 planning_contract_version: 2 diff --git a/docs/development.md b/docs/development.md index db082db4..1fbf0585 100644 --- a/docs/development.md +++ b/docs/development.md @@ -40,11 +40,19 @@ coverage owner. CI omits the two advisory macOS jobs for positively classified same-repository documentation-only pull requests and direct promotions from `dev` to `main`. Direct promotions still run the Linux tests and coverage. Manual runs, release-preparation pull requests, fork pull requests and uncertain -classifications retain the full matrix. Once required checks pass for the verified head and base, -an advisory job waiting for a runner can finish independently. Use a manual CI -run to check macOS on a deferred change. -Inspect any reported product regression before promotion. Report runner capacity -separately from test failures and retry only the affected job when appropriate. +classifications retain the full matrix. Once required checks pass for the +verified head and base, an advisory job waiting for a runner can finish +independently. Use a manual CI run to check macOS on a deferred change. Inspect +any reported product regression before promotion and retry only the affected job +when appropriate. + +When measuring CI latency, identify the required checks and their source apps +from the target branch ruleset. Measure the interval from the last required +success to the PR merge. Report that interval separately from runner time and +advisory queue time. A job that never received a runner contributes zero runner +time. An advisory cancellation can leave the workflow run marked failed even +when all required checks passed. + Bandit scans only the supported runtime package at medium-or-higher severity and confidence; tests and synthetic fixtures are outside that bounded gate. @@ -69,9 +77,14 @@ reopening it, updating its head, or editing its base starts checks for the current GitHub test merge. Converting it to draft cancels in-progress review CI on that pull request and uses the draft jobs. Manual and scheduled job names also differ from the ready pull request contexts. Keep the existing -ready jobs required and confirm the successful jobs for the current candidate -and target before merging. See the [protected release path](release.md#stable-release) -for the additional release authorization. +ready jobs required and confirm the successful checks for the current candidate +and target before merging. GitHub Actions reports `analyze-python` and the code +scanning app reports the separate required `CodeQL` result. Finalize the title +and body while the PR is a draft. GitHub sends title, body and base changes as +`edited` events, and the required workflows listen for them to validate +retargeting. Metadata edits after readiness can restart checks for the same +test merge. See the [protected release path](release.md#stable-release) for the +additional release authorization. Runtime code must remain compatible with the Python range and runtime dependencies declared in `pyproject.toml`; `uv.lock` owns the resolved dependency set. Tests must use synthetic data; public examples must use safe placeholder hosts and credentials while describing the real operating behavior rather than labelling the feature itself as synthetic. User-visible changes require a fragment in `changelog.d/`. Repository-only qualification tools and evidence live under `scripts/` and `compatibility/`; they are excluded from both published distributions. Validate the manifest with `PYTHONPATH=src python scripts/ocr_compat.py validate`. diff --git a/docs/gitlab.md b/docs/gitlab.md index a93f5a48..1c6045c0 100644 --- a/docs/gitlab.md +++ b/docs/gitlab.md @@ -171,11 +171,18 @@ publication: a missing receipt stays in the job and cannot publish findings or replace the previous review. A present v9-v13 receipt remains readable for historical diagnostics but blocks a new current MR publication. -The GitLab checkout must contain a direct `.git` directory so the toolkit can -bind the selection rules used by preview and production. A linked worktree or -an external Git configuration include stops the review before OCR runs. The -ordinary projection accepts regular files. Changed symlink entries and -unsupported Git file-type transitions also stop before OCR. +For ordinary merge requests, a direct GitLab Runner checkout can use an +unconditional `include.path` in `.git/config`. Review and posting each +construct a private Git view from the reviewed commit and local objects. +The generated config preserves the direct `core.ignoreCase` setting and +omits the external file, credential helpers and URL rewrites. Tracked ignored +files still require verifiable exclusion evidence before publication. + +Use a direct `.git` directory. Conditional includes, separate worktree +configuration and alternate object stores are unsupported on this isolated +route. A change to a submodule pointer uses the separate gitlink qualification +path. The ordinary projection accepts regular files; changed symlinks and +unsupported file-type transitions stop before OCR. The provider validates same-project ownership, the current MR diff base/start/head/version, source H, actual target branch/T/protection, and selected policy branch/P/protection before OCR. Missing, pending, malformed, or contradictory diff data is unavailable or stale, not an empty review; a valid empty delta is a normal no-change case. `ocr-ci review` collects immutable evidence from actual code revisions, admits context under the selected policy capability, applies DLP and budgets, binds every immutable changed path to OCR's selected/excluded partition, runs OCR once, reconciles federation, validates the result, cleans private state, and attaches the ordinary receipt. `ocr-ci post` hostile-reads that receipt and independently checks the supplied selection against the Git diff; it rejects another `CI_JOB_ID` in a current-review result or preview/setup status when present. A successful result covers this MR only: no parent-MR lookup, chain review, integration claim, extra pipeline trigger, or merge is performed. Arbitrary valid branch names and a target with no parent MR are supported. diff --git a/docs/local.md b/docs/local.md index ea6ffefb..9229a506 100644 --- a/docs/local.md +++ b/docs/local.md @@ -187,13 +187,19 @@ source semantics or changes to shared selection, context, rules or model can require a full review. A direct source read can qualify when the toolkit verifies its result against -an immutable file and the file remains unchanged. This includes a verified -request for a line range beyond the end of the file. The toolkit can repeat -bounded literal `code_search`, `file_find`, `file_read_diff` and built-in -evidence queries over the new inputs. The group qualifies when every replay -produces the same complete result. Changed results, incomplete evidence -pages and ambiguous or unsupported tool requests require fresh review for -that group. Groups newly reviewed in a narrowed run need fresh review again +an immutable file and the file remains unchanged. This covers reads past EOF +and native reads limited by line count, line length or rendered bytes. The +verification includes the visible UTF-8 text, range, line addresses and +omission notices. An edit in a hidden part of the read file requires fresh +review of the dependent group. + +The toolkit repeats bounded `code_search`, `file_find`, `file_read_diff` and +built-in evidence queries on the new inputs. For a capped native code search it +compares the first 100 matches, their order and the matching-file count. +Supported searches include literal and PCRE patterns and bounded +`:(exclude)` file patterns. A changed visible result, an unsupported pathspec, +a search that exceeds resource limits, or an incomplete evidence page calls +for fresh review of that group. Groups newly reviewed in a narrowed run need fresh review again because OCR gave them a shorter comparison inventory. Dependency verification uses locally available Git objects before OCR runs. The report's native tool counters describe calls made by the fresh OCR diff --git a/docs/review-decision-flow.md b/docs/review-decision-flow.md index 4fccf5a0..6fd8564e 100644 --- a/docs/review-decision-flow.md +++ b/docs/review-decision-flow.md @@ -138,7 +138,7 @@ flowchart TD gitlink_scope -- Yes --> gitlink_projection[Freeze original trees, ordinary diff,
Git inputs and child overrides] gitlink_projection --> preview[Run exact OCR preview with
toolkit-owned child environment] gitlink_check -- No, local --> preview - gitlink_check -- No, GitLab --> ordinary_projection[Freeze immutable ordinary diff
and Git selection inputs] + gitlink_check -- No, GitLab --> ordinary_projection[Freeze immutable ordinary diff and Git inputs;
isolate unconditional Runner include] ordinary_projection --> preview preview --> preview_ok{Preview accepted and applicable
Git partition verified?} preview_ok -- Unclassified diagnostics --> preview_unclassified[Closed stage/count status;
model not started] diff --git a/docs/security.md b/docs/security.md index 21fcf930..9aef021d 100644 --- a/docs/security.md +++ b/docs/security.md @@ -199,6 +199,28 @@ automatic approval while preserving publication of the safely reviewed subset. Any reused native work blocks a new automatic GitLab approval and preserves prior finding threads. +GitLab Runner may externalize checkout credentials and Git settings through an +unconditional `include.path` in the direct checkout's local config. Runner +owns that configuration. Its settings grant no authority to select fewer files +for review, mark a partial review complete, or publish configuration values. +For an ordinary GitLab MR in this layout, preview and native review use a +private Git directory with HEAD and index derived from the reviewed commit. +The view uses local objects, disables Git transports and lazy fetches, and +imports only the direct case-sensitivity setting and bounded checkout metadata +for attributes, exclusions and shallow history. The external config is outside +this projection. This boundary governs Git selection; the Runner and the OS +account executing the job remain trusted. + +Review checks the projection again after OCR returns. Before a GitLab write, +posting independently reconstructs selection and checks coverage. Missing +proof stops publication; a proven exclusion blocks automatic approval. +Conditional includes and changed gitlinks retain their separate restrictions. +When hardening expands a check to another MR type, qualify both ordinary Runner +layouts (with and without an include) through review and posting. Include a +tracked, ignored change so the test observes partial coverage as well as a +successful review. This guards against denying routine reviews or silently +approving work that OCR skipped. + Changed Git submodule pointers are a separate repository-coverage boundary. For an exact capability-qualified OCR version, the toolkit compares complete before/after Git trees, the explicit unfiltered diff, and the ordinary-file projection before diff --git a/src/ocr_toolkit/evidence/collect.py b/src/ocr_toolkit/evidence/collect.py index 76ddaffb..fd76b301 100644 --- a/src/ocr_toolkit/evidence/collect.py +++ b/src/ocr_toolkit/evidence/collect.py @@ -21,6 +21,7 @@ from ocr_toolkit.evidence.repository import ( GitRepositoryReader, RepositoryEvidenceError, + RepositoryObject, build_file_snapshot, file_deltas, ) @@ -116,8 +117,20 @@ def collect_repository_evidence( base_sha, head_sha = _commit_refs(reader, base_ref, head_ref) changed = reader.changed_paths(base_sha, head_sha) policy_sha = reader.resolve_commit(policy_ref) if policy_ref is not None else base_sha - base = build_file_snapshot(reader, base_sha, RefRole.BASE, paths=changed) - head = build_file_snapshot(reader, head_sha, RefRole.HEAD, paths=changed) + tree_entries: dict[str, tuple[RepositoryObject, ...]] = {} + + def entries_at(commit_sha: str) -> tuple[RepositoryObject, ...]: + """Share the immutable tree only within this collection call.""" + if commit_sha not in tree_entries: + tree_entries[commit_sha] = reader.list_objects(commit_sha) + return tree_entries[commit_sha] + + base = build_file_snapshot( + reader, base_sha, RefRole.BASE, paths=changed, entries=entries_at(base_sha) + ) + head = build_file_snapshot( + reader, head_sha, RefRole.HEAD, paths=changed, entries=entries_at(head_sha) + ) base_paths = {record.source_path for record in base.records} head_paths = {record.source_path for record in head.records} base_coverage = [] @@ -128,6 +141,7 @@ def collect_repository_evidence( RefRole.BASE, changed_paths=changed, coverage_sink=base_coverage, + entries=entries_at(base_sha), ) if include_policy_records: policy_facts, policy_diagnostics = collect_ref_facts( @@ -135,6 +149,7 @@ def collect_repository_evidence( policy_sha, RefRole.POLICY, changed_paths=changed, + entries=entries_at(policy_sha), ) policy_facts = [record for record in policy_facts if record.kind in POLICY_KINDS] else: @@ -151,6 +166,7 @@ def collect_repository_evidence( RefRole.HEAD, changed_paths=changed, coverage_sink=head_coverage, + entries=entries_at(head_sha), ) base = EvidenceSnapshot( base.ref, @@ -306,10 +322,18 @@ def collect_repository_evidence( else: try: target_files = build_file_snapshot( - reader, target_sha, RefRole.TARGET, paths=changed + reader, + target_sha, + RefRole.TARGET, + paths=changed, + entries=entries_at(target_sha), ) target_facts, target_fact_diagnostics = collect_ref_facts( - reader, target_sha, RefRole.TARGET, changed_paths=changed + reader, + target_sha, + RefRole.TARGET, + changed_paths=changed, + entries=entries_at(target_sha), ) except RepositoryEvidenceError as exc: if str(exc) != "repository tree exceeds the bounded entry limit": diff --git a/src/ocr_toolkit/evidence/collectors/orchestration.py b/src/ocr_toolkit/evidence/collectors/orchestration.py index d67a249b..a58d8a7c 100644 --- a/src/ocr_toolkit/evidence/collectors/orchestration.py +++ b/src/ocr_toolkit/evidence/collectors/orchestration.py @@ -72,6 +72,7 @@ def collect_ref_facts( *, changed_paths: Iterable[str] = (), coverage_sink: list[CoverageRecord] | None = None, + entries: tuple[RepositoryObject, ...] | None = None, ) -> tuple[list[EvidenceRecord], list[str]]: """Collect supported facts from one immutable tree with explicit diagnostics.""" @@ -84,7 +85,8 @@ def collect_ref_facts( ) changed_exact = tuple(sorted(set(changed_paths))) changed = {path.casefold() for path in changed_exact} - entries = reader.list_objects(commit_sha) + if entries is None: + entries = reader.list_objects(commit_sha) entries_by_path = {entry.path: entry for entry in entries} role_paths = selected_role_paths(tuple(entry.path for entry in entries)) topology_entries = tuple( diff --git a/src/ocr_toolkit/evidence/gitlink_projection.py b/src/ocr_toolkit/evidence/gitlink_projection.py index 1b388f75..6b1c151e 100644 --- a/src/ocr_toolkit/evidence/gitlink_projection.py +++ b/src/ocr_toolkit/evidence/gitlink_projection.py @@ -10,8 +10,10 @@ import stat import subprocess import time -from contextlib import ExitStack +from collections.abc import Iterator +from contextlib import ExitStack, contextmanager from dataclasses import dataclass +from dataclasses import field as dataclass_field from pathlib import Path from ocr_toolkit.common.filesystem import open_private_parent_directory, same_file_identity @@ -51,6 +53,14 @@ _REVIEW_SELECTION_SCHEMA = "ocr.review-selection/v1" _LOCAL_INPUTS = (".gitignore", ".gitmodules", ".gitattributes") _GIT_METADATA_INPUTS = ("config", "config.worktree", "info/attributes", "info/exclude") +_GIT_CONFIG_INCLUDE = re.compile(rb"(?im)^\s*\[\s*include(if)?(?:\s|\])") +_GIT_VIEW_NAME = "ordinary-git-view" +_GIT_VIEW_COPIED = ("info/attributes", "info/exclude", "shallow") +_GIT_VIEW_INPUTS = ("config", "HEAD", "index", *_GIT_VIEW_COPIED) + + +class GitProjectionConfigError(RepositoryEvidenceError): + """A fixed diagnostic about local Git config isolation.""" @dataclass(frozen=True, slots=True) @@ -95,6 +105,7 @@ class GitlinkProjection: line_counts: tuple[tuple[str, int, int], ...] environment: tuple[tuple[str, str], ...] input_digest: str + git_view_digest: str | None = None def child_environment(self) -> dict[str, str]: return dict(self.environment) @@ -116,7 +127,14 @@ class ReviewSelection: excluded: tuple[PreviewExclusion, ...] -def _read_input(root: int, path: Path) -> bytes | None: +@dataclass(frozen=True, slots=True) +class _GitInputSnapshot: + digest: str + view_config: bytes | None = dataclass_field(repr=False) + view_files: tuple[tuple[str, bytes], ...] = dataclass_field(repr=False) + + +def _read_input(root: int, path: Path, *, limit: int = _GIT_INPUT_LIMIT) -> bytes | None: parent = root try: for component in path.parts[:-1]: @@ -138,7 +156,7 @@ def _read_input(root: int, path: Path) -> bytes | None: metadata = os.stat(path.name, dir_fd=parent, follow_symlinks=False) except FileNotFoundError: return None - if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > _GIT_INPUT_LIMIT: + if not stat.S_ISREG(metadata.st_mode) or metadata.st_size > limit: raise RepositoryEvidenceError("OCR local Git input is unsafe or too large") descriptor = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=parent) try: @@ -146,11 +164,19 @@ def _read_input(root: int, path: Path) -> bytes | None: if ( not stat.S_ISREG(opened.st_mode) or not same_file_identity(opened, metadata) - or opened.st_size > _GIT_INPUT_LIMIT + or opened.st_size > limit ): raise RepositoryEvidenceError("OCR local Git input changed or is unsafe") - payload = os.read(descriptor, _GIT_INPUT_LIMIT + 1) - if len(payload) > _GIT_INPUT_LIMIT or len(payload) != opened.st_size: + with os.fdopen(descriptor, "rb", closefd=False) as stream: + payload = stream.read(limit + 1) + after = os.fstat(descriptor) + named = os.stat(path.name, dir_fd=parent, follow_symlinks=False) + if ( + len(payload) != opened.st_size + or not same_file_identity(after, named) + or (opened.st_size, opened.st_mtime_ns, opened.st_ctime_ns) + != (after.st_size, after.st_mtime_ns, after.st_ctime_ns) + ): raise RepositoryEvidenceError("OCR local Git input changed or is too large") return payload finally: @@ -162,7 +188,51 @@ def _read_input(root: int, path: Path) -> bytes | None: os.close(parent) -def _input_digest(root: Path, plan: GitlinkInputPlan) -> str: +@contextmanager +def _direct_git_input(root: Path) -> Iterator[tuple[int, int]]: + with ExitStack() as stack: + try: + root_fd, git_name = open_private_parent_directory(root / ".git", create=False) + stack.callback(os.close, root_fd) + git_fd = os.open(git_name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd) + stack.callback(os.close, git_fd) + except (OSError, ValueError) as exc: + raise GitProjectionConfigError( + "OCR Git projection requires a direct Git directory" + ) from exc + yield root_fd, git_fd + + +def _input_digest_frame(path: Path, payload: bytes | None) -> bytes: + data = b"M" if payload is None else b"P" + hashlib.sha256(payload).digest() + return str(path).encode("utf-8") + b"\0" + data + + +def _validate_direct_git_store(git_fd: int) -> os.stat_result: + try: + with ExitStack() as stack: + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW + objects = os.open("objects", flags, dir_fd=git_fd) + stack.callback(os.close, objects) + try: + info = os.open("info", flags, dir_fd=objects) + except FileNotFoundError: + return os.fstat(objects) + stack.callback(os.close, info) + for name in ("alternates", "http-alternates"): + try: + os.stat(name, dir_fd=info, follow_symlinks=False) + except FileNotFoundError: + continue + raise GitProjectionConfigError("OCR Git config isolation requires local objects") + return os.fstat(objects) + except OSError as exc: + raise GitProjectionConfigError("OCR Git config isolation requires local objects") from exc + + +def _input_snapshot( + root: Path, plan: GitlinkInputPlan, *, allow_ordinary_include: bool +) -> _GitInputSnapshot: paths = {Path(path) for path in _LOCAL_INPUTS} git_dir = Path(".git") paths.update(git_dir / path for path in _GIT_METADATA_INPUTS) @@ -173,36 +243,130 @@ def _input_digest(root: Path, plan: GitlinkInputPlan) -> str: break paths.update((directory / ".gitignore", directory / ".gitattributes")) digest = hashlib.sha256() - with ExitStack() as stack: - try: - root_fd, git_name = open_private_parent_directory(root / git_dir, create=False) - stack.callback(os.close, root_fd) - git_fd = os.open(git_name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd) - stack.callback(os.close, git_fd) - except (OSError, ValueError) as exc: - # Linked worktrees have indirect configuration that is not pinned here. - raise RepositoryEvidenceError( - "OCR gitlink projection requires a direct Git directory" - ) from exc + view_config = None + metadata = {} + with _direct_git_input(root) as (root_fd, git_fd): for path in sorted(paths): payload = ( _read_input(git_fd, path.relative_to(git_dir)) if path.is_relative_to(git_dir) else _read_input(root_fd, path) ) - digest.update(str(path).encode("utf-8")) - digest.update(b"\0") - digest.update(b"M" if payload is None else b"P") - if payload is not None: - if path in configs and re.search( - rb"(?im)^\s*\[\s*include(?:if)?(?:\s|\])", - payload.removeprefix(b"\xef\xbb\xbf"), - ): - raise RepositoryEvidenceError("OCR local Git config includes are unsupported") - digest.update(hashlib.sha256(payload).digest()) + if payload is not None and path in configs: + includes = _GIT_CONFIG_INCLUDE.finditer(payload.removeprefix(b"\xef\xbb\xbf")) + for include in includes: + if not allow_ordinary_include or path.name != "config" or include[1]: + raise GitProjectionConfigError( + "OCR local Git config includes are unsupported for this review" + ) + view_config = payload + if path.is_relative_to(git_dir): + metadata[path.relative_to(git_dir).as_posix()] = payload + digest.update(_input_digest_frame(path, payload)) + if view_config is not None: + if ( + metadata["config.worktree"] is not None + or _read_input(git_fd, Path("commondir")) is not None + ): + raise GitProjectionConfigError( + "OCR Git config isolation does not support separate common or worktree config" + ) + objects = _validate_direct_git_store(git_fd) + digest.update(f"objects\0{objects.st_dev}:{objects.st_ino}\0".encode("ascii")) + metadata["shallow"] = _read_input(git_fd, Path("shallow")) + digest.update(_input_digest_frame(git_dir / "shallow", metadata["shallow"])) + view_files = tuple( + (name, payload) for name in _GIT_VIEW_COPIED if (payload := metadata.get(name)) is not None + ) + return _GitInputSnapshot(digest.hexdigest(), view_config, view_files) + + +def _private_git_view_digest(path: Path) -> str: + digest = hashlib.sha256() + try: + descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for name in _GIT_VIEW_INPUTS: + item = Path(name) + limit = 2 * _DIFF_OUTPUT_LIMIT if name == "index" else _GIT_INPUT_LIMIT + digest.update(_input_digest_frame(item, _read_input(descriptor, item, limit=limit))) + finally: + os.close(descriptor) + except (OSError, ValueError) as exc: + raise GitProjectionConfigError("OCR isolated Git config could not be verified") from exc return digest.hexdigest() +def _direct_ignore_case(config: bytes, home: Path, environment: dict[str, str]) -> bytes: + # Ask Git to decode only one boolean in the pinned direct config. The + # external configuration is never opened, copied or passed to OCR. + completed = subprocess.run( + [ + *read_only_git_prefix(), + "config", + "--no-includes", + "--file", + "-", + "--type=bool", + "--get", + "core.ignoreCase", + ], + input=config, + capture_output=True, + cwd=home, + env=environment, + timeout=_GIT_TIMEOUT_SECONDS, + check=False, + ) + if completed.returncode == 1 and not completed.stdout and not completed.stderr: + return b"false" + if ( + completed.returncode == 0 + and not completed.stderr + and completed.stdout in (b"true\n", b"false\n") + ): + return completed.stdout.rstrip(b"\n") + raise GitProjectionConfigError("OCR could not read the direct Git config safely") + + +def _prepare_private_git_view( + root: Path, + home: Path, + head: str, + environment: dict[str, str], + snapshot: _GitInputSnapshot, +) -> Path: + view = home / _GIT_VIEW_NAME + assert snapshot.view_config is not None + try: + ignore_case = _direct_ignore_case(snapshot.view_config, home, environment) + view.mkdir(mode=0o700) + for name in ("info", "objects", "refs"): + (view / name).mkdir(mode=0o700) + for name, payload in snapshot.view_files: + (view / name).write_bytes(payload) + (view / "config").write_bytes( + b"[core]\n\trepositoryformatversion = 0\n\tbare = false\n" + b"\thooksPath = /dev/null\n\tignoreCase = " + ignore_case + b"\n" + ) + (view / "HEAD").write_text(f"{head}\n", encoding="ascii") + environment.update( + GIT_DIR=str(view), + GIT_WORK_TREE=str(root), + GIT_OBJECT_DIRECTORY=str(root / ".git" / "objects"), + GIT_ALLOW_PROTOCOL="", + GIT_NO_LAZY_FETCH="1", + ) + # Preserve attribute lookup for files absent in the checkout using only + # the reviewed tree. No checkout or filter execution is requested. + _git_output(root, ["read-tree", "--", head], environment) + except GitProjectionConfigError: + raise + except (OSError, ValueError, subprocess.TimeoutExpired) as exc: + raise GitProjectionConfigError("OCR could not isolate local Git configuration") from exc + return view + + def _projection_environment(plan: GitlinkInputPlan) -> dict[str, str]: # The same inherited environment is frozen once for preview and production. environment = { @@ -696,13 +860,24 @@ def _patch_fingerprints( def make_gitlink_projection( - reader: GitRepositoryReader, plan: GitlinkInputPlan + reader: GitRepositoryReader, + plan: GitlinkInputPlan, + *, + ordinary_config_home: Path | None = None, ) -> GitlinkProjection: """Qualify the original range and freeze exact OCR Git inputs.""" environment = _projection_environment(plan) root = reader.root - input_digest = _input_digest(root, plan) + allow_ordinary_include = ordinary_config_home is not None and not plan.changes + initial_inputs = _input_snapshot(root, plan, allow_ordinary_include=allow_ordinary_include) + view_digest = None + if initial_inputs.view_config is not None: + assert ordinary_config_home is not None + view = _prepare_private_git_view( + root, ordinary_config_home, plan.head_sha, environment, initial_inputs + ) + view_digest = _private_git_view_digest(view) merge_base = ( _git_output(root, ["merge-base", plan.base_sha, plan.head_sha], environment) .decode("ascii") @@ -726,7 +901,10 @@ def make_gitlink_projection( ): raise RepositoryEvidenceError("OCR non-regular ordinary change is unsupported") fingerprints, line_counts = _patch_fingerprints(root, plan, environment, projected) - if input_digest != _input_digest(root, plan): + if ( + initial_inputs.digest + != _input_snapshot(root, plan, allow_ordinary_include=allow_ordinary_include).digest + ): raise RepositoryEvidenceError("OCR local Git inputs changed during qualification") return GitlinkProjection( plan, @@ -736,7 +914,8 @@ def make_gitlink_projection( fingerprints, line_counts, tuple(sorted(environment.items())), - input_digest, + initial_inputs.digest, + view_digest, ) @@ -744,12 +923,19 @@ def verify_gitlink_projection(reader: GitRepositoryReader, projection: GitlinkPr """Recheck every original endpoint, consulted input and projected record.""" current = plan_review_input(reader, projection.plan.base_sha, projection.plan.head_sha) + isolate = projection.git_view_digest is not None if ( current != projection.plan - or _input_digest(reader.root, projection.plan) != projection.input_digest + or _input_snapshot(reader.root, projection.plan, allow_ordinary_include=isolate).digest + != projection.input_digest ): raise RepositoryEvidenceError("OCR gitlink review inputs drifted") environment = projection.child_environment() + if ( + isolate + and _private_git_view_digest(Path(environment["GIT_DIR"])) != projection.git_view_digest + ): + raise GitProjectionConfigError("OCR isolated Git config changed during review") if ( _raw_diff(reader.root, projection.plan, environment, reveal_gitlinks=True) != projection.original_diff diff --git a/src/ocr_toolkit/evidence/repository.py b/src/ocr_toolkit/evidence/repository.py index b32f9798..8a25b15d 100644 --- a/src/ocr_toolkit/evidence/repository.py +++ b/src/ocr_toolkit/evidence/repository.py @@ -348,6 +348,7 @@ def grep_tree( patterns: tuple[str, ...], *, case_sensitive: bool, + use_perl_regexp: bool = False, ) -> bytes: """Return bounded, NUL-addressed immutable tree matches, without text converters.""" @@ -366,7 +367,7 @@ def grep_tree( args.append("-i") args.extend( [ - "-F", + "-P" if use_perl_regexp else "-F", "-n", "-z", "--no-color", @@ -381,7 +382,7 @@ def grep_tree( ) result = self._run_streamed( args, - timeout=self._timeout(10), + timeout=min(self._timeout(10), 10), text=False, local_only=True, max_bytes=MAX_GIT_GREP_BYTES, @@ -959,8 +960,9 @@ def build_file_snapshot( role: RefRole, *, paths: tuple[str, ...] | None = None, + entries: tuple[RepositoryObject, ...] | None = None, ) -> EvidenceSnapshot: - """Build repository-file facts for a commit without reading file contents.""" + """Build file facts, optionally using entries already read for this commit.""" if role not in {RefRole.BASE, RefRole.HEAD, RefRole.TARGET}: raise RepositoryEvidenceError("file snapshot role must be base, head, or target") @@ -973,7 +975,9 @@ def build_file_snapshot( if role in {RefRole.BASE, RefRole.TARGET} else TrustClass.SOURCE_REPOSITORY ) - for entry in reader.list_objects(sha): + if entries is None: + entries = reader.list_objects(sha) + for entry in entries: if selected is not None and entry.path not in selected: continue if entry.is_symlink: diff --git a/src/ocr_toolkit/local_incremental_dependencies.py b/src/ocr_toolkit/local_incremental_dependencies.py index e7fc9bd2..04e1a544 100644 --- a/src/ocr_toolkit/local_incremental_dependencies.py +++ b/src/ocr_toolkit/local_incremental_dependencies.py @@ -30,6 +30,7 @@ RUN_ID, DependencyScope, IncrementalError, + IncrementalSearchError, ToolReplay, canonical_json, literal_path, @@ -39,7 +40,22 @@ from ocr_toolkit.review_range import ReviewRange from ocr_toolkit.review_trace import NativeTraceSource +_MAX_READ_LINES = 500 +_MAX_READ_LINE_BYTES = 2048 +_MAX_READ_BODY_BYTES = 256 * 1024 +_MAX_READ_METADATA_BYTES = 512 # Header and notes, excluding the file path. _READ_RANGE = re.compile(r"LINE_RANGE: ([0-9]{1,10})-([0-9]{1,10})\Z") +_READ_LINE_NOTE = ( + f"\nNote: Lines longer than {_MAX_READ_LINE_BYTES} bytes were cut mid-line and the omitted " + "bytes are not part of this result. Reason about the visible part only.\n" +).encode() +_READ_BODY_NOTE = ( + f"\nNote: Output truncated at {_MAX_READ_BODY_BYTES} bytes. " + "Re-read the remaining lines with a narrower start_line/end_line range.\n" +).encode() +_READ_RANGE_NOTE = ( + f"\nNote: Results truncated to {_MAX_READ_LINES} lines. Please narrow your line range.\n" +).encode() _GROUP_TASKS = {"main_task", "plan_task", "review_filter_task", "memory_compression_task"} _GROUP_CALLS = REPLAY_TOOLS | {"file_read", "code_comment", "task_done", DIAGRAM_TOOL_NAME} _MAX_RESPONSE_CALLS = 128 @@ -84,9 +100,11 @@ class _ReadObservation: path: str revision: str start: int - end: int + requested_end: int | None total: int - content: bytes | None = field(repr=False) + result_digest: bytes | None = field(repr=False) + result_size: int = 0 + truncated: bool = False def _read_observation( @@ -127,50 +145,105 @@ def _read_observation( ) if failure is None or not 1 <= (total := int(failure[1])) < requested_start: raise IncrementalError("native read failure has no deterministic range outcome") - return _ReadObservation(path, revision, requested_start, requested_end or 0, total, None) - header, truncated, source_range, body = response.split("\n", 3) + return _ReadObservation(path, revision, requested_start, requested_end, total, None) + header, truncation, source_range, _ = response.split("\n", 3) total_match = re.fullmatch(rf"File: {re.escape(path)} \(Total lines: ([0-9]{{1,10}})\)", header) range_match = _READ_RANGE.fullmatch(source_range) - if total_match is None or range_match is None or truncated != "IS_TRUNCATED: false": - raise IncrementalError("native read has no complete matching file response") + if ( + total_match is None + or range_match is None + or truncation not in {"IS_TRUNCATED: true", "IS_TRUNCATED: false"} + ): + raise IncrementalError("native read has no matching file response") total = int(total_match[1]) - start, end = map(int, range_match.groups()) - if not 1 <= start == requested_start <= end == min( - total, requested_end or total - ) <= 1_000_000_000 or not body.endswith("\n"): + start, shown_end = map(int, range_match.groups()) + end = min(total, requested_end or total) + if not start == requested_start <= shown_end <= end <= 1_000_000_000: raise IncrementalError("native read response range does not match its inputs") - lines = body[:-1].split("\n") - if len(lines) != end - start + 1: - raise IncrementalError("native read response has incomplete source lines") - contents = [] - for number, line in enumerate(lines, start): - prefix = f"{number}|" - if not line.startswith(prefix): - raise IncrementalError("native read response has invalid line addresses") - contents.append(line.removeprefix(prefix)) - return _ReadObservation(path, revision, start, end, total, _digest(contents)) + raw = response.encode() + if len(raw) > _MAX_READ_BODY_BYTES + _MAX_READ_METADATA_BYTES + len(path): + raise IncrementalError("native read exceeds its result budget") + truncated = truncation == "IS_TRUNCATED: true" + if truncated and not raw.endswith((_READ_LINE_NOTE, _READ_BODY_NOTE, _READ_RANGE_NOTE)): + raise IncrementalError("native read has an unrecognized truncation notice") + return _ReadObservation( + path, + revision, + requested_start, + requested_end, + total, + hashlib.sha256(raw).digest(), + len(raw), + truncated, + ) + + +def _read_line(line: bytes) -> tuple[bytes, bool]: + size = len(line) - int(line.endswith(b"\r")) + if size <= _MAX_READ_LINE_BYTES: + return line[:size], False + cut = _MAX_READ_LINE_BYTES + # The source has already been validated as UTF-8. Back off over continuation bytes. + while (line[cut] & 0xC0) == 0x80: + cut -= 1 + return line[:cut] + f" …[line truncated, {size - cut} more bytes omitted]".encode(), True + + +def _matches_read(observation: _ReadObservation, lines: list[bytes]) -> bool: + if observation.total != len(lines): + return False + if observation.result_digest is None: + return observation.start > len(lines) + + start = observation.start + end = min(observation.requested_end or len(lines), len(lines)) + capped_end = min(end, start + _MAX_READ_LINES - 1) + line_cut = body_cut = False + body = bytearray() + shown_end = start - 1 + for number in range(start, capped_end + 1): + text, cut = _read_line(lines[number - 1]) + row = f"{number}|".encode() + text + b"\n" + size = len(body) + len(row) + if size > _MAX_READ_BODY_BYTES: + body_cut = True + break + # An impossible short trace result cannot drive reconstruction of a larger body. + if size > observation.result_size: + return False + body.extend(row) + shown_end = number + line_cut |= cut + + range_cut = capped_end < end + truncated = "true" if line_cut or body_cut or range_cut else "false" + header = ( + f"File: {observation.path} (Total lines: {observation.total})\n" + f"IS_TRUNCATED: {truncated}\nLINE_RANGE: {start}-{shown_end}\n" + ).encode() + response = bytearray(header) + response.extend(body) + if line_cut: + response.extend(_READ_LINE_NOTE) + if body_cut: + response.extend(_READ_BODY_NOTE) + if range_cut: + response.extend(_READ_RANGE_NOTE) + return ( + len(response) == observation.result_size + and hashlib.sha256(response).digest() == observation.result_digest + ) def _verified_windows(observations: set[_ReadObservation], blob: bytes) -> set[_ReadObservation]: if b"\0" in blob: return set() try: - lines = blob.decode("utf-8").split("\n") if blob else [] + blob.decode("utf-8") except UnicodeError: return set() - return { - observation - for observation in observations - if len(lines) == observation.total - and ( - observation.start > len(lines) - if observation.content is None - else _digest( - [line.removesuffix("\r") for line in lines[observation.start - 1 : observation.end]] - ) - == observation.content - ) - } + lines = blob.split(b"\n") if blob else [] + return {observation for observation in observations if _matches_read(observation, lines)} def _groups(value: object, selected: set[str]) -> dict[str, tuple[str, ...]]: @@ -297,14 +370,14 @@ def _group_record(self, record: dict[str, Any], kind: str) -> None: if kind == "llm_request": group.main_request |= task == "main_task" elif kind == "llm_response": - self._requested_tools(record.get("tool_calls"), group) + self._requested_tools(record.get("tool_calls"), group, task=task) elif kind == "llm_error": group.reasons.add("llm_error") else: self._tool(record, group) @staticmethod - def _requested_tools(value: object, group: _GroupObservation) -> None: + def _requested_tools(value: object, group: _GroupObservation, *, task: str) -> None: """Check model requests that native may reject before recording execution.""" if value is None: @@ -315,6 +388,10 @@ def _requested_tools(value: object, group: _GroupObservation) -> None: for item in value: if not isinstance(item, dict) or not isinstance(name := item.get("name"), str): group.reasons.add("invalid_arguments") + elif name == "approve_all_comments" and task == "review_filter_task": + # Native recognizes this response without dispatching a tool or removing a finding. + if item.get("arguments") != "{}": + group.reasons.add("invalid_arguments") elif name == "code_comment": group.requested_comments += 1 elif name not in _GROUP_CALLS: @@ -376,6 +453,8 @@ def _tool(self, record: dict[str, Any], group: _GroupObservation) -> None: group.reasons.add(reason) else: group.reasons.add("unsupported_tool") + except IncrementalSearchError as exc: + group.reasons.add(exc.reason) except (TypeError, ValueError, RecursionError): if tool == "code_comment" and ok: # An ambiguously authored finding can be filed against a different group. @@ -543,14 +622,18 @@ def all_unqualified(reason: str) -> DependencyAssessment: for key in sorted(candidates): group = candidates[key] rejected = set() - if not group.reads <= verified: - rejected.add("read_verification") + rejected.update( + "read_truncated" if item.truncated else "read_verification" + for item in group.reads - verified + ) replays = tuple( sorted(group.replays, key=lambda item: (item.tool, item.arguments, item.result)) ) for replay in replays: if not replay_verifier.verifies(replay): - rejected.add(_replay_reason(replay.tool)) + rejected.add( + replay_verifier.failure_reason(replay) or _replay_reason(replay.tool) + ) if rejected: reasons.update(rejected) continue diff --git a/src/ocr_toolkit/local_incremental_replay.py b/src/ocr_toolkit/local_incremental_replay.py index 66e593f0..53c4998a 100644 --- a/src/ocr_toolkit/local_incremental_replay.py +++ b/src/ocr_toolkit/local_incremental_replay.py @@ -16,10 +16,15 @@ TOOL_NAME, call_named_tool, ) -from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryObject +from ocr_toolkit.evidence.repository import ( + GitRepositoryReader, + RepositoryEvidenceError, + RepositoryObject, +) from ocr_toolkit.evidence.store import EvidenceStore from ocr_toolkit.local_incremental_state import ( IncrementalError, + IncrementalSearchError, ToolReplay, canonical_json, literal_path, @@ -42,6 +47,7 @@ _MAX_MATCHES = 100 _MAX_RESULT_BYTES = 256 * 1024 _MAX_REPLAY_CALLS = 64 +_SEARCH_CAP_PREFIX = f"Note: Showing the first {_MAX_MATCHES} matches across " def _complete_evidence_result(tool: str, args: dict[str, Any], payload: dict[str, Any]) -> bool: @@ -79,6 +85,8 @@ def _complete_evidence_result(tool: str, args: dict[str, Any], payload: dict[str def _result_digest(tool: str, args: dict[str, Any], result: str) -> str: raw = result.encode() if not raw or len(raw) > _MAX_RESULT_BYTES: + if tool == "code_search" and _capped_search(args, result): + raise IncrementalSearchError("search_capped", "native capped search exceeds its budget") raise IncrementalError("incremental tool result exceeds its replay budget") if tool in _EVIDENCE_TOOLS: payload = unique_json(raw) @@ -91,7 +99,12 @@ def _result_digest(tool: str, args: dict[str, Any], result: str) -> str: def observed_replay(tool: str, args: dict[str, Any], result: str) -> ToolReplay: raw = canonical_json(args) validated_replay_arguments(tool, raw) - return ToolReplay(tool, raw.decode(), _result_digest(tool, args, result)) + return ToolReplay( + tool, + raw.decode(), + _result_digest(tool, args, result), + capped_search=tool == "code_search" and _capped_search(args, result), + ) def _arg_texts(args: dict[str, Any]) -> Iterator[str]: @@ -102,19 +115,25 @@ def _arg_texts(args: dict[str, Any]) -> Iterator[str]: yield from value +def _capped_search(args: dict[str, Any], result: str) -> bool: + if args.get("side") == "old": + return result.startswith("SIDE: old\nREVISION: ") and result.split("\n", 2)[-1].startswith( + _SEARCH_CAP_PREFIX + ) + return result.startswith(_SEARCH_CAP_PREFIX) + + def _render_search(raw: bytes, revision: str) -> str: if not raw: return "No matches found" - if len(raw) > _MAX_RESULT_BYTES or not raw.endswith(b"\n"): - raise IncrementalError("native search output is incomplete or exceeds its budget") + if not raw.endswith(b"\n"): + raise IncrementalError("native search output is incomplete") prefix = f"{revision}:".encode() - rows = raw[:-1].split(b"\n", _MAX_MATCHES) - if len(rows) > _MAX_MATCHES: - raise IncrementalError("native search exceeds the complete match limit") + rows = raw[:-1].split(b"\n") matches: dict[str, list[str]] = {} - for row in rows: + for index, row in enumerate(rows): name, number, value = row.split(b"\0", 2) - path, text = name.removeprefix(prefix).decode(), value.decode() + path = name.removeprefix(prefix).decode() if ( not name.startswith(prefix) or not literal_path(path) @@ -122,10 +141,19 @@ def _render_search(raw: bytes, revision: str) -> str: or b"\0" in value ): raise IncrementalError("native search match is ambiguous") - matches.setdefault(path, []).append(f"{int(number)}|{text}\n") - return "".join( + lines = matches.setdefault(path, []) + if index < _MAX_MATCHES: + lines.append(f"{int(number)}|{value.decode()}\n") + note = "" + if len(rows) > _MAX_MATCHES: + note = ( + f"{_SEARCH_CAP_PREFIX}{len(matches)} matching files. Some files are partially shown " + "or omitted entirely. Narrow file_patterns to see the rest.\n" + ) + return note + "".join( f"File: {path}\nMatch lines: {len(lines)}\n{''.join(lines)}\n" for path, lines in matches.items() + if lines ) @@ -181,6 +209,7 @@ class ReplayVerifier: authorize_text: Callable[[str], bool] trees: dict[str, tuple[RepositoryObject, ...]] = field(default_factory=dict) _observed: dict[tuple[str, str], str | None] = field(default_factory=dict) + _failures: dict[tuple[str, str], str | None] = field(default_factory=dict) _diffs: dict[str, str] | None = None def verifies(self, replay: ToolReplay) -> bool: @@ -192,13 +221,27 @@ def verifies(self, replay: ToolReplay) -> bool: try: args = validated_replay_arguments(replay.tool, replay.arguments.encode()) if all(self.authorize_text(value) for value in _arg_texts(args)): + self._failures[key] = None self._observed[key] = _result_digest( replay.tool, args, self._execute(replay.tool, args) ) + except IncrementalSearchError as exc: + self._failures[key] = exc.reason except (ValueError, OSError, TimeoutExpired, RecursionError): pass return self._observed[key] == replay.result + def failure_reason(self, replay: ToolReplay) -> str | None: + """Explain a failed search comparison without including its inputs or output.""" + + key = (replay.tool, replay.arguments) + if self._observed.get(key) == replay.result: + return None + reason = self._failures.get(key) + if reason is None and replay.capped_search and key in self._failures: + return "search_capped" + return reason + def _tree(self, revision: str) -> tuple[RepositoryObject, ...]: if revision not in self.trees: self.trees[revision] = self.reader.list_objects(revision, local_only=True) @@ -245,13 +288,20 @@ def _execute(self, tool: str, args: dict[str, Any]) -> str: else: if any(entry.is_submodule for entry in tree): raise IncrementalError("native search scope may follow Git submodules") - result = _render_search( - self.reader.grep_tree( + regex = args.get("use_perl_regexp", False) + try: + raw_matches = self.reader.grep_tree( revision, args["search_text"], tuple(args.get("file_patterns", ())), case_sensitive=args.get("case_sensitive", False), - ), - revision, - ) + use_perl_regexp=regex, + ) + except (RepositoryEvidenceError, TimeoutExpired) as exc: + if regex: + raise IncrementalSearchError( + "search_regex", "native search regex could not be replayed completely" + ) from exc + raise + result = _render_search(raw_matches, revision) return f"SIDE: old\nREVISION: {revision}\n{result}" if old else result diff --git a/src/ocr_toolkit/local_incremental_state.py b/src/ocr_toolkit/local_incremental_state.py index d2285b87..6d9649b8 100644 --- a/src/ocr_toolkit/local_incremental_state.py +++ b/src/ocr_toolkit/local_incremental_state.py @@ -90,6 +90,14 @@ class IncrementalError(ValueError): """Incremental review inputs or coverage could not be proved.""" +class IncrementalSearchError(IncrementalError): + """Carry a bounded diagnostic for an unverified native search.""" + + def __init__(self, reason: str, message: str) -> None: + super().__init__(message) + self.reason = reason + + @dataclass(frozen=True, slots=True) class ToolReplay: """Hold bounded admitted arguments and the digest of the witnessed result.""" @@ -97,6 +105,7 @@ class ToolReplay: tool: str arguments: str = field(repr=False) result: str + capped_search: bool = field(default=False, compare=False, repr=False) def payload(self) -> dict[str, str]: return {"tool": self.tool, "arguments": self.arguments, "result": self.result} @@ -173,6 +182,17 @@ def _query_text(value: object) -> bool: ) +def _search_pathspec(value: object) -> bool: + if not isinstance(value, str) or len(value) > 256: + return False + pattern = value.removeprefix(":(exclude)") + return ( + _SEARCH_PATTERN.fullmatch(pattern) is not None + and not pattern.startswith("/") + and ".." not in pattern.split("/") + ) + + def validated_replay_arguments(tool: str, raw: bytes) -> dict[str, Any]: """Revalidate the closed argument families before any repository or MCP read.""" @@ -197,24 +217,27 @@ def validated_replay_arguments(tool: str, raw: bytes) -> dict[str, Any]: search = tool == "code_search" key = "search_text" if search else "query_name" options = {"file_patterns", "use_perl_regexp"} if search else set() - patterns = args.get("file_patterns", []) valid = ( args.keys() <= {"side", "case_sensitive", key} | options and _query_text(args.get(key)) and (search or args[key].isascii()) and args.get("side", "new") in ("old", "new") and type(args.get("case_sensitive", False)) is bool - and args.get("use_perl_regexp", False) is False - and isinstance(patterns, list) - and len(patterns) <= 16 - and all( - isinstance(pattern, str) - and _SEARCH_PATTERN.fullmatch(pattern) - and not pattern.startswith("/") - and ".." not in pattern.split("/") - for pattern in patterns - ) ) + if valid and search: + patterns = args.get("file_patterns", []) + if not ( + isinstance(patterns, list) + and len(patterns) <= 16 + and all(_search_pathspec(pattern) for pattern in patterns) + ): + raise IncrementalSearchError( + "search_pathspec", "incremental search pathspec is unsupported" + ) + if type(args.get("use_perl_regexp", False)) is not bool: + raise IncrementalSearchError( + "search_regex", "incremental search regex mode must be a boolean" + ) else: valid = ( args.keys() <= _EVIDENCE_REPLAY_FIELDS[tool] diff --git a/src/ocr_toolkit/posting/workflow.py b/src/ocr_toolkit/posting/workflow.py index 237dfd75..6e9ac8da 100644 --- a/src/ocr_toolkit/posting/workflow.py +++ b/src/ocr_toolkit/posting/workflow.py @@ -12,6 +12,7 @@ from collections.abc import Callable from dataclasses import replace from pathlib import Path +from tempfile import TemporaryDirectory from typing import Any from ocr_toolkit import review_analysis @@ -1011,33 +1012,39 @@ def verified_review_coverage( if identity.diff_base_sha is None: raise RepositoryEvidenceError("ordinary review has no original diff identity") - reader = GitRepositoryReader(Path.cwd()) + reader = GitRepositoryReader(Path.cwd(), local_only=True) plan = plan_review_input(reader, identity.diff_base_sha, identity.source_sha) if plan.changes: raise RepositoryEvidenceError("ordinary review receipt contains a changed gitlink") - projection = make_gitlink_projection(reader, plan) - metadata = result.get(TOOLKIT_RESULT_KEY) - publication = metadata.get("publication") if isinstance(metadata, dict) else None - filtered = isinstance(publication, dict) and publication.get("state") == "publication-filtered" - has_selection_proof = TOOLKIT_REVIEW_SELECTION_KEY in result - if filtered or has_selection_proof: - selection = selection_from_review_proof(projection, result) - else: - selection = selection_from_manifest(projection, result) - if ( - not filtered - and qualify_review_manifest(projection, selection, result) != has_selection_proof - ): - raise RepositoryEvidenceError("OCR ordinary selection proof is unexpected") try: - actual = coverage_from_selection(projection, selection) - claimed = parse_review_coverage(metadata["review_coverage"]) - except (KeyError, TypeError, ReviewCoverageError) as exc: - raise RepositoryEvidenceError("ordinary review coverage is invalid") from exc - if claimed != actual: - raise RepositoryEvidenceError("ordinary review coverage disagrees with Git and OCR") - verify_gitlink_projection(reader, projection) - return actual + with TemporaryDirectory(prefix="ocr-post-git-view-") as home: + projection = make_gitlink_projection(reader, plan, ordinary_config_home=Path(home)) + metadata = result.get(TOOLKIT_RESULT_KEY) + publication = metadata.get("publication") if isinstance(metadata, dict) else None + filtered = ( + isinstance(publication, dict) and publication.get("state") == "publication-filtered" + ) + has_selection_proof = TOOLKIT_REVIEW_SELECTION_KEY in result + if filtered or has_selection_proof: + selection = selection_from_review_proof(projection, result) + else: + selection = selection_from_manifest(projection, result) + if ( + not filtered + and qualify_review_manifest(projection, selection, result) != has_selection_proof + ): + raise RepositoryEvidenceError("OCR ordinary selection proof is unexpected") + try: + actual = coverage_from_selection(projection, selection) + claimed = parse_review_coverage(metadata["review_coverage"]) + except (KeyError, TypeError, ReviewCoverageError) as exc: + raise RepositoryEvidenceError("ordinary review coverage is invalid") from exc + if claimed != actual: + raise RepositoryEvidenceError("ordinary review coverage disagrees with Git and OCR") + verify_gitlink_projection(reader, projection) + return actual + except OSError as exc: + raise RepositoryEvidenceError("OCR ordinary Git review inputs are unavailable") from exc def verified_no_model_repository_coverage(status: PreExecutionStatus) -> RepositoryCoverage: diff --git a/src/ocr_toolkit/reporting/incremental.py b/src/ocr_toolkit/reporting/incremental.py index f44c6ba4..bff09eb1 100644 --- a/src/ocr_toolkit/reporting/incremental.py +++ b/src/ocr_toolkit/reporting/incremental.py @@ -23,7 +23,11 @@ "native_counters", "native_trace", "no_evidence_summary", + "read_truncated", "read_verification", + "search_capped", + "search_pathspec", + "search_regex", "search_tool", "unsupported_tool", } diff --git a/src/ocr_toolkit/review_runner.py b/src/ocr_toolkit/review_runner.py index a29fd32e..8dbe712d 100644 --- a/src/ocr_toolkit/review_runner.py +++ b/src/ocr_toolkit/review_runner.py @@ -99,6 +99,7 @@ from ocr_toolkit.evidence.collect import collect_repository_evidence from ocr_toolkit.evidence.gitlink_projection import ( GitlinkProjection, + GitProjectionConfigError, PreviewExclusion, RawDiffEntry, ReviewSelection, @@ -1945,7 +1946,7 @@ def _verify_projection_after_execution(result_path: Path, projection: GitlinkPro """Reject review-input drift before any publication DLP work.""" try: - verify_gitlink_projection(GitRepositoryReader(Path.cwd()), projection) + verify_gitlink_projection(GitRepositoryReader(Path.cwd(), local_only=True), projection) except (RepositoryEvidenceError, OSError, subprocess.TimeoutExpired) as exc: _discard_unadmitted_result(result_path) raise ReviewRunnerError("OCR review inputs drifted during model execution") from exc @@ -2786,7 +2787,7 @@ def _run_background_qualified_review( ) return 2, qualification try: - verify_gitlink_projection(GitRepositoryReader(Path.cwd()), projection) + verify_gitlink_projection(GitRepositoryReader(Path.cwd(), local_only=True), projection) except (RepositoryEvidenceError, OSError, subprocess.TimeoutExpired) as exc: raise ReviewRunnerError("OCR review inputs drifted before model execution") from exc if state is not None: @@ -4218,7 +4219,7 @@ def _run_evidence_review( gitlink_detected = False review_plan = None try: - reader = GitRepositoryReader(Path.cwd()) + reader = GitRepositoryReader(Path.cwd(), local_only=True) plan_input = plan_gitlink_input if state.local else plan_review_input review_plan = plan_input(reader, refs.base, refs.head) if review_plan is not None and review_plan.changes: @@ -4234,7 +4235,11 @@ def _run_evidence_review( else: gitlink_detected = True elif review_plan is not None: - projection = make_gitlink_projection(reader, review_plan) + projection = make_gitlink_projection( + reader, + review_plan, + ordinary_config_home=session_home if not state.local else None, + ) except RepositoryEvidenceError as exc: if review_plan is not None and review_plan.changes: gitlink_detected = True @@ -4244,7 +4249,10 @@ def _run_evidence_review( except RepositoryEvidenceError: pass if not gitlink_detected: - raise ReviewRunnerError("immutable review coverage could not be qualified") from exc + reason = "immutable review coverage could not be qualified" + if isinstance(exc, GitProjectionConfigError): + reason += f": {exc}" + raise ReviewRunnerError(reason) from exc print( "OCR gitlink qualification: immutable changed pointer is outside the " "qualified subset; model review did not run", @@ -4408,6 +4416,13 @@ def _run_evidence_review( state.debug.capture("diagram.json", artifacts.diagram) if not state.analysis.enabled: state.debug.capture_native_trace() + if ( + (exit_code == 0 or partial) + and projection is not None + and projection.git_view_digest is not None + ): + # Check the model's isolated Git inputs before removing their private home. + _verify_projection_after_execution(result_path, projection) finally: try: try: @@ -4437,7 +4452,7 @@ def _run_evidence_review( forbidden += enrichment.forbidden_sources or tuple( ForbiddenValue(v, "other") for v in enrichment.forbidden_publication ) - if projection is not None: + if projection is not None and projection.git_view_digest is None: _verify_projection_after_execution(result_path, projection) usage, publication_filtered, publication = _finalize_ocr_result( result_path, diff --git a/tests/test_evidence_collectors.py b/tests/test_evidence_collectors.py index b0c1bdb6..8cb81e87 100644 --- a/tests/test_evidence_collectors.py +++ b/tests/test_evidence_collectors.py @@ -1133,6 +1133,46 @@ def test_changed_head_guidance_cannot_self_authorize_policy(tmp_path: Path) -> N assert not head_records +def test_collection_reads_each_immutable_tree_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _git(tmp_path, "init", "-q") + _git(tmp_path, "config", "user.email", "agent@example.invalid") + _git(tmp_path, "config", "user.name", "Synthetic Agent") + manifest = tmp_path / "package.json" + (tmp_path / "AGENTS.md").write_text("Review security carefully.\n", encoding="utf-8") + manifest.write_text('{"dependencies": {"example": "1.0.0"}}\n', encoding="utf-8") + _git(tmp_path, "add", ".") + _git(tmp_path, "commit", "-qm", "base") + base = _git(tmp_path, "rev-parse", "HEAD") + manifest.write_text('{"dependencies": {"example": "2.0.0"}}\n', encoding="utf-8") + _git(tmp_path, "commit", "-qam", "head") + head = _git(tmp_path, "rev-parse", "HEAD") + _git(tmp_path, "checkout", "-q", "--detach", base) + manifest.write_text('{"dependencies": {"example": "3.0.0"}}\n', encoding="utf-8") + _git(tmp_path, "commit", "-qam", "actual target") + target = _git(tmp_path, "rev-parse", "HEAD") + + list_objects = GitRepositoryReader.list_objects + scans = [] + + def count_tree(reader: GitRepositoryReader, ref: str) -> tuple[RepositoryObject, ...]: + scans.append(ref) + return list_objects(reader, ref) + + monkeypatch.setattr(GitRepositoryReader, "list_objects", count_tree) + store = collect_repository_evidence( + tmp_path, base_ref=base, head_ref=head, policy_ref=base, target_ref=target + ) + + assert scans == [base, head, target] + assert store.policy is not None + assert any(record.source_path == "AGENTS.md" for record in store.policy.records) + assert store.target is not None + assert store.target.commit_sha == target + assert any(record.kind == "dependency.declared" for record in store.target.records) + + def test_source_guidance_content_is_not_read(tmp_path: Path) -> None: """Never include source guidance in the bounded blob read queue.""" diff --git a/tests/test_gitlinks.py b/tests/test_gitlinks.py index ceb8c1ef..75094b6c 100644 --- a/tests/test_gitlinks.py +++ b/tests/test_gitlinks.py @@ -30,13 +30,20 @@ ) from ocr_toolkit.evidence.gitlinks import changed_gitlinks, plan_gitlink_input, plan_review_input from ocr_toolkit.evidence.repository import GitRepositoryReader, RepositoryEvidenceError -from ocr_toolkit.ocr_result import TOOLKIT_RESULT_KEY, TOOLKIT_REVIEW_SELECTION_KEY +from ocr_toolkit.ocr_result import ( + TOOLKIT_RESULT_KEY, + TOOLKIT_RESULT_SCHEMA_VERSION, + TOOLKIT_REVIEW_SELECTION_KEY, +) +from ocr_toolkit.posting.workflow import verified_review_coverage from ocr_toolkit.pre_execution import ( GITLINK_PROJECTION_UNQUALIFIED, GITLINK_STATUS_SCHEMA, read_pre_execution_status, ) from ocr_toolkit.preflight import RECOMMENDED_OCR_VERSION, SUPPORTED_OCR_VERSIONS +from ocr_toolkit.review_coverage import coverage_from_selection +from ocr_toolkit.review_receipt import ReceiptReviewIdentity OLD_OID = "1" * 40 NEW_OID = "2" * 40 @@ -141,6 +148,21 @@ def _ordinary_exclusion_fixture(root: Path) -> tuple[str, str]: return base, _git(root, "rev-parse", "HEAD") +def _include_runner_config(root: Path) -> Path: + directory = root.with_name(root.name + ".tmp") + directory.mkdir() + runner_config = directory / ".gitlab-runner.ext.conf" + runner_config.write_text( + '[credential "https://gitlab.example.invalid"]\n' + "\thelper = store\n" + '[url "https://job-token@example.invalid/"]\n' + "\tinsteadOf = https://gitlab.example.invalid/\n", + encoding="utf-8", + ) + _git(root, "config", "include.path", str(runner_config)) + return runner_config + + @pytest.mark.parametrize("kind", ["added", "updated", "deleted"]) def test_changed_gitlinks_use_immutable_tree_modes_with_ordinary_file( tmp_path: Path, kind: str @@ -907,8 +929,66 @@ def test_projection_rejects_local_git_config_include(tmp_path: Path) -> None: plan = plan_gitlink_input(reader, base, head) assert plan is not None _git(tmp_path, "config", "include.path", "/tmp/unused-config") + home = tmp_path / "private" + home.mkdir(mode=0o700) with pytest.raises(RepositoryEvidenceError, match="includes"): + make_gitlink_projection(reader, plan, ordinary_config_home=home) + assert not list(home.iterdir()) + + +def test_ordinary_gitlab_projection_isolates_runner_include(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + base, head = _ordinary_exclusion_fixture(root) + _git(root, "config", "core.ignoreCase", "true") + reader = GitRepositoryReader(root, local_only=True) + plan = plan_review_input(reader, base, head) + original = make_gitlink_projection(reader, plan) + runner_config = _include_runner_config(root) + home = tmp_path / "private" + home.mkdir(mode=0o700) + directory = root / ".git" + config = (directory / "config").read_bytes() + index = (directory / "index").read_bytes() + + with pytest.raises(RepositoryEvidenceError, match="includes are unsupported"): make_gitlink_projection(reader, plan) + projection = make_gitlink_projection(reader, plan, ordinary_config_home=home) + + assert projection.original_diff == original.original_diff + assert projection.fingerprints == original.fingerprints + assert projection.line_counts == original.line_counts + env = projection.child_environment() + assert env["GIT_OBJECT_DIRECTORY"] == str(directory / "objects") + assert env["GIT_WORK_TREE"] == str(root) + sanitized = Path(env["GIT_DIR"]) / "config" + assert b"ignoreCase = true" in sanitized.read_bytes() + assert b"credential" not in sanitized.read_bytes() and b"include" not in sanitized.read_bytes() + assert b"job-token" not in sanitized.read_bytes() + assert (directory / "config").read_bytes() == config + assert (directory / "index").read_bytes() == index + + # Runner may remove the external include after checkout. The file is not + # a Git input to the isolated projection. + runner_config.unlink() + verify_gitlink_projection(reader, projection) + sanitized.write_text("[core]\n\tbare = false\n", encoding="utf-8") + with pytest.raises(RepositoryEvidenceError, match="isolated Git config changed"): + verify_gitlink_projection(reader, projection) + + +def test_ordinary_gitlab_projection_rejects_conditional_include(tmp_path: Path) -> None: + root = tmp_path / "repo" + root.mkdir() + base, head = _ordinary_exclusion_fixture(root) + reader = GitRepositoryReader(root, local_only=True) + plan = plan_review_input(reader, base, head) + home = tmp_path / "private" + home.mkdir(mode=0o700) + _git(root, "config", "includeIf.onbranch:*.path", "/unused/synthetic-config") + with pytest.raises(RepositoryEvidenceError, match="includes are unsupported"): + make_gitlink_projection(reader, plan, ordinary_config_home=home) + assert not list(home.iterdir()) def test_projection_rejects_bom_prefixed_local_git_config_include(tmp_path: Path) -> None: @@ -1339,6 +1419,7 @@ def test_installed_ocr_gitlink_preview_qualification( "excluded-rename", "move", "ordinary", + "ordinary-runner", "ordinary-quoted", "ordinary-non-utf8", ], @@ -1359,15 +1440,20 @@ def test_installed_ocr_projected_review_matches_native_manifest( "excluded-rename": _mixed_fixture, "move": _move_fixture, "ordinary": _ordinary_exclusion_fixture, + "ordinary-runner": _ordinary_exclusion_fixture, "ordinary-quoted": _ordinary_quoted_fixture, "ordinary-non-utf8": _ordinary_non_utf8_fixture, } base, head = fixtures[kind](repo) if kind in fixtures else _fixture(repo, kind) - reader = GitRepositoryReader(repo) - plan = plan_review_input(reader, base, head) - projection = make_gitlink_projection(reader, plan) home = tmp_path / "ocr-home" home.mkdir(mode=0o700) + if kind == "ordinary-runner": + _include_runner_config(repo) + reader = GitRepositoryReader(repo) + plan = plan_review_input(reader, base, head) + projection = make_gitlink_projection( + reader, plan, ordinary_config_home=home if kind == "ordinary-runner" else None + ) env = projection.child_environment() env["HOME"] = str(home) args = [ @@ -1397,7 +1483,8 @@ def test_installed_ocr_projected_review_matches_native_manifest( timeout=30, ) assert preview.returncode == 0 and preview.stderr == b"" - if kind == "ordinary" and version == "1.14.5": + has_gitignore = kind in {"ordinary", "ordinary-runner"} + if has_gitignore and version == "1.14.5": # This qualified binary omits tracked gitignored files from preview. assert {entry.path for entry in projection.ordinary_diff} == {"hidden.py", "selected.py"} assert [item["path"] for item in json.loads(preview.stdout)["files"]] == ["selected.py"] @@ -1410,7 +1497,7 @@ def test_installed_ocr_projected_review_matches_native_manifest( assert all(entry.status != "D" for entry in selected) if kind in {"added", "updated", "deleted"}: assert selected == projection.ordinary_diff - elif kind == "ordinary": + elif has_gitignore: assert [entry.path for entry in selected] == ["selected.py"] assert [(item.entry.path, item.reason) for item in selection.excluded] == [ ("hidden.py", "gitignore") @@ -1446,9 +1533,31 @@ def finish_review(_request): ) assert production.returncode == 0 and production.stderr == b"" payload = json.loads(production.stdout) - qualify_review_manifest( - projection, selection, payload, require_fresh_complete=kind != "ordinary" + uses_proof = qualify_review_manifest( + projection, selection, payload, require_fresh_complete=not has_gitignore ) + if kind == "ordinary-runner": + assert uses_proof + expected = coverage_from_selection(projection, selection) + payload[TOOLKIT_RESULT_KEY] = { + "review_coverage": expected.payload(), + "publication": {"state": "passed"}, + } + payload[TOOLKIT_REVIEW_SELECTION_KEY] = review_selection_proof(projection, selection) + identity = ReceiptReviewIdentity( + source_sha=head, + target_sha=base, + target_protection="protected", + mr_author_id=42, + schema_version=TOOLKIT_RESULT_SCHEMA_VERSION, + policy_sha=base, + diff_base_sha=base, + ) + monkeypatch.chdir(repo) + assert verified_review_coverage(payload, identity) == expected + del payload[TOOLKIT_REVIEW_SELECTION_KEY] + with pytest.raises(RepositoryEvidenceError, match="omitted"): + verified_review_coverage(payload, identity) if kind == "excluded-rename": (renamed,) = ( record diff --git a/tests/test_local_incremental.py b/tests/test_local_incremental.py index 99cf5166..4fc5d3f8 100644 --- a/tests/test_local_incremental.py +++ b/tests/test_local_incremental.py @@ -62,7 +62,7 @@ def _fixture(tmp_path, environment): return root, base, head, paths, changed -def _mixed_fixture(tmp_path, environment): +def _mixed_fixture(tmp_path, environment, *, bounded_tools=False): compat = load_script() paths = [f"file_{index:02}.{'md' if index % 2 else 'json'}" for index in range(23)] texts = { @@ -75,7 +75,14 @@ def _mixed_fixture(tmp_path, environment): } texts[paths[7]] += f"See [configuration]({paths[6]}).\n" texts[paths[9]] += f"The setting is `{Path(paths[6]).stem}_state`.\n" + if bounded_tools: + appendix = "\n## Appendix\n" + "x" * 2045 + "🧪beyond\n" + appendix += "Example marker\n" * 128 + "\n" * 400 + "End of appendix.\n" + texts[paths[1]] += appendix + texts[paths[3]] += appendix initial = {path: text.replace("ready", "waiting") for path, text in texts.items()} + if bounded_tools: + initial[paths[1]] = initial[paths[1]].replace("End of appendix.", "End of examples.") first, *others = paths root, base, _ = compat.execution._synthetic_repo( tmp_path, @@ -968,6 +975,21 @@ def test_native_incremental_reuses_21_markdown_and_json_files_after_unchanged_se ) +def test_native_incremental_reuses_bounded_markdown_results_and_rechecks_invalidated_groups( + tmp_path, monkeypatch, qualified_native_ocr, capsys +): + _native_incremental_case( + tmp_path, + monkeypatch, + qualified_native_ocr, + capsys, + "flag", + False, + mixed=True, + bounded_tools=True, + ) + + @pytest.mark.parametrize( ("tool", "arguments", "result"), ( @@ -1057,6 +1079,7 @@ def _native_incremental_case( mixed=False, diagnostics_only=False, advanced=False, + bounded_tools=False, ): qualifying_candidate = bool(os.environ.get("OCR_QUALIFY_CANDIDATE")) binary, _ = qualified_native_ocr( @@ -1077,7 +1100,9 @@ def _native_incremental_case( monkeypatch.setenv("GIT_NO_LAZY_FETCH", "1") if mixed: - root, base, first, paths, texts = _mixed_fixture(tmp_path, environment) + root, base, first, paths, texts = _mixed_fixture( + tmp_path, environment, bounded_tools=bounded_tools + ) rule = root / ".opencodereview" / "rule.json" rule.parent.mkdir(exist_ok=True) rule.write_text('{"include":["*.md"]}') @@ -1095,6 +1120,9 @@ def _native_incremental_case( confirmed_search: set[str] = set() search_text = "Release notes" if mixed else "missing_synthetic_symbol" operator_token = "roverJune" + unqualified_reasons = ( + "Unqualified groups by reason: search_pathspec 15, search_tool 1, unsupported_tool 1." + ) evidence_path = paths[10] advanced_calls = { paths[6]: ("file_find", {"query_name": paths[10]}), @@ -1106,6 +1134,40 @@ def _native_incremental_case( {"action": "list", "kind": "repository.file", "ref": "base", "page_size": 50}, ), } + bounded_read, bounded_search, changed_read, changed_search = ( + paths[3], + paths[5], + paths[11], + paths[13], + ) + bounded_calls = { + bounded_read: ( + ("file_read", {"file_path": bounded_read, "start_line": 4, "end_line": 540}), + ), + bounded_search: ( + ("code_search", {"search_text": "Example marker", "file_patterns": [bounded_read]}), + ( + "code_search", + { + "search_text": "Example (marker|sample)", + "use_perl_regexp": True, + "file_patterns": ["*.md", f":(exclude){paths[1]}"], + }, + ), + ), + changed_read: (("file_read", {"file_path": paths[1], "start_line": 4, "end_line": 540}),), + changed_search: ( + ( + "code_search", + { + "search_text": "Example state is (ready|active)", + "use_perl_regexp": True, + "file_patterns": [paths[1]], + }, + ), + ), + } + bounded_responses: dict[str, tuple[str, ...]] = {} diagram_on = False diagram_owner = paths[0] confirmed_diagram: set[str] = set() @@ -1118,6 +1180,10 @@ def _native_incremental_case( updated_anchors = { path: text.replace("ready", "active") for path, text in comment_anchors.items() } + if bounded_tools: + edited_texts[paths[1]] = edited_texts[paths[1]].replace( + "End of appendix.", "End of material." + ) else: edited_texts = { path: text.replace("return 2 +", "return 3 +") for path, text in texts.items() @@ -1221,10 +1287,15 @@ def tool_script(request): "ocr_toolkit_evidence", {"action": "get", "id": page["records"][0]["id"]}, ) + elif bounded_tools and path in bounded_calls and len(names) <= len(bounded_calls[path]): + name, arguments = bounded_calls[path][len(names) - 1] elif "code_comment" not in names: rendered = [ message.get("content", "") for message in messages if message.get("role") == "tool" ] + if bounded_tools and path in bounded_calls: + with lock: + bounded_responses[path] = tuple(rendered[1:]) if DIAGRAM_TOOL_NAME in names and any( '"received"' in response for response in rendered ): @@ -1292,6 +1363,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): ) seen.clear() switches = ["--incremental"] if incremental else [] + native_flags = [] if bounded_tools else ["--no-filter"] if analysis: switches += ["--analysis-max-tokens-budget", "2"] if analysis_input == "flag": @@ -1319,7 +1391,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): head, "--concurrency", "2", - "--no-filter", + *native_flags, ] ) captured = capsys.readouterr() @@ -1334,10 +1406,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): assert "toolkit_incremental" in payload, captured.err if diagnostics_only: assert "Incremental baseline: 17 groups, 0 qualified." in captured.err - assert ( - "Unqualified groups by reason: search_tool 16, unsupported_tool 1." - in captured.err - ) + assert unqualified_reasons in captured.err assert all( value not in captured.err for value in ( @@ -1372,10 +1441,7 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): == baseline["toolkit_incremental"]["baseline_groups"] ) assert not any(file.scope for file in cache.files.values()) - assert ( - "Unqualified groups by reason: search_tool 16, unsupported_tool 1." - in baseline_report - ) + assert unqualified_reasons in baseline_report private_state = baseline_path.read_text() assert all( value not in private_state + baseline_report @@ -1410,6 +1476,28 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): else: assert {item.tool for item in scope.replays} == {tool} assert len(scope.replays) == (2 if path == evidence_path else 1) + if bounded_tools: + assert cache.baseline_groups is not None + assert not cache.baseline_groups.reasons, (cache.baseline_groups, baseline_report) + assert compat.peer._StubHandler.request_stages.count("filter") == len(paths) + assert "approve_all_comments" not in baseline["tool_calls"]["by_tool"] + assert set(bounded_responses) == set(bounded_calls) + for path, target in ((bounded_read, bounded_read), (changed_read, paths[1])): + (output,) = bounded_responses[path] + assert "IS_TRUNCATED: true\nLINE_RANGE: 4-503" in output + assert "10 more bytes omitted" in output and "🧪" not in output + scope = cache.files[path].scope + assert scope is not None and scope.head_paths == (dependency_path(target),) + for output in bounded_responses[bounded_search]: + assert "Showing the first 100 matches across 1 matching files" in output + for path, replays in ((bounded_search, 2), (changed_search, 1)): + scope = cache.files[path].scope + assert scope is not None and len(scope.replays) == replays + prior_read, prior_search = ( + bounded_responses[changed_read], + bounded_responses[changed_search], + ) + bounded_responses.clear() old_run = baseline["manifest"]["run_id"] changed_now.update(paths[1:3] if diagram else paths[:2]) corrupted_path = paths[-1] @@ -1439,6 +1527,16 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): ) if diagram: expected_fresh.add(diagram_owner) + if bounded_tools: + expected_fresh.update({changed_read, changed_search}) + assert compat.peer._StubHandler.request_stages.count("filter") == ( + len(paths) + len(expected_fresh) + ) + assert set(bounded_responses) == {changed_read, changed_search}, narrowed[ + "toolkit_incremental" + ] + assert bounded_responses[changed_read] == prior_read + assert bounded_responses[changed_search] != prior_search if ( qualifying_candidate and narrowed["status"] == "complete" @@ -1479,6 +1577,9 @@ def run(label, head, *, incremental=True, analysis=False, expected_exit=0): if diagram: assert "```mermaid" not in markdown return + if bounded_tools: + assert {bounded_read, bounded_search} <= {item["path"] for item in carry["reused"]} + return if mixed: assert carry["reused_count"] == 21 groups = {cache.files[item["path"]].scope.members for item in carry["reused"]} diff --git a/tests/test_local_incremental_reads.py b/tests/test_local_incremental_reads.py new file mode 100644 index 00000000..952fa614 --- /dev/null +++ b/tests/test_local_incremental_reads.py @@ -0,0 +1,154 @@ +"""Verify exact native read observations against bounded immutable Git content.""" + +import json +from time import monotonic + +from ocr_toolkit.evidence.repository import GitRepositoryReader +from ocr_toolkit.evidence.text_contracts import MAX_SOURCE_BYTES +from ocr_toolkit.local_incremental_dependencies import ( + NativeDependencies, + _read_observation, + _verified_windows, +) +from ocr_toolkit.review_range import ReviewRange +from tests.test_ocr_compat import load_script + +_UTF8_NOTICE = ( + "\nNote: Lines longer than 2048 bytes were cut mid-line and the omitted bytes are not part " + "of this result. Reason about the visible part only.\n" +) + + +def test_truncated_read_requires_exact_visible_source_and_omission_count(): + review_range = ReviewRange("1" * 40, "2" * 40) + args = {"file_path": "example.txt"} + content = "x" * 2045 + source = (content + "🧪beyond\r\n").encode() + result = ( + "File: example.txt (Total lines: 2)\nIS_TRUNCATED: true\nLINE_RANGE: 1-2\n" + f"1|{content} …[line truncated, 10 more bytes omitted]\n2|\n{_UTF8_NOTICE}" + ) + valid = _read_observation(args, result, review_range, ok=True) + wrong_count = _read_observation( + args, result.replace("10 more", "11 more"), review_range, ok=True + ) + wrong_visible_source = _read_observation( + args, result.replace("1|x", "1|y"), review_range, ok=True + ) + wrong_range = _read_observation( + args, result.replace("LINE_RANGE: 1-2", "LINE_RANGE: 1-1"), review_range, ok=True + ) + assert valid.truncated and valid.revision == review_range.head + assert _verified_windows({valid, wrong_count, wrong_visible_source, wrong_range}, source) == { + valid + } + assert not _verified_windows({valid}, source.replace(b"beyond", b"beyon\0")) + assert not _verified_windows({valid}, source.replace(b"beyond", b"beyon\xff")) + + +def _read_body_at_size(total): + rows = ["a" * 2040] * 128 + current = sum(len(f"{number}|{line}\n") for number, line in enumerate(rows, 1)) + return "\n".join([*rows, "b" * (total - current - len("129|\n"))]) + + +def test_qualified_native_read_limits_match_immutable_git(tmp_path, qualified_native_ocr): + binary, _ = qualified_native_ocr( + "OCR_FEDERATION_QUALIFY_BINARY", handoff="local_review_incremental" + ) + compat = load_script() + home = tmp_path / "home" + environment = compat.execution._isolated_probe_environment(home) + tail = "x" * 2040 + "🧪beyond\r\n" + root, base, head = compat.execution._synthetic_repo( + tmp_path, + environment, + baseline="BASE " + tail, + changed="HEAD " + tail, + context_files={ + "lines.txt": "\n".join(f"line{number}" for number in range(1, 502)), + "exact.txt": _read_body_at_size(262_144), + "over.txt": _read_body_at_size(262_145), + "combined.txt": "a" * 10 + _read_body_at_size(262_145) + "\n" * 400, + }, + ) + cases = [ + ({"file_path": "lines.txt"}, "true", "1-500", "Results truncated to 500 lines."), + ( + {"file_path": "lines.txt", "start_line": 2, "end_line": 501}, + "false", + "2-501", + "501|line501\n", + ), + ( + {"file_path": "example.py", "start_line": 1, "end_line": 1, "side": "old"}, + "true", + "1-1", + "1|BASE ", + ), + ({"file_path": "example.py", "end_line": 1, "side": "new"}, "true", "1-1", "1|HEAD "), + ({"file_path": "exact.txt"}, "false", "1-129", "129|b"), + ({"file_path": "over.txt"}, "true", "1-128", "Output truncated at 262144 bytes."), + ({"file_path": "combined.txt"}, "true", "1-128", "Results truncated to 500 lines."), + ] + results = {} + + def tool_script(request): + for message in request["messages"]: + identity = message.get("tool_call_id", "") + if message["role"] == "tool" and identity.startswith("read-"): + results[int(identity.removeprefix("read-"))] = message["content"] + index = len(results) + if index < len(cases): + return {"name": "file_read", "arguments": json.dumps(cases[index][0])}, f"read-{index}" + return {"name": "task_done", "arguments": "{}"}, "done" + + with compat.peer._stub_gateway(tool_script=tool_script) as url: + environment.update( + OCR_LLM_URL=url, + OCR_LLM_TOKEN="synthetic-token", + OCR_LLM_MODEL="synthetic-model", + OCR_LLM_PROTOCOL="openai", + OCR_TELEMETRY_ENABLED="false", + ) + output = compat.execution._run( + [ + binary, + "review", + "--from", + base, + "--to", + head, + "--effort", + "low", + "--concurrency", + "1", + "--format", + "json", + "--audience", + "agent", + ], + cwd=root, + env=environment, + ) + assert json.loads(output)["tool_calls"]["by_tool"]["file_read"] == len(cases) + assert len(results) == len(cases) + review_range = ReviewRange(base, head) + observations = set() + for index, (args, truncated, expected_range, marker) in enumerate(cases): + result = results[index] + assert f"IS_TRUNCATED: {truncated}\nLINE_RANGE: {expected_range}\n" in result + assert marker in result + if args["file_path"] == "example.py": + assert "🧪" not in result and "10 more bytes omitted" in result + observations.add(_read_observation(args, result, review_range, ok=True)) + assert results[2].startswith(f"SIDE: old\nREVISION: {base}\n") + assert len(results[4].split("\n", 3)[-1].encode()) == 262_144 + assert results[6].index(_UTF8_NOTICE) < results[6].index("Output truncated at 262144 bytes.") + dependencies = NativeDependencies.inspect(home, root, review_range) + assert dependencies is not None + assert dependencies.groups["example.py"].reads == observations + reader = GitRepositoryReader( + root, max_file_bytes=MAX_SOURCE_BYTES, deadline=monotonic() + 10, local_only=True + ) + assert dependencies._verify_reads(reader, observations) == observations diff --git a/tests/test_local_incremental_replay.py b/tests/test_local_incremental_replay.py index ad61701a..50e2b392 100644 --- a/tests/test_local_incremental_replay.py +++ b/tests/test_local_incremental_replay.py @@ -2,11 +2,12 @@ import json from collections import Counter +from pathlib import Path import pytest from ocr_toolkit import local_incremental_replay -from ocr_toolkit.evidence import CoverageRecord, CoverageState, EvidenceStore, RefRole +from ocr_toolkit.evidence import CoverageRecord, CoverageState, EvidenceStore, RefRole, repository from ocr_toolkit.evidence.actions import ACTION_RECEIPT_BUCKETS, EVIDENCE_ACTIONS from ocr_toolkit.evidence.mcp import ( COVERAGE_TOOL_NAME, @@ -18,9 +19,11 @@ from ocr_toolkit.evidence.repository import GitRepositoryReader from ocr_toolkit.local_incremental_dependencies import NativeDependencies, dependency_path from ocr_toolkit.local_incremental_replay import ReplayVerifier, observed_replay -from ocr_toolkit.local_incremental_state import IncrementalError, ToolReplay +from ocr_toolkit.local_incremental_state import IncrementalError, IncrementalSearchError, ToolReplay +from ocr_toolkit.result_contract import parse_result_outcome from ocr_toolkit.review_range import ReviewRange from tests.test_evidence_repository import git +from tests.test_ocr_compat import load_script @pytest.fixture(scope="module") @@ -104,27 +107,241 @@ def test_replay_reproduces_immutable_native_output_and_detects_changes( assert current.verifies(observed) is remains_valid -def test_excess_search_matches_do_not_confirm_a_partial_observation(tmp_path): +def _search_block(path, lines): + return ( + f"File: {path}\nMatch lines: {len(lines)}\n" + + "".join(f"{number}|{line}\n" for number, line in enumerate(lines, start=1)) + + "\n" + ) + + +def _search_note(files): + return ( + f"Note: Showing the first 100 matches across {files} matching files. " + "Some files are partially shown or omitted entirely. Narrow file_patterns to see the rest.\n" + ) + + +def test_capped_search_binds_visible_matches_and_omitted_file_count(tmp_path, monkeypatch): git(tmp_path, "init", "-q") - (tmp_path / "status.md").write_text("ordinary text\n") + first = tmp_path / "first.md" + middle = tmp_path / "middle.md" + last = tmp_path / "z-last.md" + first.write_text("searchable line\n" * 99) + middle.write_text("searchable middle\n") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + last.write_text("searchable initially omitted\n") + git(tmp_path, "add", last.name) + git(tmp_path, "commit", "-qm", "first cap") + capped_head = git(tmp_path, "rev-parse", "HEAD") + arguments = {"search_text": "searchable"} + first_block = _search_block(first.name, ["searchable line"] * 99) + full_prefix = first_block + _search_block(middle.name, ["searchable middle"]) + capped = observed_replay("code_search", arguments, _search_note(3) + full_prefix) + uncapped = observed_replay("code_search", arguments, full_prefix) + reader = GitRepositoryReader(tmp_path) + + def verifier(head): + return ReplayVerifier(reader, ReviewRange(base, head), None, lambda _: True) + + assert verifier(capped_head).verifies(capped) + assert not verifier(capped_head).verifies(uncapped) + with monkeypatch.context() as global_limits: + global_limits.setattr(repository, "MAX_GIT_GREP_BYTES", 60) + limited = verifier(capped_head) + assert not limited.verifies(capped) + assert limited.failure_reason(capped) == "search_capped" + + old_arguments = {**arguments, "side": "old"} + assert verifier(capped_head).verifies( + observed_replay("code_search", old_arguments, f"SIDE: old\nREVISION: {base}\n{full_prefix}") + ) + + last.write_text("searchable changed but omitted\n" * 2) + git(tmp_path, "commit", "-qam", "edit invisible matches") + assert verifier(git(tmp_path, "rev-parse", "HEAD")).verifies(capped) + + last.write_text("no hits remain\n") + git(tmp_path, "commit", "-qam", "remove the cap") + current = verifier(git(tmp_path, "rev-parse", "HEAD")) + assert not current.verifies(capped) + assert current.failure_reason(capped) == "search_capped" + assert current.verifies(uncapped) + + (tmp_path / "z-extra.md").write_text("searchable extra\n") + last.write_text("searchable last\n") git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "add another matching file") + count_change = verifier(git(tmp_path, "rev-parse", "HEAD")) + assert not count_change.verifies(capped) + assert count_change.verifies( + observed_replay("code_search", arguments, _search_note(4) + full_prefix) + ) + + +def test_capped_search_rejects_unrepresentable_rows_even_after_the_prefix(tmp_path): + git(tmp_path, "init", "-q") + (tmp_path / "first.md").write_text("searchable line\n" * 100) + (tmp_path / "z:7:ambiguous.md").write_text("searchable ambiguous line\n") + git(tmp_path, "add", "first.md") git(tmp_path, "commit", "-qm", "base") base = git(tmp_path, "rev-parse", "HEAD") - (tmp_path / "status.md").write_text("searchable line\n" * 101) - git(tmp_path, "commit", "-qam", "head") + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-qm", "ambiguous matching path") head = git(tmp_path, "rev-parse", "HEAD") verifier = ReplayVerifier( GitRepositoryReader(tmp_path), ReviewRange(base, head), None, lambda _: True ) - arguments = {"search_text": "searchable"} - partial_output = ( - "File: status.md\nMatch lines: 100\n" - + "".join(f"{line}|searchable line\n" for line in range(1, 101)) - + "\n" + witnessed = _search_note(2) + _search_block("first.md", ["searchable line"] * 100) + assert not verifier.verifies( + observed_replay("code_search", {"search_text": "searchable"}, witnessed) ) - with pytest.raises(IncrementalError, match="complete match limit"): - verifier._execute("code_search", arguments) - assert not verifier.verifies(observed_replay("code_search", arguments, partial_output)) + + +def test_search_unsupported_regex_and_pathspec_keep_a_private_reason(review_revisions): + root, base, _, head = review_revisions + verifier = ReplayVerifier( + GitRepositoryReader(root), ReviewRange(base, head), None, lambda _: True + ) + invalid = observed_replay( + "code_search", {"search_text": "(", "use_perl_regexp": True}, "No matches found" + ) + assert not verifier.verifies(invalid) + assert verifier.failure_reason(invalid) == "search_regex" + with pytest.raises(IncrementalSearchError) as error: + observed_replay( + "code_search", + {"search_text": "example", "file_patterns": [":(attr:worktree)*"]}, + "No matches found", + ) + assert error.value.reason == "search_pathspec" + + +def test_search_pcre_match_limit_fails_closed(tmp_path): + git(tmp_path, "init", "-q") + source = tmp_path / "sample.md" + source.write_text("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!\n") + git(tmp_path, "add", source.name) + git(tmp_path, "commit", "-qm", "base") + base = git(tmp_path, "rev-parse", "HEAD") + git(tmp_path, "commit", "--allow-empty", "-qm", "head") + head = git(tmp_path, "rev-parse", "HEAD") + reader = GitRepositoryReader(tmp_path) + query = r"(*LIMIT_MATCH=1)(*NO_JIT)^(a+)+$" + failed = reader._run(["grep", "-P", "-e", query, head, "--", source.name]) + if "not compiled with USE_LIBPCRE" in failed.stderr: + pytest.skip("installed Git does not provide PCRE search") + assert failed.returncode == 128 and "match limit" in failed.stderr.casefold() + + verifier = ReplayVerifier(reader, ReviewRange(base, head), None, lambda _: True) + observed = observed_replay( + "code_search", + {"search_text": query, "use_perl_regexp": True, "file_patterns": [source.name]}, + "No matches found", + ) + assert not verifier.verifies(observed) + assert verifier.failure_reason(observed) == "search_regex" + + +def test_native_search_boundaries_match_saved_replay(tmp_path, qualified_native_ocr): + binary, version = qualified_native_ocr("OCR_FEDERATION_QUALIFY_BINARY") + compat = load_script() + if compat.core._version(version) < (1, 14, 6): + pytest.skip("search replay uses the OCR 1.14.6 boundary") + from ocr_qualification.comparison import ComparisonConversation, ToolCase + + git_env = compat.execution._isolated_probe_environment(tmp_path / "git-home") + review_env = compat.execution._isolated_probe_environment(tmp_path / "review-home") + lines = ["release-note7: Résumé\r"] + ["release-note7"] * 98 + contents = { + "docs/a.md": "".join(f"{line}\n" for line in lines), + "docs/b.md": "release-note8\n", + "docs/c.md": "release-note9\n", + "docs/excluded/manual.md": "release-note10\n", + } + root, base, head = compat.execution._synthetic_repo(tmp_path, git_env, context_files=contents) + (root / "docs/a.md").write_text("worktree only release-note11\n", encoding="utf-8") + (root / "docs/untracked.md").write_text("untracked release-note12\n", encoding="utf-8") + a_block = _search_block("docs/a.md", lines) + b_block = _search_block("docs/b.md", ["release-note8"]) + literal = {"search_text": "release-note"} + cases = ( + ({**literal, "file_patterns": ["docs/a.md"]}, a_block), + ({**literal, "file_patterns": ["docs/a.md", "docs/b.md"]}, a_block + b_block), + ( + { + "search_text": r"(?<=release-)note[0-9]+", + "use_perl_regexp": True, + "file_patterns": ["docs/", ":(exclude)docs/excluded/"], + }, + _search_note(3) + a_block + b_block, + ), + ( + { + "search_text": r"(?<=return )1$", + "use_perl_regexp": True, + "file_patterns": [":(exclude)docs/"], + "side": "old", + }, + f"SIDE: old\nREVISION: {base}\nFile: example.py\nMatch lines: 1\n2| return 1\n\n", + ), + ) + conversation = ComparisonConversation( + [ToolCase("code_search", arguments, ()) for arguments, _ in cases] + ) + witnessed = {} + + def script(request): + response = conversation(request) + for message in request["messages"]: + if message.get("role") == "tool": + witnessed[message["tool_call_id"]] = message["content"] + return response + + with compat.peer._stub_gateway(tool_script=script) as url: + review_env.update( + OCR_LLM_URL=url, + OCR_LLM_TOKEN="synthetic-token", + OCR_LLM_MODEL="synthetic-model", + OCR_LLM_PROTOCOL="openai", + OCR_TELEMETRY_ENABLED="false", + ) + output = compat.execution._run( + [ + str(Path(binary).resolve()), + "review", + "--from", + base, + "--to", + head, + "--effort", + "low", + "--concurrency", + "1", + "--no-filter", + "--format", + "json", + "--audience", + "agent", + ], + cwd=root, + env=review_env, + ) + + assert conversation.complete + result = parse_result_outcome(json.loads(output)) + assert result.kind == "clean" and result.completed_count == 1 + assert (root / "docs/a.md").read_text(encoding="utf-8") == "worktree only release-note11\n" + assert (root / "docs/untracked.md").read_text(encoding="utf-8") == "untracked release-note12\n" + verifier = ReplayVerifier( + GitRepositoryReader(root), ReviewRange(base, head), None, lambda _: True + ) + for index, (arguments, expected) in enumerate(cases): + actual = witnessed[f"comparison-{index}"] + assert actual == expected + assert verifier.verifies(observed_replay("code_search", arguments, actual)) def test_duplicate_diff_paths_are_counted_against_the_aggregate_budget( @@ -184,9 +401,13 @@ def test_replay_budget_counts_distinct_queries_and_keeps_verified_results(review ( ("tracker__echo", '{"text":"external"}'), ("future_native_tool", "{}"), - ("code_search", '{"search_text":"[a-z]","use_perl_regexp":true}'), + ("code_search", '{"search_text":"[a-z]","use_perl_regexp":"true"}'), ("code_search", '{"search_text":"text","case_sensitive":"true"}'), ("code_search", '{"search_text":"text","file_patterns":["../outside"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(exclude)../outside"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(exclude)/absolute"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(attr:worktree)*"]}'), + ("code_search", '{"search_text":"text","file_patterns":[":(exclude,attr:worktree)*"]}'), ("code_search", '{"search_text":"text","search_text":"other"}'), ("file_find", '{"query_name":"private word"}'), ("file_read_diff", '{"path_array":["notes/release.md","status.md"]}'), @@ -296,6 +517,11 @@ def test_incomplete_or_unbound_observation_cannot_create_replay(tool, arguments, ("changed_search", "search_tool"), ("unexecuted_call", "unsupported_tool"), ("unknown_call", "unsupported_tool"), + ("filter_keep_all", None), + ("filter_wrong_task", "unsupported_tool"), + ("filter_wrong_arguments", "invalid_arguments"), + ("filter_remove", "unsupported_tool"), + ("filter_dispatched", "unsupported_tool"), ("failed_tool", "failed_tool_call"), ("model_failure", "llm_error"), ("invalid_args", "invalid_arguments"), @@ -366,6 +592,31 @@ def tool_call(tool, args, result, *, ok=True): observe("llm_response", tool_calls=[{"name": "future_native_tool"}]) case "unknown_call": tool_call("future_native_tool", {}, "Native returned an observation") + case "filter_keep_all" | "filter_wrong_task" | "filter_wrong_arguments" | "filter_remove": + calls = [ + { + "id": "filter-approve", + "name": "approve_all_comments", + "arguments": "[]" if observation == "filter_wrong_arguments" else "{}", + } + ] + if observation == "filter_remove": + calls.append( + { + "id": "filter-remove", + "name": "report_incorrect_comments", + "arguments": '{"analysis":"Synthetic contradiction","comment_ids":["c-0"]}', + } + ) + observe( + "llm_response", + taskType="main_task" + if observation == "filter_wrong_task" + else "review_filter_task", + tool_calls=calls, + ) + case "filter_dispatched": + tool_call("approve_all_comments", {}, "Unexpected executable tool observation") case "failed_tool": tool_call("file_find", {"query_name": "readme"}, "Tool failed", ok=False) case "invalid_args":