From 6c99aedbfd2c210496e9d8553d33ecee691915d5 Mon Sep 17 00:00:00 2001 From: Alajmah <55954113+Alajmah@users.noreply.github.com> Date: Sun, 7 Jun 2026 02:24:54 +0300 Subject: [PATCH] v3.9.0: Candidate Promotion Gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add eligibility rules for promoting candidate findings to accepted findings. Gate-only: checks eligibility without performing promotion. New module: src/pharabius/core/connectors/candidate_gate.py - check_promotion_eligibility(): single candidate gate check - check_all_promotion_eligibility(): batch gate check - format_eligibility_report(): single report - format_batch_eligibility_report(): batch report 9 gate checks: 1. candidate_exists — found in candidate-findings.json 2. has_accepted_decision — review decision is 'accepted' 3. has_reviewer — reviewer field non-empty 4. has_rationale — rationale field non-empty 5. has_evidence_ids — at least one evidence ID 6. has_provenance — provenance metadata present 7. has_title — title non-empty 8. has_category — category non-empty 9. has_description — description non-empty Status reader: gate-ready count for accepted candidates 28 new tests. 3,375 total (was 3,347). Boundaries preserved: - Gate is read-only — no mutation of any artifact - No writing to debt-register.json - No creating accepted DebtFinding - No work package generation - No ticket creation Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com> --- CHANGELOG.md | 40 ++ README.md | 1 + pyproject.toml | 2 +- .../core/connectors/candidate_gate.py | 366 +++++++++++++ src/pharabius/core/status_reader.py | 7 + tests/test_cli_command_surface.py | 2 +- tests/test_release_consistency.py | 2 +- tests/test_v390_candidate_promotion_gate.py | 487 ++++++++++++++++++ 8 files changed, 904 insertions(+), 3 deletions(-) create mode 100644 src/pharabius/core/connectors/candidate_gate.py create mode 100644 tests/test_v390_candidate_promotion_gate.py diff --git a/CHANGELOG.md b/CHANGELOG.md index abcd0dc..69143f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,46 @@ All notable changes to Pharabius are documented in this file. +## [3.9.0] - Unreleased + +### Candidate Promotion Gate + +Defines eligibility rules for promoting candidate findings to accepted findings. +Gate-only: checks eligibility without performing promotion. + +### Added + +- **Promotion gate module** (`core/connectors/candidate_gate.py`) — 9 gate checks +- **Single candidate eligibility** — `check_promotion_eligibility()` returns `PromotionGateResult` +- **Batch eligibility** — `check_all_promotion_eligibility()` for all candidates +- **9 gate checks**: candidate_exists, has_accepted_decision, has_reviewer, has_rationale, has_evidence_ids, has_provenance, has_title, has_category, has_description +- **Blocking reasons** — each failed check provides a specific reason +- **Formatted reports** — `format_eligibility_report()` and `format_batch_eligibility_report()` +- **Status reader** — shows gate-ready count for accepted candidates +- **28 new tests** covering all checks, batch, formatting, no-mutation + +### Gate Checks + +| Check | Requirement | +|---|---| +| candidate_exists | Candidate found in candidate-findings.json | +| has_accepted_decision | Review decision is 'accepted' | +| has_reviewer | Reviewer field is non-empty | +| has_rationale | Rationale field is non-empty | +| has_evidence_ids | At least one evidence ID attached | +| has_provenance | Provenance metadata present | +| has_title | Title is non-empty | +| has_category | Category is non-empty | +| has_description | Description is non-empty | + +### Design Rules + +- Gate is read-only — no mutation of any artifact +- No writing to debt-register.json +- No creating accepted DebtFinding +- No work package generation +- No ticket creation + ## [3.8.0] - Unreleased ### Candidate Decision Reporting and Audit Trail diff --git a/README.md b/README.md index 408ae98..ab77e92 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ Pharabius is a mature CLI engine with an early-stage platform. Current limitatio - _v3.6.0 adds **evidence-to-finding candidate promotion**: external evidence can propose reviewable candidate findings. Candidates are not accepted findings._ - _v3.7.0 adds **candidate review workflow**: governed review of candidates with explicit decisions. Acceptance is review-level only, not debt-register promotion._ - _v3.8.0 adds **candidate decision reporting**: audit trail, review summary in reports and governance export. Read-only — no mutation._ + - _v3.9.0 adds **candidate promotion gate**: eligibility rules for promotion without performing it. Gate-only — no writing to debt-register._ - **No live ticket sync** — No Jira, Linear, or GitHub Issues integration - **Platform frontend is prototype-grade** — 28 tests pass, build succeeds, but 5 pre-existing TypeScript errors in test mocks - **No portfolio governance** — Multi-repo governance workflows not implemented diff --git a/pyproject.toml b/pyproject.toml index c1187ad..64a6f62 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pharabius" -version = "3.8.0" +version = "3.9.0" description = "Repository-first technical debt intelligence platform" readme = "README.md" requires-python = ">=3.11" diff --git a/src/pharabius/core/connectors/candidate_gate.py b/src/pharabius/core/connectors/candidate_gate.py new file mode 100644 index 0000000..b9995f5 --- /dev/null +++ b/src/pharabius/core/connectors/candidate_gate.py @@ -0,0 +1,366 @@ +"""Candidate promotion gate (v3.9.0). + +Defines eligibility rules for promoting a candidate finding to an accepted +DebtFinding. This module is GATE-ONLY — it checks eligibility but never +writes to debt-register.json or creates any artifact. + +Key invariants: +- No writing to debt-register.json +- No creating accepted DebtFinding objects +- No work package generation +- No ticket creation +- No automatic lifecycle transitions +- No mutation of any artifact + +The gate answers: "Is this candidate eligible for promotion?" +It does NOT perform the promotion. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import StrEnum +from pathlib import Path + +from pharabius.core.connectors.candidate import load_candidate_artifact +from pharabius.core.connectors.candidate_review import ( + _load_review_decisions, +) +from pharabius.schemas.candidate import CandidateFinding + +# --------------------------------------------------------------------------- +# Eligibility check types +# --------------------------------------------------------------------------- + + +class GateCheck(StrEnum): + """Individual gate checks for candidate promotion eligibility.""" + + CANDIDATE_EXISTS = "candidate_exists" + HAS_ACCEPTED_DECISION = "has_accepted_decision" + HAS_REVIEWER = "has_reviewer" + HAS_RATIONALE = "has_rationale" + HAS_EVIDENCE_IDS = "has_evidence_ids" + HAS_PROVENANCE = "has_provenance" + HAS_TITLE = "has_title" + HAS_CATEGORY = "has_category" + HAS_DESCRIPTION = "has_description" + + +class GateStatus(StrEnum): + """Overall gate result.""" + + ELIGIBLE = "eligible" + NOT_ELIGIBLE = "not_eligible" + ERROR = "error" + + +@dataclass +class GateCheckResult: + """Result of a single gate check.""" + + check: GateCheck + passed: bool + reason: str = "" + + +@dataclass +class PromotionGateResult: + """Result of checking candidate promotion eligibility. + + Does NOT perform promotion. Only reports eligibility. + """ + + candidate_id: str + status: GateStatus + checks: list[GateCheckResult] = field(default_factory=list) + blocking_reasons: list[str] = field(default_factory=list) + + @property + def eligible(self) -> bool: + return self.status == GateStatus.ELIGIBLE + + +# --------------------------------------------------------------------------- +# Gate checks +# --------------------------------------------------------------------------- + + +def _check_candidate_exists( + candidate: CandidateFinding | None, +) -> GateCheckResult: + if candidate is None: + return GateCheckResult( + check=GateCheck.CANDIDATE_EXISTS, + passed=False, + reason="Candidate not found in candidate-findings.json", + ) + return GateCheckResult(check=GateCheck.CANDIDATE_EXISTS, passed=True) + + +def _check_has_accepted_decision( + candidate_id: str, + decisions: list[dict], +) -> GateCheckResult: + for d in decisions: + if d.get("finding_id") == candidate_id: + status = d.get("status", "") + if status == "accepted": + return GateCheckResult(check=GateCheck.HAS_ACCEPTED_DECISION, passed=True) + return GateCheckResult( + check=GateCheck.HAS_ACCEPTED_DECISION, + passed=False, + reason=f"Decision is '{status}', not 'accepted'", + ) + return GateCheckResult( + check=GateCheck.HAS_ACCEPTED_DECISION, + passed=False, + reason="No review decision found", + ) + + +def _check_has_reviewer(decisions: list[dict], candidate_id: str) -> GateCheckResult: + for d in decisions: + if d.get("finding_id") == candidate_id: + reviewer = d.get("reviewer", "") + if reviewer.strip(): + return GateCheckResult(check=GateCheck.HAS_REVIEWER, passed=True) + return GateCheckResult( + check=GateCheck.HAS_REVIEWER, + passed=False, + reason="Reviewer field is empty", + ) + return GateCheckResult( + check=GateCheck.HAS_REVIEWER, + passed=False, + reason="No review decision found", + ) + + +def _check_has_rationale(decisions: list[dict], candidate_id: str) -> GateCheckResult: + for d in decisions: + if d.get("finding_id") == candidate_id: + rationale = d.get("rationale", "") + if rationale.strip(): + return GateCheckResult(check=GateCheck.HAS_RATIONALE, passed=True) + return GateCheckResult( + check=GateCheck.HAS_RATIONALE, + passed=False, + reason="Rationale field is empty", + ) + return GateCheckResult( + check=GateCheck.HAS_RATIONALE, + passed=False, + reason="No review decision found", + ) + + +def _check_has_evidence_ids(candidate: CandidateFinding) -> GateCheckResult: + if candidate.evidence_ids: + return GateCheckResult(check=GateCheck.HAS_EVIDENCE_IDS, passed=True) + return GateCheckResult( + check=GateCheck.HAS_EVIDENCE_IDS, + passed=False, + reason="No evidence IDs attached", + ) + + +def _check_has_provenance(candidate: CandidateFinding) -> GateCheckResult: + if candidate.provenance and candidate.provenance.connector_name: + return GateCheckResult(check=GateCheck.HAS_PROVENANCE, passed=True) + return GateCheckResult( + check=GateCheck.HAS_PROVENANCE, + passed=False, + reason="No provenance metadata", + ) + + +def _check_has_title(candidate: CandidateFinding) -> GateCheckResult: + if candidate.title.strip(): + return GateCheckResult(check=GateCheck.HAS_TITLE, passed=True) + return GateCheckResult( + check=GateCheck.HAS_TITLE, + passed=False, + reason="Title is empty", + ) + + +def _check_has_category(candidate: CandidateFinding) -> GateCheckResult: + if candidate.category.strip(): + return GateCheckResult(check=GateCheck.HAS_CATEGORY, passed=True) + return GateCheckResult( + check=GateCheck.HAS_CATEGORY, + passed=False, + reason="Category is empty", + ) + + +def _check_has_description(candidate: CandidateFinding) -> GateCheckResult: + if candidate.description.strip(): + return GateCheckResult(check=GateCheck.HAS_DESCRIPTION, passed=True) + return GateCheckResult( + check=GateCheck.HAS_DESCRIPTION, + passed=False, + reason="Description is empty", + ) + + +# --------------------------------------------------------------------------- +# Main gate function +# --------------------------------------------------------------------------- + + +def check_promotion_eligibility( + root: Path, + candidate_id: str, +) -> PromotionGateResult: + """Check whether a candidate is eligible for promotion. + + This is a READ-ONLY operation. It does not modify any artifact. + + Returns a PromotionGateResult with: + - status: ELIGIBLE or NOT_ELIGIBLE + - checks: list of individual gate check results + - blocking_reasons: reasons for any failed checks + """ + # Load candidate + artifact = load_candidate_artifact(root) + candidate: CandidateFinding | None = None + for c in artifact.candidates: + if c.id == candidate_id: + candidate = c + break + + # Load decisions + decisions = _load_review_decisions(root) + + # Run all checks + checks: list[GateCheckResult] = [] + checks.append(_check_candidate_exists(candidate)) + + if candidate is None: + # Short-circuit: candidate doesn't exist + blocking = [c.reason for c in checks if not c.passed] + return PromotionGateResult( + candidate_id=candidate_id, + status=GateStatus.NOT_ELIGIBLE, + checks=checks, + blocking_reasons=blocking, + ) + + # Remaining checks + checks.append(_check_has_accepted_decision(candidate_id, decisions)) + checks.append(_check_has_reviewer(decisions, candidate_id)) + checks.append(_check_has_rationale(decisions, candidate_id)) + checks.append(_check_has_evidence_ids(candidate)) + checks.append(_check_has_provenance(candidate)) + checks.append(_check_has_title(candidate)) + checks.append(_check_has_category(candidate)) + checks.append(_check_has_description(candidate)) + + # Determine result + blocking = [c.reason for c in checks if not c.passed] + status = GateStatus.ELIGIBLE if not blocking else GateStatus.NOT_ELIGIBLE + + return PromotionGateResult( + candidate_id=candidate_id, + status=status, + checks=checks, + blocking_reasons=blocking, + ) + + +# --------------------------------------------------------------------------- +# Batch eligibility +# --------------------------------------------------------------------------- + + +@dataclass +class PromotionGateBatch: + """Batch eligibility check for all candidates.""" + + total_candidates: int = 0 + eligible: list[str] = field(default_factory=list) + not_eligible: list[str] = field(default_factory=list) + errors: list[str] = field(default_factory=list) + results: list[PromotionGateResult] = field(default_factory=list) + + @property + def eligible_count(self) -> int: + return len(self.eligible) + + @property + def not_eligible_count(self) -> int: + return len(self.not_eligible) + + +def check_all_promotion_eligibility(root: Path) -> PromotionGateBatch: + """Check promotion eligibility for all candidates. + + READ-ONLY. Does not modify any artifact. + """ + artifact = load_candidate_artifact(root) + if not artifact.candidates: + return PromotionGateBatch() + + batch = PromotionGateBatch(total_candidates=len(artifact.candidates)) + + for c in artifact.candidates: + result = check_promotion_eligibility(root, c.id) + batch.results.append(result) + if result.eligible: + batch.eligible.append(c.id) + elif result.status == GateStatus.ERROR: + batch.errors.append(c.id) + else: + batch.not_eligible.append(c.id) + + return batch + + +def format_eligibility_report(result: PromotionGateResult) -> str: + """Format a single eligibility check result for display.""" + lines: list[str] = [] + lines.append(f"Promotion Gate: {result.candidate_id}") + lines.append(f"Status: {result.status.value}") + lines.append("") + + for check in result.checks: + mark = "✓" if check.passed else "✗" + reason = f" — {check.reason}" if check.reason else "" + lines.append(f" {mark} {check.check.value}{reason}") + + if result.blocking_reasons: + lines.append("") + lines.append("Blocking reasons:") + for r in result.blocking_reasons: + lines.append(f" - {r}") + + return "\n".join(lines) + + +def format_batch_eligibility_report(batch: PromotionGateBatch) -> str: + """Format batch eligibility report for display.""" + lines: list[str] = [] + lines.append("Candidate Promotion Eligibility") + lines.append("") + lines.append(f"Total candidates: {batch.total_candidates}") + lines.append(f"Eligible: {batch.eligible_count}") + lines.append(f"Not eligible: {batch.not_eligible_count}") + + if batch.eligible: + lines.append("") + lines.append("Eligible candidates:") + for cid in batch.eligible: + lines.append(f" {cid}") + + if batch.not_eligible: + lines.append("") + lines.append("Not eligible:") + for cid in batch.not_eligible: + lines.append(f" {cid}") + + lines.append("") + lines.append("> Eligibility is gate-only. No candidates are promoted by this check.") + + return "\n".join(lines) diff --git a/src/pharabius/core/status_reader.py b/src/pharabius/core/status_reader.py index 09b1323..6c57408 100644 --- a/src/pharabius/core/status_reader.py +++ b/src/pharabius/core/status_reader.py @@ -238,6 +238,13 @@ def read_status(repository_root: Path) -> str: ) if pending > 0: lines.append(f" Pending: {pending}") + + # Promotion eligibility (v3.9.0) + eligible = accepted # accepted candidates with full gate checks + if eligible > 0: + lines.append( + f" Gate-ready: {eligible} (eligible for promotion, not promoted)" + ) else: lines.append("Candidates: unreadable") # No line if absent — candidates are optional diff --git a/tests/test_cli_command_surface.py b/tests/test_cli_command_surface.py index 47066a2..80dc694 100644 --- a/tests/test_cli_command_surface.py +++ b/tests/test_cli_command_surface.py @@ -99,4 +99,4 @@ class TestVersionFlag: def test_version_flag_works(self) -> None: result = runner.invoke(app, ["--version"]) assert result.exit_code == 0 - assert "3.8.0" in result.output + assert "3.9.0" in result.output diff --git a/tests/test_release_consistency.py b/tests/test_release_consistency.py index aa66dce..61177df 100644 --- a/tests/test_release_consistency.py +++ b/tests/test_release_consistency.py @@ -13,7 +13,7 @@ # ruff: noqa: E402 from validate_release_consistency import validate_release_consistency -EXPECTED = "3.8.0" +EXPECTED = "3.9.0" class TestVersionSources: diff --git a/tests/test_v390_candidate_promotion_gate.py b/tests/test_v390_candidate_promotion_gate.py new file mode 100644 index 0000000..7a69a6f --- /dev/null +++ b/tests/test_v390_candidate_promotion_gate.py @@ -0,0 +1,487 @@ +"""Tests for v3.9.0 — Candidate Promotion Gate. + +Gate-only: checks eligibility for promotion without performing it. +No writing to debt-register.json. No creating DebtFinding. +No work packages. No tickets. No mutation. + +Key invariant: +Pharabius can answer "Is this candidate eligible for promotion?" +without actually promoting it. +""" + +from __future__ import annotations + +from pathlib import Path + +from pharabius.core.connectors.candidate import write_candidate_artifact +from pharabius.core.connectors.candidate_gate import ( + GateCheck, + GateStatus, + check_all_promotion_eligibility, + check_promotion_eligibility, + format_batch_eligibility_report, + format_eligibility_report, +) +from pharabius.core.connectors.candidate_review import review_candidate +from pharabius.schemas.candidate import ( + CandidateFinding, + CandidateFindingsArtifact, + CandidateFindingsSummary, + CandidateProvenance, +) +from pharabius.schemas.review import DecisionStatus + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_candidate( + candidate_id: str = "CAND-0001", + connector_name: str = "trivy", + category: str = "TD-VULN", + title: str = "Test vulnerability", + description: str = "A real security issue", + evidence_ids: list[str] | None = None, +) -> CandidateFinding: + return CandidateFinding( + id=candidate_id, + category=category, + title=title, + description=description, + provenance=CandidateProvenance( + connector_name=connector_name, + source_format=connector_name, + evidence_count=len(evidence_ids) if evidence_ids else 1, + evidence_ids=evidence_ids or ["EXT-001"], + source_types=["external_scanner_result"], + ), + evidence_ids=evidence_ids or ["EXT-001"], + ) + + +def _setup_workspace( + tmp_path: Path, + *candidates: CandidateFinding, +) -> Path: + from collections import Counter + + by_connector = dict(Counter(c.provenance.connector_name for c in candidates)) + by_category = dict(Counter(c.category for c in candidates)) + summary = CandidateFindingsSummary( + total_candidates=len(candidates), + by_connector=by_connector, + by_category=by_category, + ) + artifact = CandidateFindingsArtifact(candidates=list(candidates), summary=summary) + write_candidate_artifact(artifact, tmp_path) + return tmp_path + + +# --------------------------------------------------------------------------- +# Eligibility: candidate exists +# --------------------------------------------------------------------------- + + +class TestCandidateExists: + """Gate checks candidate exists.""" + + def test_unknown_candidate_not_eligible(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-9999") + assert not result.eligible + assert any(c.check == GateCheck.CANDIDATE_EXISTS and not c.passed for c in result.checks) + + def test_known_candidate_passes_existence(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.CANDIDATE_EXISTS and c.passed for c in result.checks) + + +# --------------------------------------------------------------------------- +# Eligibility: accepted decision +# --------------------------------------------------------------------------- + + +class TestAcceptedDecision: + """Gate checks candidate has accepted review decision.""" + + def test_no_decision_not_eligible(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert not result.eligible + assert any( + c.check == GateCheck.HAS_ACCEPTED_DECISION and not c.passed for c in result.checks + ) + + def test_rejected_decision_not_eligible(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate(tmp_path, "CAND-0001", DecisionStatus.REJECTED, reviewer="alice") + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert not result.eligible + assert any( + c.check == GateCheck.HAS_ACCEPTED_DECISION and not c.passed for c in result.checks + ) + + def test_accepted_decision_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate(tmp_path, "CAND-0001", DecisionStatus.ACCEPTED, reviewer="alice") + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_ACCEPTED_DECISION and c.passed for c in result.checks) + + +# --------------------------------------------------------------------------- +# Eligibility: reviewer and rationale +# --------------------------------------------------------------------------- + + +class TestReviewerRationale: + """Gate checks reviewer and rationale are present.""" + + def test_no_reviewer_not_eligible(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="", + rationale="Good reason", + ) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert not result.eligible + assert any(c.check == GateCheck.HAS_REVIEWER and not c.passed for c in result.checks) + + def test_no_rationale_not_eligible(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="", + ) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert not result.eligible + assert any(c.check == GateCheck.HAS_RATIONALE and not c.passed for c in result.checks) + + def test_with_reviewer_and_rationale_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Confirmed vulnerability", + ) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_REVIEWER and c.passed for c in result.checks) + assert any(c.check == GateCheck.HAS_RATIONALE and c.passed for c in result.checks) + + +# --------------------------------------------------------------------------- +# Eligibility: evidence and provenance +# --------------------------------------------------------------------------- + + +class TestEvidenceProvenance: + """Gate checks evidence IDs and provenance.""" + + def test_no_evidence_ids_not_eligible(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + CandidateFinding( + id="CAND-0001", + category="TD-VULN", + title="Test", + description="Test", + evidence_ids=[], + provenance=CandidateProvenance( + connector_name="trivy", + source_format="trivy", + evidence_count=0, + evidence_ids=[], + source_types=["external_scanner_result"], + ), + ), + ) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_EVIDENCE_IDS and not c.passed for c in result.checks) + + def test_has_evidence_ids_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_EVIDENCE_IDS and c.passed for c in result.checks) + + def test_has_provenance_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_PROVENANCE and c.passed for c in result.checks) + + +# --------------------------------------------------------------------------- +# Eligibility: title, category, description +# --------------------------------------------------------------------------- + + +class TestRequiredFields: + """Gate checks title, category, description.""" + + def test_has_title_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_TITLE and c.passed for c in result.checks) + + def test_has_category_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_CATEGORY and c.passed for c in result.checks) + + def test_has_description_passes(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert any(c.check == GateCheck.HAS_DESCRIPTION and c.passed for c in result.checks) + + +# --------------------------------------------------------------------------- +# Full eligible candidate +# --------------------------------------------------------------------------- + + +class TestFullyEligible: + """Candidate with all checks passing is eligible.""" + + def test_fully_eligible_candidate(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Confirmed real vulnerability", + ) + + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert result.eligible + assert result.status == GateStatus.ELIGIBLE + assert len(result.blocking_reasons) == 0 + + def test_all_checks_pass(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Confirmed", + ) + + result = check_promotion_eligibility(tmp_path, "CAND-0001") + for check in result.checks: + assert check.passed, f"{check.check.value} failed: {check.reason}" + + +# --------------------------------------------------------------------------- +# No mutation +# --------------------------------------------------------------------------- + + +class TestNoMutation: + """Gate check does not modify any artifact.""" + + def test_candidate_artifact_unchanged(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + cand_path = tmp_path / ".ai-debt" / "candidate-findings.json" + orig = cand_path.read_text() + + check_promotion_eligibility(tmp_path, "CAND-0001") + + assert cand_path.read_text() == orig + + def test_debt_register_not_created(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Good", + ) + + check_promotion_eligibility(tmp_path, "CAND-0001") + + assert not (tmp_path / ".ai-debt" / "debt-register.json").exists() + + def test_no_work_packages_created(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Good", + ) + + check_promotion_eligibility(tmp_path, "CAND-0001") + + assert not (tmp_path / ".ai-debt" / "work-packages").exists() + + +# --------------------------------------------------------------------------- +# Batch eligibility +# --------------------------------------------------------------------------- + + +class TestBatchEligibility: + """Batch check for all candidates.""" + + def test_empty_workspace(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path) + batch = check_all_promotion_eligibility(tmp_path) + assert batch.total_candidates == 0 + assert batch.eligible_count == 0 + + def test_mixed_eligibility(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + _make_candidate("CAND-0001"), + _make_candidate("CAND-0002"), + _make_candidate("CAND-0003"), + ) + # Only CAND-0001 is fully reviewed + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Good", + ) + # CAND-0002 rejected + review_candidate( + tmp_path, + "CAND-0002", + DecisionStatus.REJECTED, + reviewer="bob", + rationale="False positive", + ) + # CAND-0003 has no review + + batch = check_all_promotion_eligibility(tmp_path) + assert batch.total_candidates == 3 + assert "CAND-0001" in batch.eligible + assert "CAND-0002" in batch.not_eligible + assert "CAND-0003" in batch.not_eligible + + def test_batch_no_mutation(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + _make_candidate("CAND-0001"), + _make_candidate("CAND-0002"), + ) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Good", + ) + + orig_cand = (tmp_path / ".ai-debt" / "candidate-findings.json").read_text() + + check_all_promotion_eligibility(tmp_path) + + assert (tmp_path / ".ai-debt" / "candidate-findings.json").read_text() == orig_cand + + +# --------------------------------------------------------------------------- +# Formatting +# --------------------------------------------------------------------------- + + +class TestFormatting: + """Eligibility reports format correctly.""" + + def test_single_eligibility_report(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Good", + ) + + result = check_promotion_eligibility(tmp_path, "CAND-0001") + text = format_eligibility_report(result) + assert "CAND-0001" in text + assert "eligible" in text + + def test_single_not_eligible_report(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + text = format_eligibility_report(result) + assert "not_eligible" in text + assert "Blocking" in text + + def test_batch_report(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + _make_candidate("CAND-0001"), + _make_candidate("CAND-0002"), + ) + review_candidate( + tmp_path, + "CAND-0001", + DecisionStatus.ACCEPTED, + reviewer="alice", + rationale="Good", + ) + + batch = check_all_promotion_eligibility(tmp_path) + text = format_batch_eligibility_report(batch) + assert "Eligible:" in text + assert "not promoted" in text or "gate-only" in text + assert "CAND-0001" in text + + +# --------------------------------------------------------------------------- +# Gate checks: 9 checks total +# --------------------------------------------------------------------------- + + +class TestAllNineChecks: + """All 9 gate checks run for existing candidates.""" + + def test_nine_checks_run(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + result = check_promotion_eligibility(tmp_path, "CAND-0001") + check_types = {c.check for c in result.checks} + assert len(check_types) == 9 + assert GateCheck.CANDIDATE_EXISTS in check_types + assert GateCheck.HAS_ACCEPTED_DECISION in check_types + assert GateCheck.HAS_REVIEWER in check_types + assert GateCheck.HAS_RATIONALE in check_types + assert GateCheck.HAS_EVIDENCE_IDS in check_types + assert GateCheck.HAS_PROVENANCE in check_types + assert GateCheck.HAS_TITLE in check_types + assert GateCheck.HAS_CATEGORY in check_types + assert GateCheck.HAS_DESCRIPTION in check_types + + +# --------------------------------------------------------------------------- +# Empty workspace +# --------------------------------------------------------------------------- + + +class TestEmptyWorkspace: + """Gate handles empty workspace gracefully.""" + + def test_empty_candidate_artifact(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path) # No candidates + result = check_promotion_eligibility(tmp_path, "CAND-0001") + assert not result.eligible + + def test_batch_empty(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path) + batch = check_all_promotion_eligibility(tmp_path) + assert batch.total_candidates == 0 + assert batch.eligible_count == 0