From fb391e1a0444ca767a3e71494dcd2bb12dd1e242 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Thu, 24 Sep 2026 23:51:58 +0000 Subject: [PATCH] fix(review): verifier no longer invalidates findings its own reason confirms The first sample validation (#505) found all three unpinned :latest image findings invalidated although the verifier's reason confirmed the defect: it filed the finding's own verification criterion, or its fix, as the invalidation it matched. A matched invalidation criterion that restates the finding's claim, title or fix, or a reason that states the claimed condition without negating it, no longer invalidates. The finding stays unverified and reported. Genuine refutations still invalidate, even beside a restatement. The run's misread verdicts are regression cases in the #509 harness. Closes #536 --- docs/ROADMAP.md | 3 + ...idates-findings-its-own-reason-confirms.md | 43 +++ src/devops_cli/ai/review/verification.py | 67 +++- tests/golden/review_findings.json | 352 ++++++++++++++++-- tests/test_review_regression_harness.py | 15 +- tests/test_review_verification.py | 4 +- tests/test_review_verifier_self_refutation.py | 118 ++++++ 7 files changed, 559 insertions(+), 43 deletions(-) create mode 100644 docs/agent/tasks/task-536-verifier-invalidates-findings-its-own-reason-confirms.md create mode 100644 tests/test_review_verifier_self_refutation.py diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 62d6ed340e..60fb05ffaf 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -383,6 +383,9 @@ High-density product roadmap, engineering milestones, and open-source integratio - [x] **Defect Generator Injects Into Code Examples Inside Block Comments (P1 - High, Issue #537)**: - *Context & Rationale*: The first sample validation (#505) found 9 of 78 brace-language injections inside multi-line comments, all dropped awaits in ky's JSDoc examples. The finders blanked one-line comments only, so documentation counted as code and the corpus scored reviewers on defects that do not exist. - *Delivered*: Block comments spanning lines are blanked for every brace-language finder and the Terraform block tracker; a `/*` or `//` inside a string opens no comment. TLS, file-mode and Terraform substitutions apply only outside comments. On the pinned samples no site falls inside a comment. TypeScript `drop-await` sites fell from 99 to 44 and `drop-bounds-check` from 15 to 12; other languages are unchanged. +- [x] **Verifier Invalidates Findings Its Own Reason Confirms (P1 - High, Issue #536)**: + - *Context & Rationale*: The first sample validation (#505) found all three unpinned `:latest` image findings invalidated although the verifier's reason confirmed the defect: it filed the finding's own verification criterion, or its fix, as the invalidation it matched. They were 3 of the run's 6 found-then-dropped injections. + - *Delivered*: A matched invalidation criterion that restates the finding's claim or fix, or a reason that states the claimed condition without negating it, no longer invalidates; the finding stays unverified and reported. Genuine refutations still invalidate. The run's misread verdicts are regression cases in the #509 harness. - [ ] **AST Support for C#, C/C++, Shell and Markdown (P2 - Medium, Issue #506)**: - *Context & Rationale*: The AST engine maps Python, TypeScript, JavaScript, Go, Rust, Java and HCL. C#, C, C++, shell and Markdown files yield no symbols, so repomaps, context packing and review grounding see nothing in them. - *Deliverable*: Tree-sitter grammars where a maintained package exists, and fallback extractors for functions, types and headings, each tested on its pinned sample repository. diff --git a/docs/agent/tasks/task-536-verifier-invalidates-findings-its-own-reason-confirms.md b/docs/agent/tasks/task-536-verifier-invalidates-findings-its-own-reason-confirms.md new file mode 100644 index 0000000000..4397daf461 --- /dev/null +++ b/docs/agent/tasks/task-536-verifier-invalidates-findings-its-own-reason-confirms.md @@ -0,0 +1,43 @@ +# Task 536: Verifier Invalidates Findings Its Own Reason Confirms + +**Issue**: [#536](https://github.com/dan-petty/devops-cli/issues/536) +**Status**: Done +**Milestone**: `v0.2.23` +**Priority**: `priority/p1-high` +**Scope**: `type/bug`, `scope/review`, `priority/p1-high` + +--- + +## 1. Description & Objectives + +The first sample validation (#505) found all three unpinned `:latest` image findings INVALIDATED, +although the verifier's own reason confirmed the defect. It had filed the finding's verification +criterion, or its fix, as the invalidation criterion it matched: +- "Line 6 contains `FROM alpine:latest`, which uses the unpinned `latest` tag", matched as + "The FROM directive still uses 'latest' as the image tag."; +- "The Dockerfile contains a specific tag (e.g., `golang:1.22.3`) and a checksum", which is the + fix. + +These were 3 of the run's 6 found-then-dropped injections. + +### Key Deliverables Completed: + +- [x] **Self-refutation withdrawn** (`_without_self_refutation` in `verification.py`): + - A matched invalidation criterion that restates the finding's verification criteria, title or + fix (60% or more of their words, and closer to them than to the finding's invalidation + criteria) is not a refutation. + - A reason that states the claimed condition without negating it confirms the finding. + - When the invalidation rests only on those, it is withdrawn, the INVALIDATED status included, + and the finding stays unverified and in the report. + - A genuine refutation still invalidates, even beside a restatement. +- [x] **Automated Tests & Quality Gates**: + - `tests/test_review_verifier_self_refutation.py`: + - the verification criterion, a reworded criterion, and the fix as the "invalidation"; + - no criteria and a confirming reason; + - genuine refutations by digest, by test fixture, and beside a restatement; + - an untouched confirmation. + - `tests/test_review_regression_harness.py`: the run's two misread verdicts, in the golden set + (`misread_verdicts`). + - `tests/test_review_verification.py`: the invalidation case now matches a criterion the + finding names as invalidating it, not its own claim. + - 100% passing status across Gated CI validation suite (`uv run devops ci`). diff --git a/src/devops_cli/ai/review/verification.py b/src/devops_cli/ai/review/verification.py index f7fdc88a72..d37e18e140 100644 --- a/src/devops_cli/ai/review/verification.py +++ b/src/devops_cli/ai/review/verification.py @@ -1248,6 +1248,71 @@ def _verdict_status(item: dict[str, Any], inv_matched: list[str]) -> tuple[str, return "UNVERIFIED", True +# Words too common to tell one claim from another. +_CLAIM_STOPWORDS = frozenset( + {"the", "a", "an", "of", "to", "in", "is", "are", "as", "for", "with", "that", "this"} + | {"and", "or", "be", "it", "its", "on", "by", "at", "still", "which", "verify", "check"} +) +# A reason that negates what it quotes may be a refutation; one that does not only restates. +_NEGATION = re.compile( + r"\b(?:not|no|never|none|cannot|without|already|isn't|doesn't|don't|aren't|wasn't)\b|n't\b" +) +_RESTATEMENT_OVERLAP = 0.6 + + +def _claim_words(text: str) -> set[str]: + return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in _CLAIM_STOPWORDS} + + +def _covers(text: str, claims: list[str]) -> float: + """The largest share of any claim's words that the text contains.""" + words = _claim_words(text) + shares = [len(cw & words) / len(cw) for claim in claims if (cw := _claim_words(claim))] + return max(shares, default=0.0) + + +def _restates_the_finding(criterion: str, f: Finding) -> bool: + """Whether a "matched invalidation criterion" only restates the defect or its fix. + + Models file the finding's own verification criterion, or the fix, as the invalidation they + matched: "The FROM directive still uses 'latest' as the image tag." That confirms the + defect. A criterion closer to the finding's invalidation criteria than to its claim and fix + is a refutation. + """ + claim = _covers(criterion, [*f.verification_criteria, f.title, f.fix]) + refutation = _covers(criterion, list(f.invalidation_criteria)) + return claim >= _RESTATEMENT_OVERLAP and claim > refutation + + +def _reason_confirms(reason: str, f: Finding) -> bool: + """Whether the verdict's reason states the claimed condition without negating it.""" + return ( + bool(reason) + and not _NEGATION.search(reason.lower()) + and _covers(reason, [*f.verification_criteria, f.title]) >= _RESTATEMENT_OVERLAP + ) + + +def _without_self_refutation(f: Finding, item: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: + """The verdict with its invalidation withdrawn when it rests only on the finding's own claim. + + An invalidation whose matched criteria all restate the defect or its fix, or whose reason + confirms the claimed condition, names no evidence against the finding; it leaves the + finding unverified and in the report. + """ + inv_matched = _verdict_list(item.get("invalidated_criteria_matched")) + genuine = [c for c in inv_matched if not _restates_the_finding(c, f)] + reason = str(item.get("reason") or "").strip() + if genuine and not _reason_confirms(reason, f): + return item, inv_matched + if not inv_matched and not _reason_confirms(reason, f): + return item, inv_matched + withdrawn = {**item, "invalidated": False} + if str(item.get("status") or "").strip().upper() == "INVALIDATED": + withdrawn["status"] = "" + return withdrawn, [] + + def _apply_single_finding_verification( f: Finding, item: dict[str, Any] | None, now_iso: str ) -> Finding: @@ -1256,7 +1321,7 @@ def _apply_single_finding_verification( return f ver_matched = _verdict_list(item.get("verified_criteria_matched")) - inv_matched = _verdict_list(item.get("invalidated_criteria_matched")) + item, inv_matched = _without_self_refutation(f, item) status_val, is_rep = _verdict_status(item, inv_matched) is_v = status_val == "VERIFIED" # A model's invalidation does not teach the hallucinations catalog: it is the judgement diff --git a/tests/golden/review_findings.json b/tests/golden/review_findings.json index b9e00b24c1..370005fe78 100644 --- a/tests/golden/review_findings.json +++ b/tests/golden/review_findings.json @@ -30,49 +30,321 @@ "app/paths_only.py": "from pathlib import Path\n\n\ndef where(p):\n return Path(p).resolve()\n" }, "real_defects": [ - {"id": "missing-containment", "location": "core/paths.py:4-8", "severity": "HIGH", "title": "safe_resolve_subpath allows traversal outside base_dir", "description": "No containment check follows resolve(); `../` segments escape base_dir. Symlink rejection does not stop them."}, - {"id": "missing-depth-limit", "location": "security/suppression.py:4-10", "severity": "HIGH", "title": "Missing inheritance depth limit in load_policy", "description": "The `load_policy` function accepts a `_depth` parameter but never enforces CONST_SUPPRESSION_MAX_INHERITANCE_DEPTH, so a long extends chain recurses without bound."}, - {"id": "world-writable-dir", "location": "crypto/known_hosts.py:5", "severity": "HIGH", "title": "Insecure directory creation permissions in append_entry", "description": "The parent directory of known_hosts is created with mode 0o777."}, - {"id": "playbook-0777", "location": "playbooks/cluster_backup.yaml:7", "severity": "HIGH", "title": "Backup directory created world-writable (0777)", "description": "The backup directory is created with mode 0777."}, - {"id": "unpinned-image", "location": "playbooks/gpu_validation.yaml:10", "severity": "MEDIUM", "title": "Unpinned image tag nvidia/cuda:latest", "description": "The smoke test pulls a moving tag."}, - {"id": "unchecked-status", "location": "security/vault_lease.py:4-6", "severity": "MEDIUM", "title": "HTTP POST helper does not validate response status", "description": "`_post` parses the body of any response, so a 403 or 500 is treated as data."}, - {"id": "unvalidated-dest", "location": "core/audit.py:5-6", "severity": "HIGH", "title": "Audit log destination from environment is not validated", "description": "AUDIT_LOG_DEST is resolved without a containment check."}, - {"id": "dropped-await", "location": "core/process.py:5", "severity": "HIGH", "title": "wait_for coroutine is never awaited", "description": "`asyncio.wait_for` is called without await, so the timeout never applies."}, - {"id": "fstring-sql", "location": "app/db.py:2-3", "severity": "CRITICAL", "title": "SQL injection via f-string", "description": "The f-string syntax interpolates the search term into the SQL query."}, - {"id": "bare-except", "location": "app/errors.py:4", "severity": "MEDIUM", "title": "Bare `except` clause swallows KeyboardInterrupt", "description": "The bare except clause catches everything, including KeyboardInterrupt."}, - {"id": "processed-timestamps", "location": "app/auth.py:1-2", "severity": "HIGH", "title": "Expired tokens are processed as valid", "description": "Naive and aware timestamps are compared, so expiry never applies."}, - {"id": "if-none-of", "location": "app/auth.py:5-9", "severity": "CRITICAL", "title": "Authorization bypass in allowed", "description": "If none of the roles match, the loop falls through to return True."}, - {"id": "not-properly", "location": "app/limit.py:1-2", "severity": "MEDIUM", "title": "Rate limiter not properly implemented for bursts", "description": "Every request is allowed."}, - {"id": "api-need-to", "location": "app/api.py:1-2", "severity": "MEDIUM", "title": "Clients of the API need to send the token in the query string", "description": "Tokens in query strings reach access logs."}, - {"id": "masked-live-key", "location": "app/keys.py:1", "severity": "CRITICAL", "title": "Live AWS key committed", "description": "`api_key=` is a live credential, not a placeholder."}, - {"id": "real-secret-in-tests", "location": "tests/conftest.py:1", "severity": "HIGH", "title": "Hardcoded password in test configuration", "description": "A real staging password is committed."}, - {"id": "cwe400-upload", "location": "app/upload.py:4-5", "severity": "HIGH", "title": "CWE-400: unbounded read_text() of user-uploaded file", "description": "handle_upload reads an attacker-supplied file with no size cap."}, - {"id": "unbound-local", "location": "app/prompt.py:4", "severity": "MEDIUM", "title": "`system_prompt` may be unbound (UnboundLocalError) when the list is empty", "description": "If items is empty the loop never assigns system_prompt."}, - {"id": "real-nameerror", "location": "app/retry.py:2", "severity": "HIGH", "title": "NameError: undefined variable `timeout` in retry", "description": "`timeout` is not defined anywhere in the module."}, - {"id": "missing-auth-header", "location": "app/client.py:8-9", "severity": "HIGH", "title": "delete request sent without authentication", "description": "No Authorization header is sent by delete."}, - {"id": "token-logged", "location": "app/logging.py:2", "severity": "HIGH", "title": "Looks good overall, but token is logged in plaintext", "description": "The login token is printed."}, - {"id": "persona-self-dismissal", "location": "app/logging.py:1-2", "severity": "HIGH", "title": "Token printed during login", "description": "login prints the token to stdout.", "persona_fields": {"status": "INVALIDATED", "reportable": false, "mitigated": true}}, - {"id": "miscounted-line", "location": "app/short.py:250", "severity": "MEDIUM", "title": "Unvalidated module constant", "description": "The line number is past the end of the file, as a model's own count can be."} + { + "id": "missing-containment", + "location": "core/paths.py:4-8", + "severity": "HIGH", + "title": "safe_resolve_subpath allows traversal outside base_dir", + "description": "No containment check follows resolve(); `../` segments escape base_dir. Symlink rejection does not stop them." + }, + { + "id": "missing-depth-limit", + "location": "security/suppression.py:4-10", + "severity": "HIGH", + "title": "Missing inheritance depth limit in load_policy", + "description": "The `load_policy` function accepts a `_depth` parameter but never enforces CONST_SUPPRESSION_MAX_INHERITANCE_DEPTH, so a long extends chain recurses without bound." + }, + { + "id": "world-writable-dir", + "location": "crypto/known_hosts.py:5", + "severity": "HIGH", + "title": "Insecure directory creation permissions in append_entry", + "description": "The parent directory of known_hosts is created with mode 0o777." + }, + { + "id": "playbook-0777", + "location": "playbooks/cluster_backup.yaml:7", + "severity": "HIGH", + "title": "Backup directory created world-writable (0777)", + "description": "The backup directory is created with mode 0777." + }, + { + "id": "unpinned-image", + "location": "playbooks/gpu_validation.yaml:10", + "severity": "MEDIUM", + "title": "Unpinned image tag nvidia/cuda:latest", + "description": "The smoke test pulls a moving tag." + }, + { + "id": "unchecked-status", + "location": "security/vault_lease.py:4-6", + "severity": "MEDIUM", + "title": "HTTP POST helper does not validate response status", + "description": "`_post` parses the body of any response, so a 403 or 500 is treated as data." + }, + { + "id": "unvalidated-dest", + "location": "core/audit.py:5-6", + "severity": "HIGH", + "title": "Audit log destination from environment is not validated", + "description": "AUDIT_LOG_DEST is resolved without a containment check." + }, + { + "id": "dropped-await", + "location": "core/process.py:5", + "severity": "HIGH", + "title": "wait_for coroutine is never awaited", + "description": "`asyncio.wait_for` is called without await, so the timeout never applies." + }, + { + "id": "fstring-sql", + "location": "app/db.py:2-3", + "severity": "CRITICAL", + "title": "SQL injection via f-string", + "description": "The f-string syntax interpolates the search term into the SQL query." + }, + { + "id": "bare-except", + "location": "app/errors.py:4", + "severity": "MEDIUM", + "title": "Bare `except` clause swallows KeyboardInterrupt", + "description": "The bare except clause catches everything, including KeyboardInterrupt." + }, + { + "id": "processed-timestamps", + "location": "app/auth.py:1-2", + "severity": "HIGH", + "title": "Expired tokens are processed as valid", + "description": "Naive and aware timestamps are compared, so expiry never applies." + }, + { + "id": "if-none-of", + "location": "app/auth.py:5-9", + "severity": "CRITICAL", + "title": "Authorization bypass in allowed", + "description": "If none of the roles match, the loop falls through to return True." + }, + { + "id": "not-properly", + "location": "app/limit.py:1-2", + "severity": "MEDIUM", + "title": "Rate limiter not properly implemented for bursts", + "description": "Every request is allowed." + }, + { + "id": "api-need-to", + "location": "app/api.py:1-2", + "severity": "MEDIUM", + "title": "Clients of the API need to send the token in the query string", + "description": "Tokens in query strings reach access logs." + }, + { + "id": "masked-live-key", + "location": "app/keys.py:1", + "severity": "CRITICAL", + "title": "Live AWS key committed", + "description": "`api_key=` is a live credential, not a placeholder." + }, + { + "id": "real-secret-in-tests", + "location": "tests/conftest.py:1", + "severity": "HIGH", + "title": "Hardcoded password in test configuration", + "description": "A real staging password is committed." + }, + { + "id": "cwe400-upload", + "location": "app/upload.py:4-5", + "severity": "HIGH", + "title": "CWE-400: unbounded read_text() of user-uploaded file", + "description": "handle_upload reads an attacker-supplied file with no size cap." + }, + { + "id": "unbound-local", + "location": "app/prompt.py:4", + "severity": "MEDIUM", + "title": "`system_prompt` may be unbound (UnboundLocalError) when the list is empty", + "description": "If items is empty the loop never assigns system_prompt." + }, + { + "id": "real-nameerror", + "location": "app/retry.py:2", + "severity": "HIGH", + "title": "NameError: undefined variable `timeout` in retry", + "description": "`timeout` is not defined anywhere in the module." + }, + { + "id": "missing-auth-header", + "location": "app/client.py:8-9", + "severity": "HIGH", + "title": "delete request sent without authentication", + "description": "No Authorization header is sent by delete." + }, + { + "id": "token-logged", + "location": "app/logging.py:2", + "severity": "HIGH", + "title": "Looks good overall, but token is logged in plaintext", + "description": "The login token is printed." + }, + { + "id": "persona-self-dismissal", + "location": "app/logging.py:1-2", + "severity": "HIGH", + "title": "Token printed during login", + "description": "login prints the token to stdout.", + "persona_fields": { + "status": "INVALIDATED", + "reportable": false, + "mitigated": true + } + }, + { + "id": "miscounted-line", + "location": "app/short.py:250", + "severity": "MEDIUM", + "title": "Unvalidated module constant", + "description": "The line number is past the end of the file, as a model's own count can be." + } ], "distinct_groups": [ - {"id": "filler-word", "findings": [ - {"location": "app/client.py:4-5", "severity": "HIGH", "title": "Missing timeout", "description": "requests.get has no timeout."}, - {"location": "app/client.py:5", "severity": "HIGH", "title": "Missing authorization check", "description": "fetch is callable by anyone."} - ]}, - {"id": "same-title-far-apart", "findings": [ - {"location": "app/secrets.py:1", "severity": "CRITICAL", "title": "Hardcoded secret", "description": "`AWS_KEY` is committed."}, - {"location": "app/secrets.py:90", "severity": "CRITICAL", "title": "Hardcoded secret", "description": "`DB_PASSWORD` is committed."} - ]} + { + "id": "filler-word", + "findings": [ + { + "location": "app/client.py:4-5", + "severity": "HIGH", + "title": "Missing timeout", + "description": "requests.get has no timeout." + }, + { + "location": "app/client.py:5", + "severity": "HIGH", + "title": "Missing authorization check", + "description": "fetch is callable by anyone." + } + ] + }, + { + "id": "same-title-far-apart", + "findings": [ + { + "location": "app/secrets.py:1", + "severity": "CRITICAL", + "title": "Hardcoded secret", + "description": "`AWS_KEY` is committed." + }, + { + "location": "app/secrets.py:90", + "severity": "CRITICAL", + "title": "Hardcoded secret", + "description": "`DB_PASSWORD` is committed." + } + ] + } ], "known_hallucinations": [ - {"id": "pep758", "location": "app/syntax.py:3", "severity": "HIGH", "title": "Syntax error: invalid Python 2 syntax in except clause", "description": "except ValueError, TypeError: is invalid syntax."}, - {"id": "defined-symbol", "location": "app/helpers.py:1", "severity": "LOW", "title": "Missing `helper` function", "description": "`helper` is not defined in this module."}, - {"id": "masked-syntax", "location": "app/keys.py:1", "severity": "HIGH", "title": "Syntax error: unquoted placeholder ", "description": "Unresolved identifier found in code snippet."}, - {"id": "placeholder-cve", "location": "app/client.py:1", "severity": "HIGH", "title": "Vulnerable requests dependency", "description": "requests is affected by CVE-2023-xxxx."}, - {"id": "below-floor", "location": "app/enum_use.py:1", "severity": "MEDIUM", "title": "StrEnum import is incompatible with Python 3.10", "description": "On Python 3.10 the import raises ImportError."}, - {"id": "monologue", "location": "app/api.py:1", "severity": "LOW", "title": "Let's check the token handling", "description": "Reasoning leaked into a title."}, - {"id": "compliment", "location": "app/api.py:1", "severity": "LOW", "title": "Implementation looks solid and clean", "description": "Positive remarks."}, - {"id": "fixture-token", "location": "tests/test_login.py:1", "severity": "HIGH", "title": "Hardcoded token in test fixture", "description": "A hardcoded token is committed."}, - {"id": "resolve-non-strict", "location": "app/paths_only.py:5", "severity": "LOW", "title": "Path.resolve() raises FileNotFoundError", "description": "resolve() raises FileNotFoundError when the path does not exist."} + { + "id": "pep758", + "location": "app/syntax.py:3", + "severity": "HIGH", + "title": "Syntax error: invalid Python 2 syntax in except clause", + "description": "except ValueError, TypeError: is invalid syntax." + }, + { + "id": "defined-symbol", + "location": "app/helpers.py:1", + "severity": "LOW", + "title": "Missing `helper` function", + "description": "`helper` is not defined in this module." + }, + { + "id": "masked-syntax", + "location": "app/keys.py:1", + "severity": "HIGH", + "title": "Syntax error: unquoted placeholder ", + "description": "Unresolved identifier found in code snippet." + }, + { + "id": "placeholder-cve", + "location": "app/client.py:1", + "severity": "HIGH", + "title": "Vulnerable requests dependency", + "description": "requests is affected by CVE-2023-xxxx." + }, + { + "id": "below-floor", + "location": "app/enum_use.py:1", + "severity": "MEDIUM", + "title": "StrEnum import is incompatible with Python 3.10", + "description": "On Python 3.10 the import raises ImportError." + }, + { + "id": "monologue", + "location": "app/api.py:1", + "severity": "LOW", + "title": "Let's check the token handling", + "description": "Reasoning leaked into a title." + }, + { + "id": "compliment", + "location": "app/api.py:1", + "severity": "LOW", + "title": "Implementation looks solid and clean", + "description": "Positive remarks." + }, + { + "id": "fixture-token", + "location": "tests/test_login.py:1", + "severity": "HIGH", + "title": "Hardcoded token in test fixture", + "description": "A hardcoded token is committed." + }, + { + "id": "resolve-non-strict", + "location": "app/paths_only.py:5", + "severity": "LOW", + "title": "Path.resolve() raises FileNotFoundError", + "description": "resolve() raises FileNotFoundError when the path does not exist." + } + ], + "misread_verdicts": [ + { + "id": "latest-criterion-as-invalidation", + "finding": { + "location": "docker/Dockerfile:6", + "severity": "MEDIUM", + "title": "Unpinned base image tag", + "description": "`FROM alpine:latest` pulls whatever the tag points at when built.", + "fix": "Pin alpine to a specific version tag and digest.", + "verification_criteria": [ + "The FROM directive uses the 'latest' tag" + ], + "invalidation_criteria": [ + "The base image is pinned to a version or digest" + ] + }, + "verdict": { + "status": "INVALIDATED", + "invalidated": true, + "reason": "Line 6 contains `FROM alpine:latest`, which uses the unpinned `latest` tag.", + "invalidated_criteria_matched": [ + "The FROM directive still uses 'latest' as the image tag." + ] + } + }, + { + "id": "fix-as-invalidation", + "finding": { + "location": "web/guestbook-go/Dockerfile:15", + "severity": "MEDIUM", + "title": "Unpinned base image tag (golang:latest)", + "description": "The build image is `golang:latest`.", + "fix": "Pin golang to a specific tag such as golang:1.22.3 and verify its checksum.", + "verification_criteria": [ + "The Dockerfile uses the latest tag for the golang base image" + ], + "invalidation_criteria": [ + "The golang image is pinned to a version or digest" + ] + }, + "verdict": { + "status": "INVALIDATED", + "reason": "The Dockerfile uses the `latest` tag for the golang base image, which introduces non-deterministic builds.", + "invalidated_criteria_matched": [ + "The Dockerfile contains a specific tag (e.g., `golang:1.22.3`) and a checksum." + ] + } + } ] } diff --git a/tests/test_review_regression_harness.py b/tests/test_review_regression_harness.py index 727857face..3d6d6dc93c 100644 --- a/tests/test_review_regression_harness.py +++ b/tests/test_review_regression_harness.py @@ -25,7 +25,10 @@ import pytest from devops_cli.ai.review import ReviewPipelineOrchestrator -from devops_cli.ai.review.verification import _deterministic_pre_verification +from devops_cli.ai.review.verification import ( + _apply_single_finding_verification, + _deterministic_pre_verification, +) from devops_cli.ai.review_schema import ( FileReviewPayload, Finding, @@ -114,3 +117,13 @@ def test_a_known_false_alarm_is_still_caught(case: dict[str, Any], project: Path result = _deterministic_pre_verification(finding, repo_root=project) assert (result.status, result.reportable) == ("INVALIDATED", False), result.invalidation_reason + + +@pytest.mark.parametrize("case", _GOLDEN["misread_verdicts"], ids=lambda c: c["id"]) +def test_a_verdict_restating_the_defect_does_not_remove_it(case: dict[str, Any]) -> None: + """Verify a verifier reply that confirms the defect in its reason keeps the finding (#536).""" + finding = Finding(**case["finding"]) + + result = _apply_single_finding_verification(finding, case["verdict"], "2026-09-25T00:00:00Z") + + assert (result.status in _DISMISSED, result.reportable) == (False, True) diff --git a/tests/test_review_verification.py b/tests/test_review_verification.py index c0fd0c67a7..f13d4c7591 100644 --- a/tests/test_review_verification.py +++ b/tests/test_review_verification.py @@ -353,7 +353,8 @@ def test_format_related_file_block(tmp_path: Path) -> None: (None, "UNVERIFIED", True, False, None), ( { - "invalidated_criteria_matched": ["Criterion 1"], + # A criterion the finding named as invalidating it, not its own claim (#536). + "invalidated_criteria_matched": ["Input validated upstream"], "confidence_score": 0.95, "severity": "LOW", "location": "test.py:12", @@ -407,6 +408,7 @@ def test_apply_single_finding_verification( severity="MEDIUM", status="UNVERIFIED", verification_criteria=["Criterion 1", "Criterion 2"], + invalidation_criteria=["Input validated upstream"], ) now_iso = "2026-08-26T00:00:00" diff --git a/tests/test_review_verifier_self_refutation.py b/tests/test_review_verifier_self_refutation.py new file mode 100644 index 0000000000..04678d063b --- /dev/null +++ b/tests/test_review_verifier_self_refutation.py @@ -0,0 +1,118 @@ +"""The verifier does not invalidate a finding its own reason confirms (#536). + +In the first sample validation (#505) all three unpinned `:latest` image findings were +INVALIDATED although the verifier's reason confirmed the defect: it filed the finding's own +verification criterion, or its fix, as the invalidation criterion it matched. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from devops_cli.ai.review.verification import _apply_single_finding_verification +from devops_cli.ai.review_schema import Finding + +NOW = "2026-09-25T00:00:00+00:00" + + +def _unpinned(image: str = "alpine") -> Finding: + return Finding( + severity="MEDIUM", + location="docker/Dockerfile:6", + title="Unpinned base image tag", + description=f"`FROM {image}:latest` pulls whatever the tag points at when built.", + fix=f"Pin {image} to a specific version tag such as {image}:1.22.3 and verify its checksum.", + verification_criteria=["The FROM directive uses the 'latest' tag"], + invalidation_criteria=["The base image is pinned to a version or digest"], + ) + + +def _outcome(finding: Finding, verdict: dict[str, Any]) -> tuple[str, bool]: + result = _apply_single_finding_verification(finding, verdict, NOW) + return result.status, result.reportable + + +@pytest.mark.parametrize( + "verdict", + [ + # The verification criterion, filed as the invalidation it matched. + { + "status": "INVALIDATED", + "invalidated": True, + "reason": "Line 6 contains `FROM alpine:latest`, which uses the unpinned `latest` tag.", + "invalidated_criteria_matched": [ + "The FROM directive still uses 'latest' as the image tag." + ], + }, + { + "status": "INVALIDATED", + "reason": "Line 6 specifies 'FROM debian:latest', which uses the ':latest' tag.", + "invalidated_criteria_matched": [ + "Verify that the FROM directive uses the 'latest' tag." + ], + }, + # The fix, filed as the invalidation it matched. + { + "status": "INVALIDATED", + "reason": "Using the latest tag makes builds non-deterministic.", + "invalidated_criteria_matched": [ + "The FROM directive contains a specific version tag (e.g., `alpine:1.22.3`) and " + "a checksum." + ], + }, + # No criteria at all, and a reason that states the defect. + { + "status": "INVALIDATED", + "reason": "The FROM directive uses the latest tag on line 6.", + "invalidated_criteria_matched": [], + }, + ], +) +def test_an_invalidation_that_restates_the_defect_keeps_the_finding( + verdict: dict[str, Any], +) -> None: + """Verify the finding stays in the report, unverified, not refuted.""" + assert _outcome(_unpinned(), verdict) == ("UNVERIFIED", True) + + +@pytest.mark.parametrize( + "verdict", + [ + { + "status": "INVALIDATED", + "reason": "The image is pinned by digest on line 6: `FROM alpine@sha256:4bc...`.", + "invalidated_criteria_matched": ["The base image is pinned to a version or digest"], + }, + { + "invalidated": True, + "reason": "This Dockerfile is a test fixture that is never built.", + "invalidated_criteria_matched": ["The file is a test fixture"], + }, + # A genuine refutation beside a restatement still refutes. + { + "status": "INVALIDATED", + "reason": "Line 6 is `FROM alpine:3.20@sha256:4bc...`; the tag is not latest.", + "invalidated_criteria_matched": [ + "The FROM directive still uses 'latest' as the image tag.", + "The base image is pinned to a version or digest", + ], + }, + ], +) +def test_a_genuine_refutation_still_invalidates(verdict: dict[str, Any]) -> None: + """Verify evidence against the finding still removes it.""" + assert _outcome(_unpinned(), verdict) == ("INVALIDATED", False) + + +def test_a_confirmation_is_left_as_it_was() -> None: + """Verify a verdict that confirms the finding is untouched.""" + verdict = { + "verified": True, + "status": "VERIFIED", + "reason": "Line 6 uses `alpine:latest`.", + "verified_criteria_matched": ["The FROM directive uses the 'latest' tag"], + } + + assert _outcome(_unpinned(), verdict) == ("VERIFIED", True)