diff --git a/CHANGELOG.md b/CHANGELOG.md index 69143f1..1a28b29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,51 @@ All notable changes to Pharabius are documented in this file. +## [3.10.0] - Unreleased + +### Candidate Promotion Execution + +First mutation wave: promotes eligible candidates to accepted DebtFindings. +Requires v3.9.0 gate pass. Preserves candidate lineage. Append-only audit. + +### Added + +- **Promotion execution** (`core/connectors/candidate_promotion.py`) — `promote_candidate()` function +- **Gate requirement** — promotion fails if gate checks don't pass +- **Candidate lineage** — `_promotion_lineage` metadata in `risk_breakdown` +- **Duplicate promotion guard** — each candidate can only be promoted once +- **Existing register preserved** — promotion appends, doesn't overwrite +- **Lifecycle history** — promotion appends `candidate_promotion` entry +- **Summary recalculation** — register summary updated after promotion +- **25 new tests** covering promotion, gate, lineage, guard, non-mutation + +### Promotion Flow + +```text +1. Check v3.9.0 gate (9 checks) — must all pass +2. Verify not already promoted (duplicate guard) +3. Convert CandidateFinding → DebtFinding with lineage +4. Append to existing debt-register.json +5. Recalculate register summary +6. Append lifecycle entry (CandidateAccepted → Detected) +``` + +### Lineage Metadata + +Every promoted finding carries `_promotion_lineage` in `risk_breakdown`: +- candidate_id, connector_name, source_format +- original_evidence_ids, promoted_at +- reviewer, review_rationale, reviewed_at + +### Design Rules + +- Promotion is explicit — no auto-promotion +- Promotion requires gate pass — all 9 checks must pass +- Candidate-findings.json is NOT deleted or rewritten +- Review decisions are NOT rewritten +- No auto-generated work packages, tickets, or remediation plans +- One promotion per candidate + ## [3.9.0] - Unreleased ### Candidate Promotion Gate diff --git a/README.md b/README.md index ab77e92..cb948b4 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ Pharabius is a mature CLI engine with an early-stage platform. Current limitatio - _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._ + - _v3.10.0 adds **candidate promotion execution**: promotes eligible candidates to accepted findings with lineage. First mutation wave — requires gate pass, preserves source artifacts._ - **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 64a6f62..580433c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pharabius" -version = "3.9.0" +version = "3.10.0" description = "Repository-first technical debt intelligence platform" readme = "README.md" requires-python = ">=3.11" diff --git a/src/pharabius/core/connectors/candidate_promotion.py b/src/pharabius/core/connectors/candidate_promotion.py new file mode 100644 index 0000000..5993aa7 --- /dev/null +++ b/src/pharabius/core/connectors/candidate_promotion.py @@ -0,0 +1,276 @@ +"""Candidate promotion execution (v3.10.0). + +Promotes an eligible candidate finding to an accepted DebtFinding. +Requires gate pass from v3.9.0. Appends to existing debt-register.json. + +Key invariants: +- Promotion must be explicit — no auto-promotion +- Promotion must require gate pass +- Promotion must preserve candidate lineage in risk_breakdown +- Promotion must not delete or rewrite candidate-findings.json +- Promotion must not auto-generate work packages, tickets, or remediation +- Promotion must not rewrite historical review decisions +- One promotion per candidate — duplicate guard +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +from pharabius.core.connectors.candidate import load_candidate_artifact +from pharabius.core.connectors.candidate_gate import ( + check_promotion_eligibility, +) +from pharabius.core.connectors.candidate_review import ( + _load_lifecycle_history, + _load_review_decisions, + _save_lifecycle_history, +) +from pharabius.schemas.candidate import CandidateFinding +from pharabius.schemas.finding import DebtFinding, DebtRegister, DebtRegisterSummary +from pharabius.schemas.lifecycle import LifecycleEntry + + +class PromotionError(Exception): + """Error during candidate promotion.""" + + +# --------------------------------------------------------------------------- +# Lineage metadata keys +# --------------------------------------------------------------------------- + +LINEAGE_KEY = "_promotion_lineage" + + +def _build_lineage_metadata( + candidate: CandidateFinding, + decision: dict[str, Any], +) -> dict[str, Any]: + """Build lineage metadata for promoted finding.""" + return { + "source": "candidate_promotion", + "candidate_id": candidate.id, + "connector_name": candidate.provenance.connector_name, + "source_format": candidate.provenance.source_format, + "original_evidence_ids": candidate.provenance.evidence_ids, + "promoted_at": datetime.now(UTC).replace(microsecond=0).isoformat(), + "reviewer": decision.get("reviewer", ""), + "review_rationale": decision.get("rationale", ""), + "reviewed_at": decision.get("reviewed_at", ""), + } + + +# --------------------------------------------------------------------------- +# Finding ID generation +# --------------------------------------------------------------------------- + + +def _next_finding_id(register: DebtRegister, category: str) -> str: + """Generate the next finding ID for a given category.""" + existing_ids = {f.id for f in register.findings} + counter = 0 + while True: + counter += 1 + candidate_id = f"{category}-{counter:03d}" + if candidate_id not in existing_ids: + return candidate_id + + +# --------------------------------------------------------------------------- +# Load / save register (append-safe) +# --------------------------------------------------------------------------- + + +def _load_debt_register(root: Path) -> DebtRegister: + """Load existing debt-register.json. Returns empty if missing.""" + path = root / ".ai-debt" / "debt-register.json" + if not path.exists(): + return DebtRegister() + try: + return DebtRegister.model_validate_json(path.read_text(encoding="utf-8")) + except Exception: + return DebtRegister() + + +def _resummary(register: DebtRegister) -> None: + """Recalculate register summary from findings list.""" + from collections import Counter + + findings = register.findings + severity_counts = Counter(f.severity.lower() for f in findings) + category_counts = Counter(f.category for f in findings) + tech_debt = sum(1 for f in findings if f.issue_type != "advisory") + advisory = sum(1 for f in findings if f.issue_type == "advisory") + + register.summary = DebtRegisterSummary( + total_findings=len(findings), + technical_debt_count=tech_debt, + advisory_count=advisory, + critical=severity_counts["critical"], + high=severity_counts["high"], + medium=severity_counts["medium"], + low=severity_counts["low"], + top_categories=[c for c, _ in category_counts.most_common(5)], + ) + + +def _save_debt_register(root: Path, register: DebtRegister) -> Path: + """Write debt-register.json.""" + path = root / ".ai-debt" / "debt-register.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + register.model_dump_json(indent=2) + "\n", + encoding="utf-8", + ) + return path + + +# --------------------------------------------------------------------------- +# Duplicate promotion guard +# --------------------------------------------------------------------------- + + +def _check_not_already_promoted( + register: DebtRegister, + candidate_id: str, +) -> None: + """Guard against duplicate promotion.""" + for f in register.findings: + lineage = f.risk_breakdown.get(LINEAGE_KEY, {}) + if lineage.get("candidate_id") == candidate_id: + msg = ( + f"Candidate {candidate_id} already promoted to " + f"finding {f.id}. Each candidate may only be promoted once." + ) + raise PromotionError(msg) + + +# --------------------------------------------------------------------------- +# Main: promote_candidate +# --------------------------------------------------------------------------- + + +def promote_candidate( + root: Path, + candidate_id: str, +) -> DebtFinding: + """Promote an eligible candidate to an accepted DebtFinding. + + Steps: + 1. Check promotion gate (v3.9.0) — must pass all 9 checks + 2. Verify not already promoted + 3. Convert candidate to DebtFinding with lineage + 4. Append to existing debt-register.json + 5. Append lifecycle entry + 6. Return the new DebtFinding + + Raises PromotionError for: + - Gate check failures + - Duplicate promotions + - Missing artifacts + + Does NOT: + - Delete or rewrite candidate-findings.json + - Auto-generate work packages + - Create tickets + - Modify historical review decisions + """ + # Step 1: Gate check + gate_result = check_promotion_eligibility(root, candidate_id) + if not gate_result.eligible: + reasons = "; ".join(gate_result.blocking_reasons) + msg = ( + f"Promotion gate failed for {candidate_id}: {reasons}. " + "Resolve blocking issues before promoting." + ) + raise PromotionError(msg) + + # Step 2: Load candidate + artifact = load_candidate_artifact(root) + candidate: CandidateFinding | None = None + for c in artifact.candidates: + if c.id == candidate_id: + candidate = c + break + + if candidate is None: + msg = f"Candidate {candidate_id} not found." + raise PromotionError(msg) + + # Step 3: Load review decision + decisions = _load_review_decisions(root) + decision: dict[str, Any] = {} + for d in decisions: + if d.get("finding_id") == candidate_id: + decision = d + break + + # Step 4: Load existing register and check duplicate + register = _load_debt_register(root) + _check_not_already_promoted(register, candidate_id) + + # Step 5: Build DebtFinding + lineage = _build_lineage_metadata(candidate, decision) + finding_id = _next_finding_id(register, candidate.category) + + # Severity from candidate (informational, not scored) + severity = candidate.severity if candidate.severity != "Unscored" else "Low" + + new_finding = DebtFinding( + id=finding_id, + category=candidate.category, + issue_type="technical_debt", + title=candidate.title, + description=candidate.description, + severity=severity, + confidence=candidate.confidence, + status="Detected", + locations=candidate.locations, + evidence_ids=candidate.evidence_ids, + technical_impact=( + f"Identified by {candidate.provenance.connector_name} scanner. " + "Impact assessment from external evidence." + ), + business_impact=( + "Promoted from candidate finding. " + "Validate business impact with Product Engineering Team." + ), + risk_score=25, # Default moderate risk for promoted findings + priority="Medium", + risk_breakdown={ + LINEAGE_KEY: lineage, + "source": "candidate_promotion", + "promotion_candidate_id": candidate_id, + }, + recommended_action=( + f"Review and address finding from {candidate.provenance.connector_name}. " + "External evidence should be validated before remediation." + ), + verification_recommendations=[ + "Verify the external finding still applies to current codebase.", + "Confirm remediation addresses the actual issue.", + ], + ) + + # Step 6: Append to register + register.findings.append(new_finding) + _resummary(register) + _save_debt_register(root, register) + + # Step 7: Append lifecycle entry + history = _load_lifecycle_history(root) + entry = LifecycleEntry( + artifact_type="candidate_promotion", + artifact_id=candidate_id, + from_status="CandidateAccepted", + to_status="Detected", + actor=decision.get("reviewer", "operator"), + rationale=f"Promoted to accepted finding {finding_id}", + metadata={"promoted_finding_id": finding_id}, + ) + history.append_entry(entry) + _save_lifecycle_history(root, history) + + return new_finding diff --git a/tests/test_cli_command_surface.py b/tests/test_cli_command_surface.py index 80dc694..12e9749 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.9.0" in result.output + assert "3.10.0" in result.output diff --git a/tests/test_release_consistency.py b/tests/test_release_consistency.py index 61177df..1910ce4 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.9.0" +EXPECTED = "3.10.0" class TestVersionSources: diff --git a/tests/test_v3100_candidate_promotion_execution.py b/tests/test_v3100_candidate_promotion_execution.py new file mode 100644 index 0000000..545285a --- /dev/null +++ b/tests/test_v3100_candidate_promotion_execution.py @@ -0,0 +1,445 @@ +"""Tests for v3.10.0 — Candidate Promotion Execution. + +First mutation wave: promotes eligible candidates to accepted findings. +Requires gate pass, preserves lineage, append-only audit, duplicate guard. + +Key invariants: +- Promotion must be explicit +- Promotion must require gate pass +- Promotion must preserve candidate lineage +- Promotion must not delete candidate-findings.json +- Promotion must not auto-generate work packages or tickets +- One promotion per candidate +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from pharabius.core.connectors.candidate import write_candidate_artifact +from pharabius.core.connectors.candidate_promotion import ( + PromotionError, + promote_candidate, +) +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", +) -> CandidateFinding: + return CandidateFinding( + id=candidate_id, + category=category, + title=f"Test vulnerability {candidate_id}", + description="A real security issue that needs addressing.", + severity="High", + confidence="Medium", + locations=["src/main.py:42"], + evidence_ids=["EXT-001"], + provenance=CandidateProvenance( + connector_name=connector_name, + source_format=connector_name, + evidence_count=1, + evidence_ids=["EXT-001"], + source_types=["external_scanner_result"], + ), + ) + + +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 + + +def _fully_review( + tmp_path: Path, + candidate_id: str = "CAND-0001", + reviewer: str = "alice", + rationale: str = "Confirmed real vulnerability", +) -> None: + review_candidate( + tmp_path, + candidate_id, + DecisionStatus.ACCEPTED, + reviewer=reviewer, + rationale=rationale, + ) + + +# --------------------------------------------------------------------------- +# S01: Successful promotion +# --------------------------------------------------------------------------- + + +class TestSuccessfulPromotion: + """Eligible candidate can be promoted to accepted finding.""" + + def test_promotion_returns_debt_finding(self, tmp_path: Path) -> None: + from pharabius.schemas.finding import DebtFinding + + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert isinstance(result, DebtFinding) + assert result.status == "Detected" + assert result.issue_type == "technical_debt" + + def test_promotion_writes_to_debt_register(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + reg_path = tmp_path / ".ai-debt" / "debt-register.json" + assert reg_path.exists() + reg = json.loads(reg_path.read_text()) + assert reg["summary"]["total_findings"] == 1 + + def test_promotion_generates_finding_id(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001", category="TD-VULN")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert result.id.startswith("TD-VULN-") + assert result.id != "CAND-0001" + + def test_promotion_preserves_title_and_description(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert "Test vulnerability" in result.title + + def test_promotion_preserves_category(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001", category="TD-DEP")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert result.category == "TD-DEP" + + def test_promotion_preserves_evidence_ids(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert "EXT-001" in result.evidence_ids + + +# --------------------------------------------------------------------------- +# S03: Gate requirement +# --------------------------------------------------------------------------- + + +class TestGateRequirement: + """Promotion requires passing all gate checks.""" + + def test_no_review_decision_fails(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + with pytest.raises(PromotionError, match="gate failed"): + promote_candidate(tmp_path, "CAND-0001") + + def test_rejected_decision_fails(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate(tmp_path, "CAND-0001", DecisionStatus.REJECTED, reviewer="bob") + with pytest.raises(PromotionError, match="gate failed"): + promote_candidate(tmp_path, "CAND-0001") + + def test_no_reviewer_fails(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + review_candidate( + tmp_path, "CAND-0001", DecisionStatus.ACCEPTED, reviewer="", rationale="Good" + ) + with pytest.raises(PromotionError, match="gate failed"): + promote_candidate(tmp_path, "CAND-0001") + + +# --------------------------------------------------------------------------- +# S04: Lineage metadata +# --------------------------------------------------------------------------- + + +class TestLineageMetadata: + """Promoted finding carries candidate lineage.""" + + def test_lineage_in_risk_breakdown(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert "_promotion_lineage" in result.risk_breakdown + lineage = result.risk_breakdown["_promotion_lineage"] + assert lineage["candidate_id"] == "CAND-0001" + assert lineage["source"] == "candidate_promotion" + + def test_lineage_preserves_connector(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + _make_candidate("CAND-0001", connector_name="semgrep"), + ) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + lineage = result.risk_breakdown["_promotion_lineage"] + assert lineage["connector_name"] == "semgrep" + + def test_lineage_preserves_reviewer(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001", reviewer="bob") + + result = promote_candidate(tmp_path, "CAND-0001") + lineage = result.risk_breakdown["_promotion_lineage"] + assert lineage["reviewer"] == "bob" + + def test_lineage_preserves_promoted_at(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + lineage = result.risk_breakdown["_promotion_lineage"] + assert "promoted_at" in lineage + + +# --------------------------------------------------------------------------- +# S05: Lifecycle history appended +# --------------------------------------------------------------------------- + + +class TestLifecycleHistory: + """Promotion appends lifecycle entry.""" + + def test_lifecycle_entry_created(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + lh_path = tmp_path / ".ai-debt" / "lifecycle-history.json" + assert lh_path.exists() + history = json.loads(lh_path.read_text()) + # Should have review entry + promotion entry + assert len(history["entries"]) >= 1 + promotion_entries = [ + e for e in history["entries"] if e["artifact_type"] == "candidate_promotion" + ] + assert len(promotion_entries) == 1 + assert promotion_entries[0]["from_status"] == "CandidateAccepted" + assert promotion_entries[0]["to_status"] == "Detected" + + +# --------------------------------------------------------------------------- +# S06: Duplicate promotion guard +# --------------------------------------------------------------------------- + + +class TestDuplicatePromotionGuard: + """Each candidate can only be promoted once.""" + + def test_second_promotion_fails(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + with pytest.raises(PromotionError, match="already promoted"): + promote_candidate(tmp_path, "CAND-0001") + + def test_register_not_duplicated(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + reg = json.loads((tmp_path / ".ai-debt" / "debt-register.json").read_text()) + assert reg["summary"]["total_findings"] == 1 + + +# --------------------------------------------------------------------------- +# Non-mutation guarantees +# --------------------------------------------------------------------------- + + +class TestCandidateArtifactPreserved: + """Promotion does not delete or rewrite candidate-findings.json.""" + + def test_candidate_artifact_unchanged(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + cand_path = tmp_path / ".ai-debt" / "candidate-findings.json" + orig = cand_path.read_text() + + promote_candidate(tmp_path, "CAND-0001") + + assert cand_path.exists() + assert cand_path.read_text() == orig + + def test_candidate_still_listed(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + cand = json.loads((tmp_path / ".ai-debt" / "candidate-findings.json").read_text()) + assert len(cand["candidates"]) == 1 + + +class TestNoWorkPackagesOrTickets: + """Promotion does not auto-generate work packages or tickets.""" + + def test_no_work_packages(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + assert not (tmp_path / ".ai-debt" / "work-packages").exists() + + +class TestReviewDecisionsPreserved: + """Promotion does not rewrite review decisions.""" + + def test_review_sidecar_unchanged(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + sidecar = tmp_path / ".ai-debt" / "review" / "decisions.json" + orig = sidecar.read_text() + + promote_candidate(tmp_path, "CAND-0001") + + assert sidecar.read_text() == orig + + +# --------------------------------------------------------------------------- +# Summary recalculation +# --------------------------------------------------------------------------- + + +class TestSummaryRecalculation: + """Register summary recalculated after promotion.""" + + def test_summary_reflects_promoted_finding(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + promote_candidate(tmp_path, "CAND-0001") + + reg = json.loads((tmp_path / ".ai-debt" / "debt-register.json").read_text()) + assert reg["summary"]["total_findings"] == 1 + assert reg["summary"]["technical_debt_count"] == 1 + + def test_multiple_promotions(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + _make_candidate("CAND-0001"), + _make_candidate("CAND-0002"), + ) + _fully_review(tmp_path, "CAND-0001") + _fully_review(tmp_path, "CAND-0002") + + promote_candidate(tmp_path, "CAND-0001") + promote_candidate(tmp_path, "CAND-0002") + + reg = json.loads((tmp_path / ".ai-debt" / "debt-register.json").read_text()) + assert reg["summary"]["total_findings"] == 2 + + +# --------------------------------------------------------------------------- +# Finding ID generation +# --------------------------------------------------------------------------- + + +class TestFindingIDGeneration: + """Finding IDs are unique and sequential.""" + + def test_first_id_is_001(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001", category="TD-VULN")) + _fully_review(tmp_path, "CAND-0001") + + result = promote_candidate(tmp_path, "CAND-0001") + assert result.id == "TD-VULN-001" + + def test_second_id_is_002(self, tmp_path: Path) -> None: + _setup_workspace( + tmp_path, + _make_candidate("CAND-0001", category="TD-VULN"), + _make_candidate("CAND-0002", category="TD-VULN"), + ) + _fully_review(tmp_path, "CAND-0001") + _fully_review(tmp_path, "CAND-0002") + + promote_candidate(tmp_path, "CAND-0001") + result = promote_candidate(tmp_path, "CAND-0002") + assert result.id == "TD-VULN-002" + + +# --------------------------------------------------------------------------- +# Existing register preserved +# --------------------------------------------------------------------------- + + +class TestExistingRegisterPreserved: + """Promotion appends to existing register, doesn't overwrite.""" + + def test_existing_findings_preserved(self, tmp_path: Path) -> None: + _setup_workspace(tmp_path, _make_candidate("CAND-0001")) + _fully_review(tmp_path, "CAND-0001") + + # Pre-populate debt-register with existing finding + ai_debt = tmp_path / ".ai-debt" + existing = { + "schema_version": "1.0", + "project_name": "test", + "summary": {"total_findings": 1, "critical": 0, "high": 1, "medium": 0, "low": 0}, + "findings": [ + { + "id": "TD-ARCH-001", + "category": "TD-ARCH", + "title": "Existing", + "description": "Pre-existing finding", + "technical_impact": "Test", + "business_impact": "Test", + "risk_score": 25, + "priority": "High", + "recommended_action": "Test", + } + ], + } + (ai_debt / "debt-register.json").write_text(json.dumps(existing)) + + promote_candidate(tmp_path, "CAND-0001") + + reg = json.loads((ai_debt / "debt-register.json").read_text()) + assert reg["summary"]["total_findings"] == 2 + ids = [f["id"] for f in reg["findings"]] + assert "TD-ARCH-001" in ids