diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 33f8e6be0..8751bc8e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1087,6 +1087,7 @@ jobs: tests/integration/test_release_gate_policy_single_active_postgres.py tests/integration/test_migration_0211_0212_postgres.py tests/integration/test_release_gate_summary_postgres.py + tests/integration/test_release_decision_analysis_changed_postgres.py tests/integration/test_releases_list_gate_owner_postgres.py tests/test_compliance_packs_project_list.py tests/integration/test_migration_0213_postgres.py diff --git a/CHANGELOG.md b/CHANGELOG.md index cc2849f83..6d677b02f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,9 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them). ### Fixed +- Release gate: the quick look (a run with no deep investigation yet) is scored with the project's effective policy (its thresholds, weights, bands, P0 cap and open-defect rule) instead of built-in thresholds with half the policy, and names that one policy; rules it cannot check before a deep investigation are listed as not checked. With no published policy nothing changes (D-142). The gate card shows the thresholds and pass-rate bands the verdict used ("Go under risk 20 and at 90% or more · No-Go at risk 55 or under 63% · Pass-rate bands: No-Go under 90%, Conditional under 95%") and says when a band held the verdict back (D-104), and a stored decision says when a test's category was corrected after it was made, without changing it (D-97). +- Gate policies: a draft that was never published can be deleted (`DELETE /api/v1/release-gate-policies/{policy_id}`, administrators; a published or referenced version is refused with 409); the list shows active policies and drafts first and older versions under **Past versions**, and says when no policy is active (D-141). **New version from this** asks before creating the draft (D-140). +- Run page: a test's attribution badge follows a category that changes while the page is open (D-72). Deep investigation: a root-cause stage answered by more than one engine reads "mixed" and shows the split ("1 model · 3 rules"), also in the decision trail and MCP (D-156). - Ask AI with a local model: when the model refuses a request that carried tools (HTTP 4xx), the turn is asked again without tools instead of failing; a model whose refusal names tools is remembered as tool-free. A refusal that remains no longer says "Try rephrasing" and is not offered as a retry; an internal error is no longer reported as the provider's refusal (D-143). - Local models: one model call no longer shares its time limit with the escalation that follows it, a local provider (Ollama) analyses one failure at a time unless `LLM_MAX_CONCURRENT_ANALYSES` is set, and `.env.example` ships the code's 300 s timeout instead of 120 s (D-144). - Run compare: the narrative says when it covers one suite ("checkout suite only"), and a model summary whose failed/total/pass-rate figures contradict the runs is replaced by the deterministic summary (D-148). diff --git a/UPGRADING.md b/UPGRADING.md index b3fcf993d..cedc90058 100644 --- a/UPGRADING.md +++ b/UPGRADING.md @@ -200,6 +200,26 @@ Existing usernames that contain `@` keep working for sign-in. | `POST /deep-investigate/{run_id}` in Rules mode | accepted | 422 "requires LLM or Auto mode" | | `POST /analyze` for a test with a human correction | returns the correction | the engine's answer, replacing the correction | +### Release gate and gate policies (batch 8) + +- **The quick look follows a published gate policy whole.** A project with a + published policy can see a different quick-look verdict for the same run: + its thresholds and weights now apply, not only its pass-rate bands and P0 + cap. Projects without a policy see no change. Stored decisions are not + re-evaluated. `GET /api/v1/release-readiness/{run_id}` names the policy really + used (`policy_level`, `policy_id`, `policy_version`) and lists the rules a + quick look cannot check in `input_snapshot.rules_not_checked`. +- **The same response gains `analysis_changed_since` and + `analysis_changed_at`** for a stored decision whose run had a category + correction saved after its analyses were read, and `pass_rate_bands` / + `band_held_back` for the pass-rate band applied at read time. +- **`DELETE /api/v1/release-gate-policies/{policy_id}`** (administrators) + deletes a never-published draft and answers 409 for any other version; the + delete is recorded as `policy.updated`. +- **Decision trail stages gain an optional `mode_distribution`**, and a + root-cause stage answered by more than one engine stores `analysis_mode` + `mixed`. + ### The local model path (batch 7) - **`AI_TIMEOUT_SECONDS` in `.env.example` is now 300** (the code default). An diff --git a/backend/app/agents/analysis_agent.py b/backend/app/agents/analysis_agent.py index 00ae439a2..a27817825 100644 --- a/backend/app/agents/analysis_agent.py +++ b/backend/app/agents/analysis_agent.py @@ -81,6 +81,11 @@ # Non-LLM engines and deterministic fallbacks are repeatable; retrying them # just burns CPU/LLM fallback budget and returns the same low-confidence answer. _DETERMINISTIC_ANALYSIS_ENGINES = {"rules", "ml", "blocked"} +# D-156 (review F6): the per-test ``mode_used`` values that are an engine +# answering (analysis_router: llm | ml | rules). Not engines: "hint" +# (classification_hint_service), "human_corrected" (analysis_corrections) and +# "unknown" (no engine recorded). Only these count towards a "mixed" stage. +_ANSWERING_ENGINES = frozenset({"llm", "ml", "rules"}) _METADATA_CACHE_TTL_SECONDS = 30 _METADATA_CACHE_MAX_ENTRIES = 64 _METADATA_CACHE: dict[str, tuple[float, dict[str, dict]]] = {} @@ -597,6 +602,14 @@ async def run(self, state: dict) -> dict: if audit.get("fallback_from"): fallback_count += 1 dominant_mode = max(mode_counts, key=mode_counts.get) if mode_counts else None + # D-156: three rules answers and one model answer used to read "rules". + # When the tests ran on more than one engine the stage says "mixed" and + # the split stays in result_data.mode_distribution (the decision trail + # exposes it per stage). Only an engine that answered counts towards + # "mixed" (_ANSWERING_ENGINES): a QA lead's hint, a replayed human + # correction or an unrecorded engine ("unknown") is not a second engine. + recorded_engines = [m for m in mode_counts if m in _ANSWERING_ENGINES] + stage_mode = "mixed" if len(recorded_engines) > 1 else dominant_mode stage_fallback_reason = ( f"{fallback_count}/{total_analysed} tests fell back from requested engine" if fallback_count else None @@ -619,7 +632,7 @@ async def run(self, state: dict) -> dict: "budget_skipped": len(budget_skipped), "config_skipped": len(threshold_skipped), }, - analysis_mode=dominant_mode, + analysis_mode=stage_mode, fallback_reason=stage_fallback_reason, project_id=project_id, ) diff --git a/backend/app/models/schemas.py b/backend/app/models/schemas.py index a27af5e14..1cd3223c7 100644 --- a/backend/app/models/schemas.py +++ b/backend/app/models/schemas.py @@ -7110,6 +7110,13 @@ class ReleaseCouncilResponse(BaseModel): # e.g. ``["p0_defects:2>0"]``. release_readiness_band: Optional[str] = None band_downgrades: List[str] = [] + # Batch 8 review F1: the band edges the read-time band floor applied + # (``{orange_min, yellow_min, green_min}``, the classifier's defaults filled + # in): under orange is No-Go, orange is Conditional. ``None`` with no + # active policy. ``band_held_back`` is True when the pass-rate band itself + # made the verdict stricter (a hard cap is named in ``band_downgrades``). + pass_rate_bands: Optional[dict] = None + band_held_back: bool = False # E8.4: the human-review gate on the value CI reads (section 8.2). While # the gate is enforced, an unreviewed AI decision reads PENDING_REVIEW (or # ADVISORY_ with allow_advisory) and the model's value moves here. @@ -7123,6 +7130,12 @@ class ReleaseCouncilResponse(BaseModel): # quick-look view: no decision has been stored, so there is no time. created_at: Optional[datetime] = None updated_at: Optional[datetime] = None + # D-97: a person changed a test's category in this run after the stored + # decision read its analyses. The decision is NOT recomputed (a signed + # decision must not change silently); the gate says "re-evaluate". + # Set by ``GET /release-readiness/{run_id}`` only; False on a quick look. + analysis_changed_since: bool = False + analysis_changed_at: Optional[datetime] = None class ReleaseCouncilOverrideRequest(BaseModel): @@ -9655,6 +9668,9 @@ class StageDecisionSummary(BaseModel): completed_at: Optional[datetime] = None duration_seconds: Optional[float] = None analysis_mode: Optional[str] = None # llm|ml|rules|auto|mixed + # D-156: tests per engine for a stage that analysed tests (root cause); + # "mixed" above means more than one key here. None for other stages. + mode_distribution: Optional[Dict[str, int]] = None fallback_used: Optional[bool] = None fallback_reason: Optional[str] = None route_rationale: Optional[str] = None diff --git a/backend/app/routers/release_gate_policies.py b/backend/app/routers/release_gate_policies.py index 1d61bfa95..b8420bb10 100644 --- a/backend/app/routers/release_gate_policies.py +++ b/backend/app/routers/release_gate_policies.py @@ -3,10 +3,11 @@ import uuid from typing import Optional, Sequence -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends, HTTPException, Response, status from sqlalchemy import func, or_, select, text -from sqlalchemy.exc import IntegrityError +from sqlalchemy.exc import IntegrityError, InvalidRequestError from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.orm.exc import StaleDataError from app.core.deps import ( _api_key_bound_project, @@ -16,7 +17,14 @@ require_role, ) from app.db.postgres import get_db -from app.models.postgres import ReleaseDecision, ReleaseGatePolicy, TestRun, User, UserRole +from app.models.postgres import ( + ReleaseDecision, + ReleaseGateDecision, + ReleaseGatePolicy, + TestRun, + User, + UserRole, +) from app.models.schemas import ( PolicyDocument, PolicySimulateRequest, @@ -49,6 +57,19 @@ "Another policy version was created for this scope at the same moment. Try again." ) ALREADY_PUBLISHED_DETAIL = "Policy is already published" +#: D-141: what deleting a version that was ever published is told. Past +#: verdicts name the version they were judged by, so it is kept. +DELETE_PUBLISHED_DETAIL = ( + "Only a draft that was never published can be deleted. A published version " + "is kept because past verdicts name it; deactivate it instead." +) +#: Batch 8 review F4: what a publish or an edit is told when another admin +#: deleted the draft (D-141) between this request's read and its write. +DRAFT_DELETED_DETAIL = "This draft was deleted." +#: D-141: what deleting a draft a stored decision points at is told. +DELETE_REFERENCED_DETAIL = ( + "This draft is named by a stored release decision, so it is kept." +) #: The indexes whose violation is a scope race (migration 0210, plus the #: project-scope version constraint of 0032). Any other IntegrityError is a @@ -388,13 +409,18 @@ async def update_policy( changed = [field for field, value in update_data.items() if getattr(policy, field) != value] for field, value in update_data.items(): setattr(policy, field, value) - if changed: - await _record_policy_event( - db, policy, "policy.updated", current_user, - context={"changed": ", ".join(changed)}, changed_fields=changed, - ) - - await db.commit() + try: + if changed: + await _record_policy_event( + db, policy, "policy.updated", current_user, + context={"changed": ", ".join(changed)}, changed_fields=changed, + ) + await db.commit() + except StaleDataError: + # Review F4: the draft was deleted (D-141) after the read above, so the + # UPDATE matched no row. A plain 404, not a 500; nothing is written. + await db.rollback() + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=DRAFT_DELETED_DETAIL) await db.refresh(policy) logger.info("Policy updated: %s v%d by user_id=%s", policy.id, policy.version, current_user.id) return policy @@ -427,7 +453,12 @@ async def publish_policy( await _lock_scope(db, policy.project_id) # Re-read under the lock: the same draft published by someone else is no # longer a draft. - await db.refresh(policy) + try: + await db.refresh(policy) + except InvalidRequestError: + # Review F4: the row is gone -- another admin deleted the draft (D-141) + # while this request waited for the lock. A plain 404, not a 500. + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=DRAFT_DELETED_DETAIL) if not policy.is_draft: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=ALREADY_PUBLISHED_DETAIL) current = await _active_ids_in_scope(db, policy.project_id, policy.id) @@ -508,6 +539,67 @@ async def deactivate_policy( return policy +@router.delete("/{policy_id}", status_code=204) +async def delete_policy( + policy_id: uuid.UUID, + # N20: _enforce_policy_binding below confines a project-bound key. + current_user: User = Depends(require_role(UserRole.ADMIN, allow_project_key=True)), + db: AsyncSession = Depends(get_db), +): + """Delete a draft that was never published (ADMIN only) (D-141). + + A version that was ever published stays: past verdicts and the version + history name it, so it is deactivated instead (409). A draft a stored + release decision points at is kept too (409). Records ``policy.updated`` + with ``changed: draft deleted`` in the same transaction, the way + deactivate records its edit of the active flag. + """ + result = await db.execute( + select(ReleaseGatePolicy).where(ReleaseGatePolicy.id == policy_id) + ) + policy = result.scalar_one_or_none() + if not policy: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Policy not found") + _enforce_policy_binding(current_user, policy.project_id) + if policy.project_id is not None: + # The same scope call create and get make (code review round 4): an + # admin passes by role, a bound key only for its own project. + from app.core.deps import resolve_project_scope # noqa: PLC0415 + + await resolve_project_scope(db, current_user, str(policy.project_id)) + + # Serialise against a concurrent publish of this draft in the same scope, + # then re-read it: a publish that committed first makes it a 409 here. + await _lock_scope(db, policy.project_id) + result = await db.execute( + select(ReleaseGatePolicy) + .where(ReleaseGatePolicy.id == policy_id) + .execution_options(populate_existing=True) + ) + policy = result.scalar_one_or_none() + if not policy: + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Policy not found") + if not policy.is_draft or policy.is_active or policy.activated_at is not None: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=DELETE_PUBLISHED_DETAIL) + + for model in (ReleaseDecision, ReleaseGateDecision): + referenced = await db.execute( + select(model.id).where(model.policy_id == policy.id).limit(1) + ) + if referenced.scalar_one_or_none() is not None: + raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=DELETE_REFERENCED_DETAIL) + + await _record_policy_event( + db, policy, "policy.updated", current_user, + context={"changed": "draft deleted"}, changed_fields=["deleted"], + before={"is_draft": True}, after={"deleted": True}, + ) + await db.delete(policy) + await db.commit() + logger.info("Policy draft deleted: %s v%d by user_id=%s", policy.id, policy.version, current_user.id) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + @router.post("/simulate", response_model=PolicySimulateResponse) async def simulate_policy( payload: PolicySimulateRequest, diff --git a/backend/app/routers/release_readiness.py b/backend/app/routers/release_readiness.py index 3f22036f8..dcd3d5152 100644 --- a/backend/app/routers/release_readiness.py +++ b/backend/app/routers/release_readiness.py @@ -22,7 +22,12 @@ ) from app.services.activity.service import ActorRef, record as record_activity from app.services.notification import gate_notifications -from app.services.release_council_service import apply_override, get_release_council +from app.services.release_council_service import ( + analysis_changed_since, + apply_override, + decision_evaluated_at, + get_release_council, +) logger = logging.getLogger("routers.release_readiness") @@ -99,6 +104,17 @@ async def get_release_decision( ) if allow_advisory and response.recommendation.startswith("ADVISORY_"): await db.commit() + # D-97: say when a person changed a test's category after this stored + # decision read the run's analyses. Read-only; the decision is untouched. + decided_at = None if council.synthesized else decision_evaluated_at(council) + if decided_at is not None: + # The decision's pipeline: its root-cause stage start is when the + # analyses and corrections it scored were read (review F3). + changed_at = await analysis_changed_since(db, run_id, decided_at, pipeline_run_id) + if changed_at is not None: + response = response.model_copy( + update={"analysis_changed_since": True, "analysis_changed_at": changed_at} + ) return response diff --git a/backend/app/services/activity/events.py b/backend/app/services/activity/events.py index 41479c3e1..e645d544e 100644 --- a/backend/app/services/activity/events.py +++ b/backend/app/services/activity/events.py @@ -368,10 +368,11 @@ def _spec( _spec("project.imported", "configuration", "project", "Project {entity_label} was imported from {source}", "outcome"), _spec("policy.created", "configuration", "policy", "Release gate policy {entity_label} was created"), _spec("policy.updated", "configuration", "policy", "Release gate policy {entity_label} changed: {changed}"), - # W21 ACT-01: no ``policy.deleted`` -- gate policies are versioned and - # never deleted (a superseded version is deactivated, which records - # ``policy.updated``), so the name was removed rather than left as a - # filter that matches nothing. + # W21 ACT-01: no ``policy.deleted`` -- a published gate policy is never + # deleted (a superseded version is deactivated, which records + # ``policy.updated``). Since D-141 a never-published draft can be deleted; + # that also records ``policy.updated`` ("draft deleted"), so the feed's + # policy filter keeps one name for every change. _spec("policy.activated", "configuration", "policy", "Release gate policy {entity_label} was activated"), _spec("agent_config.updated", "configuration", "project", "Agent {entity_label} configuration changed to version {config_version}: {changed}", "outcome", _HUMAN_OR_KEY), _spec("workflow.created", "configuration", "workflow", "Workflow {entity_label} version {version} was created", "outcome", _HUMAN_OR_KEY), diff --git a/backend/app/services/decision_trail_service.py b/backend/app/services/decision_trail_service.py index ecfa792a8..3ab85ba34 100644 --- a/backend/app/services/decision_trail_service.py +++ b/backend/app/services/decision_trail_service.py @@ -165,6 +165,21 @@ async def _load_workflow_events(pipeline_run: AgentPipelineRun) -> list[dict[str return fallback_events +def _stage_mode_distribution(stage: AgentStageResult) -> Optional[dict[str, int]]: + """D-156: the per-engine split a stage stored in ``result_data``, or None. + + The Root Cause stage records ``analysis_mode="mixed"`` when its tests ran + on more than one engine; this is the split the page prints beside it. + """ + result_data = getattr(stage, "result_data", None) + if not isinstance(result_data, dict): + return None + dist = result_data.get("mode_distribution") + if not isinstance(dist, dict): + return None + return {str(k): int(v) for k, v in dist.items() if isinstance(v, int) and not isinstance(v, bool)} + + def _summarize_stage(stage: AgentStageResult) -> dict[str, Any]: return { "stage_name": stage.stage_name, @@ -173,6 +188,7 @@ def _summarize_stage(stage: AgentStageResult) -> dict[str, Any]: "completed_at": stage.completed_at, "duration_seconds": _duration_seconds(stage.started_at, stage.completed_at), "analysis_mode": getattr(stage, "analysis_mode", None), + "mode_distribution": _stage_mode_distribution(stage), "fallback_used": bool(stage.fallback_used) if stage.fallback_used is not None else None, "fallback_reason": getattr(stage, "fallback_reason", None), "route_rationale": stage.route_rationale, diff --git a/backend/app/services/release_council_service.py b/backend/app/services/release_council_service.py index 35343ddcf..d0c0e3a45 100644 --- a/backend/app/services/release_council_service.py +++ b/backend/app/services/release_council_service.py @@ -37,11 +37,8 @@ from app.services.criticality_service import ( HARD_FLOOR_FACTOR as _HARD_FLOOR_FACTOR, SCORE_MODEL_VERSION, - apply_verdict_floor, - compute_composite, compute_dimension_scores, score_cluster, - score_to_recommendation, ) from app.core.config import settings @@ -121,8 +118,26 @@ async def _apply_band_floor( previously passed an all-severities total and a dead ``severity == "P0"`` zero respectively, so the cap either over-counted or never fired. """ + final, band, downgrades, band_policy, _bands = await _band_floor_detail( + db, project_id, recommendation, pass_rate, + ) + return final, band, downgrades, band_policy + + +async def _band_floor_detail( + db: AsyncSession, + project_id: Optional[uuid.UUID], + recommendation: str, + pass_rate: float, +) -> tuple[str, Optional[str], list[str], Optional[tuple[str, int, str]], Optional[dict]]: + """``_apply_band_floor`` plus the band edges it applied (batch 8 review F1). + + The gate card states the numbers that can decide the verdict; the + pass-rate bands are among them, and they come from the policy in force at + read time, which a stored decision's frozen snapshot does not carry. + """ if project_id is None: - return recommendation, None, [], None + return recommendation, None, [], None, None # Local import to keep release_council_service free of metrics-service # coupling at module level — _resolve_policy_for_project also depends on @@ -133,18 +148,40 @@ async def _apply_band_floor( resolved = await _resolve_active_policy_for_project(db, str(project_id)) if resolved is None: - return recommendation, None, [], None + return recommendation, None, [], None, None policy_doc, band_policy_id, band_policy_version, band_policy_level = resolved + bands = policy_doc.get("pass_rate_bands") or {} final, band, downgrades = await apply_policy_band_floor( db, project_id, recommendation, pass_rate, - bands=policy_doc.get("pass_rate_bands") or {}, + bands=bands, hard_caps=policy_doc.get("hard_caps") or {}, ) - return final, band, downgrades, (band_policy_id, band_policy_version, band_policy_level) + return ( + final, band, downgrades, + (band_policy_id, band_policy_version, band_policy_level), + _effective_bands(bands), + ) + + +def _effective_bands(bands: dict) -> dict: + """The band edges ``classify_with_policy`` applies: its defaults (orange 90, + yellow 95, green 99) for any edge the document leaves out. Under orange is + red (No-Go); orange is Conditional; yellow and green are Go.""" + return { + "orange_min": float(bands.get("orange_min", 90.0)), + "yellow_min": float(bands.get("yellow_min", 95.0)), + "green_min": float(bands.get("green_min", 99.0)), + } + + +def _band_held_back(before: str, after: str, downgrades: list[str]) -> bool: + """True when the pass-rate band itself made the verdict stricter. A hard + cap also pins the band red, but ``band_downgrades`` already names it.""" + return not downgrades and _normalize_verdict(after) != _normalize_verdict(before) async def apply_policy_band_floor( @@ -390,9 +427,11 @@ async def _synthesize_release_council( * A persisted row. The synthesis runs at read time only; the next deep run still writes the real ReleaseDecision and supersedes this view. - * A policy evaluator. We fall back to the hardcoded thresholds - in ``settings`` so the synth never blocks on policy table - gaps. A real deep run picks up the project-scoped policy. + * A full policy evaluation. It goes through the same evaluator as + the stored decision with the project's effective policy (D-142), + but only the rules whose inputs it has are checked; the others + are named in ``input_snapshot.rules_not_checked``. With no policy + it uses the built-in thresholds in ``settings``. Returns ``None`` (caller maps to 404) only when the run itself doesn't exist — that's a genuine "not found" the user should see. @@ -416,7 +455,21 @@ async def _synthesize_release_council( open_defects = int(signals["open_defects"]) pass_rate = float(run.pass_rate) - threshold = float(settings.RELEASE_PASS_RATE_THRESHOLD) + + # D-142: the project's effective policy, applied whole. The quick look used + # to score with the built-in thresholds (``policy_level="hardcoded"``) and + # then layer the published policy's bands and P0 cap on top, so a policy + # was half applied and the footer named both. One resolution now feeds the + # policy evaluator (thresholds, weights, the rules a quick look can check) + # and the band floor. No policy: the built-in numbers, as before. + from app.services.metrics_service import _resolve_active_policy_for_project + + resolved = ( + await _resolve_active_policy_for_project(db, str(run.project_id)) + if run.project_id is not None + else None + ) + policy_obj, policy_level, rules_not_checked = _quick_look_policy(resolved) # With no per-test analyses available (those are produced by the # offline pipeline's analysis stage, which has already run by the @@ -434,26 +487,69 @@ async def _synthesize_release_council( failure_clusters=[], open_defects=signals["open_defects_by_severity"] or open_defects, ) - composite = compute_composite(dim_scores) - if pass_rate < threshold * _HARD_FLOOR_FACTOR: - # Mirror the agent's hard floor: a run that drops below 70% of - # the configured pass-rate threshold is NO_GO regardless of - # the composite score. Bump composite so the recommendation - # function reaches NO_GO via the standard mapping. - composite = max(composite, 60.0) - recommendation = score_to_recommendation(composite, pass_rate, threshold) - recommendation, floor_reasons = apply_verdict_floor( - recommendation, - blocking_failures=int(signals["blocking_failures"]), - blocking_defects=int(signals["blocking_defects"]), + # The evaluator the stored decision uses: the policy's weights and + # thresholds, the verdict floor (D-04), then the rules. Called with the + # resolved policy as an override, so it reads no table of its own and + # counts no decision (a page read is not a gate decision). + from app.services.policy_evaluator_service import evaluate_policy + + evaluation = await evaluate_policy( + run.project_id, + dim_scores, + pass_rate, + { + "open_defects": open_defects, + "open_defects_by_severity": signals["open_defects_by_severity"], + "blocking_failures": int(signals["blocking_failures"]), + "blocking_defects": int(signals["blocking_defects"]), + }, + db, + policy_override=policy_obj, ) + thresholds = evaluation.effective_thresholds + threshold = float(thresholds["pass_rate_minimum"]) + hard_floor_factor = float(thresholds["pass_rate_hard_floor_factor"]) + composite = evaluation.effective_composite + if pass_rate < threshold * hard_floor_factor: + # Mirror the agent's hard floor: a run under the floor is NO_GO + # whatever the composite says (``score_to_recommendation`` rule 1). + # Raise the shown score to the No-Go band so it agrees with the + # verdict: 60 with the built-in No-Go line of 55. + composite = max(composite, 60.0, float(thresholds["no_go_threshold"])) + recommendation = evaluation.recommendation + floor_reasons = list((evaluation.verdict_floor or {}).get("reasons") or []) + policy_blocking = [ + f"[Policy] {ev.message}" for ev in evaluation.rule_evaluations + if not ev.passed and ev.action == "BLOCK" + ] + policy_conditions = [ + f"[Policy] {ev.message}" for ev in evaluation.rule_evaluations + if not ev.passed and ev.action == "WARN" + ] - # Layer the active ReleaseGatePolicy's pass-rate bands over the composite - # so /release-gate honours the same colours /overview renders. Fail-closed: - # the band can downgrade the verdict but never soften it. - recommendation, band, band_downgrades, band_policy = await _apply_band_floor( - db, run.project_id, recommendation, pass_rate, - ) + # Layer the same policy's pass-rate bands and P0 cap over the verdict so + # /release-gate honours the colours /overview renders. Fail-closed: the + # band can downgrade the verdict but never soften it. + band: Optional[str] = None + band_downgrades: list[str] = [] + band_policy: Optional[tuple[str, int, str]] = None + bands_applied: Optional[dict] = None + band_held_back = False + if resolved is not None: + policy_doc, band_policy_id, band_policy_version, band_policy_level = resolved + before_band = recommendation + policy_bands = policy_doc.get("pass_rate_bands") or {} + recommendation, band, band_downgrades = await apply_policy_band_floor( + db, + run.project_id, + recommendation, + pass_rate, + bands=policy_bands, + hard_caps=policy_doc.get("hard_caps") or {}, + ) + band_policy = (band_policy_id, band_policy_version, band_policy_level) + bands_applied = _effective_bands(policy_bands) + band_held_back = _band_held_back(before_band, recommendation, band_downgrades) defects_noun = "open defect" if open_defects == 1 else "open defects" reasoning = ( @@ -465,7 +561,7 @@ async def _synthesize_release_council( ) conditions = _quick_look_conditions(recommendation, pass_rate, threshold) - conditions = [f"Resolve: {reason}" for reason in floor_reasons] + conditions + conditions = [f"Resolve: {reason}" for reason in floor_reasons] + policy_conditions + conditions return ReleaseCouncilResponse( run_id=str(run_id), @@ -473,12 +569,14 @@ async def _synthesize_release_council( recommendation=recommendation, release_readiness_band=band, band_downgrades=band_downgrades, + pass_rate_bands=bands_applied, + band_held_back=band_held_back, # Floor, not round (D-96): a composite of 19.6 decided as "under 20" # must not be shown as 20. risk_score=int(math.floor(composite)), composite_risk=composite, dimension_scores=_build_dimension_scores(dim_scores), - blocking_issues=[], + blocking_issues=policy_blocking, conditions_for_go=conditions, reasoning=reasoning, score_model_version=SCORE_MODEL_VERSION, @@ -489,20 +587,30 @@ async def _synthesize_release_council( "open_defects_by_severity": signals["open_defects_by_severity"], "blocking_failures": signals["blocking_failures"], "blocking_defects": signals["blocking_defects"], - # The CONFIGURED target (RELEASE_PASS_RATE_THRESHOLD). Reporting it + # The pass-rate target applied: the policy's ``pass_rate_minimum``, + # or RELEASE_PASS_RATE_THRESHOLD with no policy. Reporting it # alone was actively misleading: a run at 83% sat next to # "threshold: 90.0" and a GO verdict, which reads as a contradiction. "threshold": threshold, # ...because `threshold` is NOT the GO cutoff. Pass rate only forces - # a verdict when it falls under `hard_floor_factor` (0.7) of the + # a verdict when it falls under `hard_floor_factor` (0.7, the + # built-in _HARD_FLOOR_FACTOR, unless a policy sets its own) of the # threshold; above that the composite risk score decides. Publish the # number actually applied so the verdict is explicable from its own # snapshot instead of appearing to contradict it. - "no_go_floor_pct": round(threshold * _HARD_FLOOR_FACTOR, 2), - "hard_floor_factor": _HARD_FLOOR_FACTOR, + "no_go_floor_pct": round(threshold * hard_floor_factor, 2), + "hard_floor_factor": hard_floor_factor, + # D-104: the two risk lines too, so the gate card can state every + # number the verdict used. + "go_threshold": float(thresholds["go_threshold"]), + "no_go_threshold": float(thresholds["no_go_threshold"]), + # Policy rules whose inputs a quick look does not have (flaky + # counts, duration regressions, per-test dimensions). Named, not + # passed as zeros: an unmeasured input must not read as a pass. + "rules_not_checked": rules_not_checked, "verdict_driver": ( "pass_rate_floor" - if pass_rate < threshold * _HARD_FLOOR_FACTOR + if pass_rate < threshold * hard_floor_factor # Above the floor but under the configured bar -> CONDITIONAL_GO. # Named distinctly so the reader can tell "your own threshold # held this back" from "the risk model held this back". @@ -518,18 +626,86 @@ async def _synthesize_release_council( override_audit=[], pass_rate=pass_rate, build_number=run.build_number, - policy_level="hardcoded", - # No stored decision on this path, so ``policy_level`` is honestly - # "hardcoded" — but the band floor above may still have applied a - # policy and changed the verdict, so name it. + # The policy this verdict was evaluated with (D-142): "hardcoded" + # only when no policy is active, and then the band fields stay None. + policy_id=evaluation.policy_id, + policy_version=evaluation.policy_version, + policy_level=policy_level, band_policy_id=band_policy[0] if band_policy else None, band_policy_version=band_policy[1] if band_policy else None, band_policy_level=band_policy[2] if band_policy else None, - rule_evaluations=[], + rule_evaluations=[ + RuleEvaluationResponse( + rule_id=ev.rule_id, + rule_name=ev.rule_name, + rule_type=ev.rule_type, + passed=ev.passed, + action=ev.action, + message=ev.message, + actual_value=ev.actual_value, + threshold_value=ev.threshold_value, + ) + for ev in evaluation.rule_evaluations + ], synthesized=True, ) +# Policy rule types a quick look can check from the run's aggregates: the open +# defect count is the one rule input it has. Flaky counts, duration +# regressions and the per-test dimensions come from deep investigation. +_QUICK_LOOK_RULE_TYPES = frozenset({"open_defect_limit"}) + + +def _quick_look_policy( + resolved: Optional[tuple[dict, str, int, str]], +) -> tuple[Any, str, list[dict]]: + """The policy the quick look evaluates, its level, and the rules it skips. + + ``resolved`` is ``_resolve_active_policy_for_project``'s answer. With no + policy, a frozen copy of the built-in numbers (as the release-risk agent + freezes its own fallback), so the verdict and score are exactly what the + quick look produced before D-142. With a policy, its whole document minus + the rules whose inputs a quick look does not have; those are returned so + the page can say they were not checked. + """ + from types import SimpleNamespace + + from app.services.criticality_service import _GO_THRESHOLD, _NO_GO_THRESHOLD, _weights + + if resolved is None: + frozen = SimpleNamespace( + id=None, + version=None, + rules={ + "thresholds": { + "go_threshold": float(_GO_THRESHOLD), + "no_go_threshold": float(_NO_GO_THRESHOLD), + "pass_rate_minimum": float(settings.RELEASE_PASS_RATE_THRESHOLD), + "pass_rate_hard_floor_factor": _HARD_FLOOR_FACTOR, + }, + "dimension_weights": _weights(), + "rules": [], + }, + ) + return frozen, "hardcoded", [] + + policy_doc, policy_id, policy_version, policy_level = resolved + rules = [r for r in (policy_doc.get("rules") or []) if isinstance(r, dict)] + checked = [r for r in rules if r.get("type") in _QUICK_LOOK_RULE_TYPES] + not_checked = [ + {"id": r.get("id"), "name": r.get("name") or r.get("type"), "type": r.get("type")} + for r in rules + if r.get("enabled", True) and r.get("type") not in _QUICK_LOOK_RULE_TYPES + ] + policy = SimpleNamespace( + id=policy_id, + version=policy_version, + rules={**policy_doc, "rules": checked}, + ) + return policy, policy_level, not_checked + + async def get_release_council( run_id: uuid.UUID, db: AsyncSession, @@ -654,16 +830,25 @@ async def get_release_council( # Initialised here, not only inside the branch below: an overridden # decision skips the band floor entirely, and the response reads this. band_policy: Optional[tuple[str, int, str]] = None + bands_applied: Optional[dict] = None + band_held_back = False if decision.human_override is None: # The open-CRITICAL defect count for the P0 hard cap is resolved # inside _apply_band_floor via the shared helper — the old inline # ``severity == "P0"`` count matched nothing, so the cap never fired. - final_recommendation, band, band_downgrades, band_policy = await _apply_band_floor( + ( + final_recommendation, band, band_downgrades, band_policy, bands_applied, + ) = await _band_floor_detail( db, project_id, decision.recommendation, run.pass_rate if run else 0.0, ) + band_held_back = band_policy is not None and _band_held_back( + decision.recommendation, final_recommendation, band_downgrades, + ) return ReleaseCouncilResponse( run_id=str(run_id), + pass_rate_bands=bands_applied, + band_held_back=band_held_back, project_id=str(project_id) if project_id else None, recommendation=final_recommendation, risk_score=decision.risk_score, @@ -708,6 +893,118 @@ async def get_release_council( ) +# A person set a test's category: one correction (``human_correction``, also +# written when a correction is edited) or a bulk reclassify of uncategorised +# failures (``bulk_reclassify``). ``ai_history_core.TEST_TRIGGERS`` names both. +_HUMAN_CATEGORY_TRIGGERS = ("human_correction", "bulk_reclassify") +# The pipeline stage that reads a run's analyses and human corrections for the +# decision (``AnalysisAgent.stage_name``). +_ANALYSIS_READ_STAGE = "root_cause_analysis" + + +def decision_evaluated_at(council: ReleaseCouncilResponse) -> Optional[datetime]: + """The fallback time a stored decision was evaluated, or None. + + ``input_snapshot.assembled_at`` is written each time the release-risk agent + evaluates (a re-run rewrites it, an override does not). It is NOT when the + decision's analyses were read: the root-cause stage read them (and the + corrections) minutes earlier, so ``analysis_changed_since`` prefers that + stage's start and uses this only when the pipeline has no such row (review + F3). A row without ``assembled_at`` falls back to ``created_at``; + ``updated_at`` is not used because an override moves it. + """ + snapshot = council.input_snapshot if isinstance(council.input_snapshot, dict) else {} + raw = snapshot.get("assembled_at") + when: Optional[datetime] = None + if isinstance(raw, str): + try: + when = datetime.fromisoformat(raw) + except ValueError: + when = None + if when is None: + when = council.created_at + if when is not None and when.tzinfo is None: + when = when.replace(tzinfo=timezone.utc) + return when + + +async def analysis_changed_since( + db: AsyncSession, + run_id: uuid.UUID, + decided_at: datetime, + pipeline_run_id: Optional[uuid.UUID] = None, +) -> Optional[datetime]: + """The newest human category change in ``run_id`` saved after the stored + decision's analyses were read. + + The read time is the start of ``pipeline_run_id``'s root-cause stage (that + stage loads the analyses and the human corrections the decision scores, + ``analysis_agent``), capped at ``decided_at``; with no such stage row it is + ``decided_at`` itself (``decision_evaluated_at``). A correction saved while + the deep run was in flight is therefore reported (review F3). + + D-97: a correction now counts in the score, but a decision stored before + the correction still reads the old category, and a signed decision must not + be recomputed silently. This only reports that the run's analysis changed, + so the gate can say "re-evaluate"; the stored row is not touched. + + Two records, either enough: the analysis version a correction or bulk + reclassify stages (it also covers an edited correction), and the + correction's own ``ai_feedback`` row (it survives a history write that + failed, which never fails the correction). Read-only; one statement. + """ + from sqlalchemy import DateTime, bindparam + + from app.models.postgres import ( + AgentStageResult, + AIAnalysisVersion, + AIFeedback, + FeedbackRating, + TestCase, + ) + + fallback = bindparam("decided_at", decided_at, type_=DateTime(timezone=True)) + if pipeline_run_id is not None: + stage_start = ( + select(sa_func.min(AgentStageResult.started_at)) + .where( + AgentStageResult.pipeline_run_id == pipeline_run_id, + AgentStageResult.stage_name == _ANALYSIS_READ_STAGE, + ) + .scalar_subquery() + ) + # LEAST skips a NULL (no stage row, or a stage never started) on + # PostgreSQL, so this is the stage start when known, else decided_at. + read_at: Any = sa_func.least(stage_start, fallback) + else: + read_at = fallback + + versions = ( + select(sa_func.max(AIAnalysisVersion.created_at)) + .where( + AIAnalysisVersion.test_run_id == run_id, + AIAnalysisVersion.trigger.in_(_HUMAN_CATEGORY_TRIGGERS), + AIAnalysisVersion.created_at > read_at, + ) + .scalar_subquery() + ) + corrections = ( + select(sa_func.max(AIFeedback.created_at)) + .select_from(AIFeedback) + .join(TestCase, TestCase.id == AIFeedback.test_case_id) + .where( + TestCase.test_run_id == run_id, + AIFeedback.rating == FeedbackRating.INCORRECT.value, + AIFeedback.corrected_category.isnot(None), + AIFeedback.created_at > read_at, + ) + .scalar_subquery() + ) + # GREATEST skips NULLs on PostgreSQL: NULL only when neither found one. + value = (await db.execute(select(sa_func.greatest(versions, corrections)))).scalar_one_or_none() + return value if isinstance(value, datetime) else None + + async def apply_override( run_id: uuid.UUID, override_recommendation: str, diff --git a/backend/tests/integration/test_release_decision_analysis_changed_postgres.py b/backend/tests/integration/test_release_decision_analysis_changed_postgres.py new file mode 100644 index 000000000..c97ec25ae --- /dev/null +++ b/backend/tests/integration/test_release_decision_analysis_changed_postgres.py @@ -0,0 +1,179 @@ +"""D-97 on real PostgreSQL: ``analysis_changed_since`` finds a human category +change saved after a stored release decision, and nothing else. + +One statement, ``GREATEST`` over two scalar subqueries (the analysis versions a +correction or bulk reclassify stages, and the correction's ``ai_feedback`` +row), so it is run here against the real tables: the run scoping through +``test_cases``, the trigger and rating filters, the strict "after" comparison +and GREATEST skipping a NULL half. + +Requires ``TESTLOOKUP_POSTGRES_TEST_DSN`` and a database migrated to head. +""" +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import pytest +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + +from tests.integration.ai_history_seed import ( + drop_project, + dsn, + seed_analysis, + seed_pipeline, + seed_project, + seed_run, + seed_user, +) + +pytest.importorskip("asyncpg") +pytestmark = [pytest.mark.integration, pytest.mark.asyncio] + +DECIDED = datetime(2026, 11, 20, 9, 0, tzinfo=timezone.utc) + + +@pytest.fixture +async def factory(): + eng = create_async_engine(dsn(), pool_size=2, max_overflow=0) + yield async_sessionmaker(eng, expire_on_commit=False) + await eng.dispose() + + +@pytest.fixture +async def world(factory): + """Two runs of one project: the decision's run and a neighbour.""" + from types import SimpleNamespace + + async with factory() as db: + project = await seed_project(db, "d97-pg") + run, cases = await seed_run(db, project, 2) + other_run, other_cases = await seed_run(db, project, 1) + analyses = [await seed_analysis(db, c) for c in cases] + other_analysis = await seed_analysis(db, other_cases[0]) + user = await seed_user(db, "dora") + await db.commit() + yield SimpleNamespace( + project=project, run=run, cases=cases, analyses=analyses, + other_run=other_run, other_cases=other_cases, other_analysis=other_analysis, user=user, + ) + await drop_project(factory, project, [user]) + + +def _feedback(world, *, case=0, at, rating="incorrect", category="PRODUCT_BUG", other=False): + from app.models.postgres import AIFeedback + + return AIFeedback( + analysis_id=world.other_analysis if other else world.analyses[case], + test_case_id=world.other_cases[0] if other else world.cases[case], + user_id=world.user, rating=rating, corrected_category=category, + source="manual", exported=False, created_at=at, + ) + + +def _version(world, *, case=0, n, trigger, at, other=False): + from app.models.postgres import AIAnalysisVersion + + return AIAnalysisVersion( + test_case_id=world.other_cases[0] if other else world.cases[case], + test_run_id=world.other_run if other else world.run, + project_id=world.project, test_fingerprint="fp", version=n, trigger=trigger, + content_sha256="0" * 64, failure_category="PRODUCT_BUG", created_at=at, + ) + + +async def _probe(factory, world, pipeline=None): + from app.services.release_council_service import analysis_changed_since + + async with factory() as db: + return await analysis_changed_since(db, world.run, DECIDED, pipeline) + + +async def _pipeline_with_root_cause(factory, world, started_at): + from app.models.postgres import AgentStageResult + + async with factory() as db: + pipeline = await seed_pipeline(db, world.run) + db.add(AgentStageResult( + pipeline_run_id=pipeline, task_key="root_cause_analysis", + stage_name="root_cause_analysis", status="completed", started_at=started_at, + )) + # Another stage of the same pipeline, earlier still: not the read time. + db.add(AgentStageResult( + pipeline_run_id=pipeline, task_key="ingestion", + stage_name="ingestion", status="completed", started_at=started_at - timedelta(hours=1), + )) + await db.commit() + return pipeline + + +async def test_a_correction_saved_while_the_run_was_in_flight_is_found(factory, world): + """Review F3: root cause read the analyses at 08:50, the decision was + assembled at 09:00; a correction at 08:55 is not in the decision. With the + pipeline it is reported; with only the decision time it is not.""" + in_flight = DECIDED - timedelta(minutes=5) + pipeline = await _pipeline_with_root_cause(factory, world, DECIDED - timedelta(minutes=10)) + async with factory() as db: + db.add(_version(world, n=1, trigger="human_correction", at=in_flight)) + # Before the root-cause stage started: already in the decision. + db.add(_feedback(world, case=1, at=DECIDED - timedelta(minutes=20))) + await db.commit() + assert await _probe(factory, world, pipeline) == in_flight + assert await _probe(factory, world) is None + + +async def test_a_pipeline_without_a_root_cause_row_falls_back_to_the_decision_time(factory, world): + async with factory() as db: + pipeline = await seed_pipeline(db, world.run) + db.add(_feedback(world, at=DECIDED - timedelta(minutes=5))) + await db.commit() + assert await _probe(factory, world, pipeline) is None + async with factory() as db: + db.add(_feedback(world, case=1, at=DECIDED + timedelta(minutes=5))) + await db.commit() + assert await _probe(factory, world, pipeline) == DECIDED + timedelta(minutes=5) + + +async def test_nothing_after_the_decision_is_none(factory, world): + async with factory() as db: + db.add(_feedback(world, at=DECIDED - timedelta(hours=1))) + db.add(_version(world, n=1, trigger="human_correction", at=DECIDED - timedelta(minutes=5))) + # Exactly at the decision time is not after it. + db.add(_version(world, case=1, n=1, trigger="human_correction", at=DECIDED)) + await db.commit() + assert await _probe(factory, world) is None + + +async def test_noise_is_ignored(factory, world): + """A pipeline re-analysis, a rating that is not a correction, a correction + without a category, and a correction in another run: none of them.""" + later = DECIDED + timedelta(hours=2) + async with factory() as db: + db.add(_version(world, n=1, trigger="pipeline", at=later)) + db.add(_version(world, case=1, n=1, trigger="manual_analyze", at=later)) + db.add(_feedback(world, at=later, rating="correct", category=None)) + db.add(_feedback(world, case=1, at=later, category=None)) + db.add(_feedback(world, at=later, other=True)) + db.add(_version(world, n=1, trigger="human_correction", at=later, other=True)) + await db.commit() + assert await _probe(factory, world) is None + + +async def test_a_correction_row_alone_is_found(factory, world): + """The history write failed (it never fails a correction): the + ``ai_feedback`` row is enough.""" + at = DECIDED + timedelta(hours=1) + async with factory() as db: + db.add(_feedback(world, at=at)) + await db.commit() + assert await _probe(factory, world) == at + + +async def test_a_version_alone_is_found_and_the_newest_wins(factory, world): + """An edited correction or a bulk reclassify stages a version and no new + ``ai_feedback`` row; with both kinds present the newest time is returned.""" + async with factory() as db: + db.add(_version(world, n=1, trigger="bulk_reclassify", at=DECIDED + timedelta(hours=1))) + db.add(_version(world, case=1, n=1, trigger="human_correction", at=DECIDED + timedelta(hours=4))) + db.add(_feedback(world, at=DECIDED + timedelta(hours=2))) + await db.commit() + assert await _probe(factory, world) == DECIDED + timedelta(hours=4) diff --git a/backend/tests/regression/test_admin_routes_refuse_project_keys.py b/backend/tests/regression/test_admin_routes_refuse_project_keys.py index e1861466f..5ebe62a4d 100644 --- a/backend/tests/regression/test_admin_routes_refuse_project_keys.py +++ b/backend/tests/regression/test_admin_routes_refuse_project_keys.py @@ -113,6 +113,8 @@ "_enforce_policy_binding", "the stored policy's project; system default refused"), ("app/routers/release_gate_policies.py", "deactivate_policy"): ( "_enforce_policy_binding", "the stored policy's project; system default refused"), + ("app/routers/release_gate_policies.py", "delete_policy"): ( + "_enforce_policy_binding", "D-141: the stored draft's project; system default refused"), ("app/routers/release_gate_policies.py", "simulate_policy"): ( "_enforce_api_key_project_binding", "against the body run's project"), # ── re-audit N26: require_role(UserRole.QA_LEAD, allow_project_key=True) ── diff --git a/backend/tests/regression/test_gate_says_when_analysis_changed.py b/backend/tests/regression/test_gate_says_when_analysis_changed.py new file mode 100644 index 000000000..9738c6db4 --- /dev/null +++ b/backend/tests/regression/test_gate_says_when_analysis_changed.py @@ -0,0 +1,204 @@ +"""D-97 (the High finding's last part): the gate says when a stored decision +predates a correction in its run. + +Batch 1 made a correction count in the score, but a release decision stored +before the correction still read the old category, and nothing told the +reader. A signed decision must not be recomputed silently, so the read only +reports it: ``GET /release-readiness/{run_id}`` sets +``analysis_changed_since`` / ``analysis_changed_at`` when a person changed a +test's category in the run after the decision read the run's analyses. The +query itself runs on PostgreSQL in +``tests/integration/test_release_decision_analysis_changed_postgres.py``. +""" +from __future__ import annotations + +import uuid +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +pytest.importorskip("sqlalchemy") + +from app.models.schemas import ReleaseCouncilResponse # noqa: E402 + +RUN = uuid.uuid4() +ASSEMBLED = datetime(2026, 11, 20, 9, 0, tzinfo=timezone.utc) +CREATED = datetime(2026, 11, 19, 8, 0, tzinfo=timezone.utc) +CORRECTED = ASSEMBLED + timedelta(hours=3) + + +def _council(**kw): + base = dict( + run_id=str(RUN), recommendation="GO", risk_score=12, + input_snapshot={"assembled_at": ASSEMBLED.isoformat()}, + created_at=CREATED, updated_at=CREATED, + ) + base.update(kw) + return ReleaseCouncilResponse(**base) + + +class TestDecisionTime: + def test_the_evaluation_time_is_the_snapshot_assembly(self): + from app.services.release_council_service import decision_evaluated_at + + assert decision_evaluated_at(_council()) == ASSEMBLED + + def test_without_a_snapshot_time_the_row_creation(self): + from app.services.release_council_service import decision_evaluated_at + + assert decision_evaluated_at(_council(input_snapshot={"pass_rate": 91.0})) == CREATED + assert decision_evaluated_at(_council(input_snapshot={"assembled_at": "not a time"})) == CREATED + + def test_a_naive_time_is_utc(self): + from app.services.release_council_service import decision_evaluated_at + + naive = _council(input_snapshot={"assembled_at": "2026-11-20T09:00:00"}) + assert decision_evaluated_at(naive) == ASSEMBLED + + def test_no_time_at_all_is_none(self): + from app.services.release_council_service import decision_evaluated_at + + assert decision_evaluated_at(_council(input_snapshot=None, created_at=None)) is None + + +class TestTheQuery: + @pytest.mark.asyncio + async def test_one_read_only_statement_over_both_records(self): + from sqlalchemy.dialects import postgresql + + from app.services.release_council_service import analysis_changed_since + + db = SimpleNamespace(execute=AsyncMock( + return_value=SimpleNamespace(scalar_one_or_none=lambda: CORRECTED) + )) + assert await analysis_changed_since(db, RUN, ASSEMBLED) == CORRECTED + (stmt,), _ = db.execute.await_args + sql = str(stmt.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True})) + assert sql.lstrip().upper().startswith("SELECT") + assert "greatest(" in sql + assert "ai_analysis_versions" in sql and "ai_feedback" in sql + assert "'human_correction'" in sql and "'bulk_reclassify'" in sql + assert "'incorrect'" in sql and "corrected_category IS NOT NULL" in sql + assert sql.count(RUN.hex[:8]) >= 2 # both halves are scoped to the run + assert sql.count("2026-11-20 09:00:00") == 2 # both halves: after the decision + + @pytest.mark.asyncio + async def test_with_the_pipeline_the_root_cause_start_is_the_read_time(self): + """Review F3: the root-cause stage read the analyses and corrections the + decision scored, minutes before ``assembled_at``. A correction saved in + between must count, so the comparison is against LEAST(stage start, + decided_at), and the stage start is the decision's own pipeline's.""" + from sqlalchemy.dialects import postgresql + + from app.services.release_council_service import analysis_changed_since + + pipeline = uuid.uuid4() + db = SimpleNamespace(execute=AsyncMock( + return_value=SimpleNamespace(scalar_one_or_none=lambda: CORRECTED) + )) + await analysis_changed_since(db, RUN, ASSEMBLED, pipeline) + (stmt,), _ = db.execute.await_args + sql = str(stmt.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True})) + assert "agent_stage_results" in sql and "'root_cause_analysis'" in sql + assert sql.count("least(") == 2 # both halves compare against the read time + assert pipeline.hex[:8] in sql + + @pytest.mark.asyncio + async def test_without_a_pipeline_the_decision_time_is_used(self): + from sqlalchemy.dialects import postgresql + + from app.services.release_council_service import analysis_changed_since + + db = SimpleNamespace(execute=AsyncMock( + return_value=SimpleNamespace(scalar_one_or_none=lambda: None) + )) + await analysis_changed_since(db, RUN, ASSEMBLED, None) + (stmt,), _ = db.execute.await_args + sql = str(stmt.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True})) + assert "agent_stage_results" not in sql and "least(" not in sql + + @pytest.mark.asyncio + async def test_nothing_found_is_none(self): + from app.services.release_council_service import analysis_changed_since + + db = SimpleNamespace(execute=AsyncMock( + return_value=SimpleNamespace(scalar_one_or_none=lambda: None) + )) + assert await analysis_changed_since(db, RUN, ASSEMBLED) is None + + +async def _route(monkeypatch, council, changed_at, pipeline_run_id=None): + from app.routers import release_readiness + from app.services import report_distribution_policy as policy + from app.services.review_envelope import not_ai_generated + + monkeypatch.setattr(release_readiness, "get_release_council", AsyncMock(return_value=council)) + monkeypatch.setattr( + policy, "release_review_projection", + AsyncMock(return_value=(not_ai_generated(), False, False)), + ) + probe = AsyncMock(return_value=changed_at) + monkeypatch.setattr(release_readiness, "analysis_changed_since", probe) + db = SimpleNamespace( + execute=AsyncMock(return_value=SimpleNamespace(first=lambda: (pipeline_run_id, uuid.uuid4()))), + commit=AsyncMock(), + ) + out = await release_readiness.get_release_decision( + RUN, allow_advisory=False, + current_user=SimpleNamespace(id=uuid.uuid4(), role="QA_ENGINEER"), db=db, + ) + return out, probe + + +class TestTheGateRead: + @pytest.mark.asyncio + async def test_a_correction_after_the_decision_is_reported(self, monkeypatch): + council = _council() + out, probe = await _route(monkeypatch, council, CORRECTED) + + assert out.analysis_changed_since is True + assert out.analysis_changed_at == CORRECTED + assert probe.await_args.args[1:] == (RUN, ASSEMBLED, None) + # The stored decision is reported as it is: nothing recomputed. + assert out.recommendation == "GO" and out.risk_score == 12 + assert council.analysis_changed_since is False + + @pytest.mark.asyncio + async def test_the_route_passes_the_decisions_pipeline(self, monkeypatch): + """Review F3: the stored decision's pipeline reaches the query, so its + root-cause start is the read time.""" + pipeline = uuid.uuid4() + out, probe = await _route(monkeypatch, _council(), CORRECTED, pipeline_run_id=pipeline) + + assert probe.await_args.args[1:] == (RUN, ASSEMBLED, pipeline) + assert out.analysis_changed_since is True + + @pytest.mark.asyncio + async def test_no_later_correction_reports_nothing(self, monkeypatch): + out, probe = await _route(monkeypatch, _council(), None) + + probe.assert_awaited_once() + assert out.analysis_changed_since is False and out.analysis_changed_at is None + + @pytest.mark.asyncio + async def test_a_quick_look_is_not_checked(self, monkeypatch): + """A quick look is computed now, from the current categories.""" + out, probe = await _route(monkeypatch, _council(synthesized=True, created_at=None), CORRECTED) + + probe.assert_not_awaited() + assert out.analysis_changed_since is False + + @pytest.mark.asyncio + async def test_the_json_carries_the_time(self, monkeypatch): + out, _probe = await _route(monkeypatch, _council(), CORRECTED) + + body = out.model_dump(mode="json") + assert body["analysis_changed_since"] is True + assert datetime.fromisoformat(body["analysis_changed_at"]) == CORRECTED + + +def test_the_response_model_defaults_to_unchanged(): + bare = ReleaseCouncilResponse(run_id=str(RUN), recommendation="GO", risk_score=0) + assert bare.analysis_changed_since is False and bare.analysis_changed_at is None diff --git a/backend/tests/regression/test_quick_look_applies_the_policy_whole.py b/backend/tests/regression/test_quick_look_applies_the_policy_whole.py new file mode 100644 index 000000000..2cd148053 --- /dev/null +++ b/backend/tests/regression/test_quick_look_applies_the_policy_whole.py @@ -0,0 +1,332 @@ +"""D-142: the quick look evaluates with the project's effective policy, whole. + +Before: ``_synthesize_release_council`` scored with the built-in thresholds, +hard-coded ``policy_level="hardcoded"``, and then layered the published +policy's pass-rate bands and P0 cap on top. A policy was half applied (its +bands moved the verdict, its thresholds, weights and rules did not) and the +gate footer read "Evaluated with system defaults · pass-rate bands: project +policy v1". + +After: one resolution of the effective policy feeds the stored decision's own +evaluator (thresholds, weights, the rules a quick look has inputs for) and the +band floor. With no policy the verdict, score and footer fields are exactly +what they were (the identity grid below replays the old algorithm). +""" +from __future__ import annotations + +import uuid +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +pytest.importorskip("sqlalchemy") + + +class _Scalar: + def __init__(self, value): + self._v = value + + def scalar_one_or_none(self): + return self._v + + +def _run(pass_rate): + return SimpleNamespace( + id=uuid.uuid4(), pass_rate=pass_rate, project_id=uuid.uuid4(), + build_number="b-142", status="FAILED", + ) + + +def _signals(*, by_severity=None, blocking_failures=0, blocking_defects=0): + by_severity = dict(by_severity or {}) + return { + "blocking_failures": blocking_failures, + "open_defects_by_severity": by_severity, + "open_defects": sum(by_severity.values()), + "blocking_defects": blocking_defects, + } + + +@pytest.fixture +def world(monkeypatch): + """Patch the run's signals, the policy resolution and the P0 count; the + session then sees exactly one read, the run itself.""" + from app.services import metrics_service, run_release_signals + + state = SimpleNamespace(signals=_signals(), policy=None, p0=0) + monkeypatch.setattr( + run_release_signals, "load_run_release_signals", + AsyncMock(side_effect=lambda *a, **k: state.signals), + ) + monkeypatch.setattr( + metrics_service, "_resolve_active_policy_for_project", + AsyncMock(side_effect=lambda *a, **k: state.policy), + ) + monkeypatch.setattr( + metrics_service, "count_open_critical_defects", + AsyncMock(side_effect=lambda *a, **k: state.p0), + ) + return state + + +async def _quick_look(run): + from app.services.release_council_service import _synthesize_release_council + + db = SimpleNamespace(execute=AsyncMock(side_effect=[_Scalar(run)])) + return await _synthesize_release_council(run.id, db) + + +def _old_quick_look(pass_rate, signals): + """The pre-D-142 algorithm, verbatim, for the no-policy identity check.""" + from app.core.config import settings + from app.services.criticality_service import ( + HARD_FLOOR_FACTOR, + apply_verdict_floor, + compute_composite, + compute_dimension_scores, + score_to_recommendation, + ) + + threshold = float(settings.RELEASE_PASS_RATE_THRESHOLD) + dims = compute_dimension_scores( + analyses={}, anomalies=[], pass_rate=pass_rate, is_regression=False, + regression_tests=[], failure_clusters=[], + open_defects=signals["open_defects_by_severity"] or int(signals["open_defects"]), + ) + composite = compute_composite(dims) + if pass_rate < threshold * HARD_FLOOR_FACTOR: + composite = max(composite, 60.0) + rec = score_to_recommendation(composite, pass_rate, threshold) + rec, reasons = apply_verdict_floor( + rec, + blocking_failures=int(signals["blocking_failures"]), + blocking_defects=int(signals["blocking_defects"]), + ) + return rec, composite, reasons, threshold + + +_GRID_SIGNALS = [ + _signals(), + _signals(by_severity={"MEDIUM": 3}), + _signals(by_severity={"HIGH": 1}, blocking_defects=1), + _signals(by_severity={"LOW": 2}, blocking_failures=2), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("pass_rate", [100.0, 95.0, 93.8, 89.0, 70.0, 64.0, 62.0, 50.0, 0.0]) +@pytest.mark.parametrize("signals", _GRID_SIGNALS) +async def test_no_policy_leaves_verdict_score_and_footer_exactly_as_before(world, pass_rate, signals): + from app.services.release_council_service import _quick_look_conditions + + world.signals = signals + world.policy = None + result = await _quick_look(_run(pass_rate)) + + rec, composite, reasons, threshold = _old_quick_look(pass_rate, signals) + assert result.recommendation == rec + assert result.composite_risk == composite + assert result.risk_score == int(composite // 1) + # The footer's fields: "Evaluated with system defaults", no band policy. + assert result.policy_level == "hardcoded" + assert result.policy_id is None and result.policy_version is None + assert result.band_policy_level is None and result.release_readiness_band is None + assert result.rule_evaluations == [] and result.blocking_issues == [] + assert result.conditions_for_go == ( + [f"Resolve: {r}" for r in reasons] + _quick_look_conditions(rec, pass_rate, threshold) + ) + assert result.input_snapshot["threshold"] == threshold + assert result.input_snapshot["no_go_floor_pct"] == round(threshold * 0.7, 2) + + +def _policy(document, *, version=1, level="project"): + return (document, "pol-142", version, level) + + +GREEN_BANDS = {"green_min": 90.0, "yellow_min": 85.0, "orange_min": 80.0} + + +@pytest.mark.asyncio +async def test_a_policy_pass_rate_minimum_applies_and_the_level_is_true(world): + """The finding's own case: minimum 95, a 93.8% run. Built-in 90 said GO.""" + world.policy = _policy({"thresholds": {"pass_rate_minimum": 95.0}, "pass_rate_bands": GREEN_BANDS}) + result = await _quick_look(_run(93.8)) + + assert result.recommendation == "CONDITIONAL_GO" + assert result.policy_level == "project" + assert result.policy_id == "pol-142" and result.policy_version == 1 + assert result.band_policy_level == "project" and result.band_policy_version == 1 + assert result.input_snapshot["threshold"] == 95.0 + assert result.input_snapshot["no_go_floor_pct"] == round(95.0 * 0.7, 2) + assert any("95.0%" in c for c in result.conditions_for_go) + + +@pytest.mark.asyncio +async def test_a_policy_risk_line_applies(world): + """A Go line of 5: the quick look's ~6 risk is Conditional, not Go.""" + world.policy = _policy({ + "thresholds": {"go_threshold": 5.0, "no_go_threshold": 40.0}, + "pass_rate_bands": GREEN_BANDS, + }, level="system", version=7) + result = await _quick_look(_run(100.0)) + + assert result.recommendation == "CONDITIONAL_GO" + assert result.policy_level == "system" and result.policy_version == 7 + assert result.input_snapshot["go_threshold"] == 5.0 + assert result.input_snapshot["no_go_threshold"] == 40.0 + + +@pytest.mark.asyncio +async def test_an_open_defect_rule_the_quick_look_can_measure_is_applied(world): + world.signals = _signals(by_severity={"MEDIUM": 3}) + world.policy = _policy({ + "pass_rate_bands": GREEN_BANDS, + "rules": [{ + "id": "r-defects", "name": "Open defect limit", "type": "open_defect_limit", + "params": {"max_open_defects": 1, "action": "BLOCK"}, + }], + }) + result = await _quick_look(_run(100.0)) + + assert result.recommendation == "NO_GO" + assert [ev.rule_id for ev in result.rule_evaluations] == ["r-defects"] + assert result.rule_evaluations[0].passed is False + assert result.blocking_issues and result.blocking_issues[0].startswith("[Policy] ") + + +@pytest.mark.asyncio +async def test_rules_the_quick_look_cannot_measure_are_named_not_passed(world): + """No flaky count on a quick look: the rule is listed as not checked, never + evaluated against a zero that would read as a pass.""" + world.policy = _policy({ + "pass_rate_bands": GREEN_BANDS, + "rules": [ + {"id": "r-flaky", "name": "Flaky test limit", "type": "flaky_recurrence", + "params": {"max_flaky_tests": 0, "action": "BLOCK"}}, + {"id": "r-off", "name": "Disabled", "type": "flaky_recurrence", "enabled": False, + "params": {}}, + ], + }) + result = await _quick_look(_run(100.0)) + + assert result.rule_evaluations == [] + assert result.input_snapshot["rules_not_checked"] == [ + {"id": "r-flaky", "name": "Flaky test limit", "type": "flaky_recurrence"}, + ] + assert result.recommendation == "GO" + + +# ── Review F1: the bands that can floor the verdict are published ──────────── +# +# Every policy saved from the editor carries the band defaults (red under 90, +# orange 90-95). A 92% run at risk ~6 is Conditional because of the orange band +# and an 85% run is No-Go because of the red band; the response must carry the +# band edges and say that the band moved the verdict, or the gate card states +# thresholds ("Go under risk 20 and at 90% or more") its own verdict contradicts. + + +@pytest.mark.asyncio +async def test_a_92_percent_run_is_held_back_by_the_orange_band(world): + world.policy = _policy({"rules": []}) # no bands in the document: the classifier's defaults + result = await _quick_look(_run(92.0)) + + assert result.recommendation == "CONDITIONAL_GO" + assert result.release_readiness_band == "orange" + assert result.pass_rate_bands == {"orange_min": 90.0, "yellow_min": 95.0, "green_min": 99.0} + assert result.band_held_back is True + + +@pytest.mark.asyncio +async def test_an_85_percent_run_is_held_back_by_the_red_band(world): + world.policy = _policy({"pass_rate_bands": {"orange_min": 90, "yellow_min": 95, "green_min": 99}}) + result = await _quick_look(_run(85.0)) + + assert result.recommendation == "NO_GO" + assert result.release_readiness_band == "red" + assert result.band_held_back is True + + +@pytest.mark.asyncio +async def test_a_band_that_agrees_or_a_hard_cap_is_not_a_band_hold(world): + world.policy = _policy({"pass_rate_bands": GREEN_BANDS}) + agreed = await _quick_look(_run(100.0)) + assert agreed.recommendation == "GO" and agreed.band_held_back is False + assert agreed.pass_rate_bands == {"orange_min": 80.0, "yellow_min": 85.0, "green_min": 90.0} + + world.p0 = 1 + world.policy = _policy({"pass_rate_bands": GREEN_BANDS, "hard_caps": {"max_p0_defects": 0}}) + capped = await _quick_look(_run(100.0)) + assert capped.recommendation == "NO_GO" and capped.band_downgrades == ["p0_defects:1>0"] + assert capped.band_held_back is False # band_downgrades names the cap + + +@pytest.mark.asyncio +async def test_no_policy_publishes_no_bands(world): + result = await _quick_look(_run(92.0)) + assert result.pass_rate_bands is None and result.band_held_back is False + + +class _Rows: + def __init__(self, value): + self._v = value + + def scalar_one_or_none(self): + return self._v + + def scalars(self): + return SimpleNamespace(all=lambda: self._v) + + def all(self): + return self._v + + +def _stored(recommendation="GO", human_override=None): + return SimpleNamespace( + test_run_id=uuid.uuid4(), recommendation=recommendation, risk_score=10, composite_risk=10.0, + dimension_scores=None, blocking_issues=[], conditions_for_go=[], reasoning="stored", + score_model_version=2, input_snapshot={}, human_override=human_override, overridden_by=None, + original_recommendation=None, original_risk_score=None, override_audit=[], policy_id=None, + policy_evaluation=None, created_at=None, updated_at=None, + ) + + +async def _stored_council(decision, run): + from app.services.release_council_service import get_release_council + + db = SimpleNamespace(execute=AsyncMock(side_effect=[ + _Rows(decision), _Rows(run), _Rows([]), _Rows([]), # decision, run, clusters, defects by component + ])) + return await get_release_council(run.id, db) + + +@pytest.mark.asyncio +async def test_a_stored_go_held_back_by_the_band_says_so(world): + world.policy = _policy({"rules": []}) + council = await _stored_council(_stored("GO"), _run(92.0)) + + assert council.recommendation == "CONDITIONAL_GO" + assert council.original_recommendation == "GO" + assert council.pass_rate_bands == {"orange_min": 90.0, "yellow_min": 95.0, "green_min": 99.0} + assert council.band_held_back is True + + +@pytest.mark.asyncio +async def test_an_overridden_stored_decision_has_no_band_floor(world): + world.policy = _policy({"rules": []}) + council = await _stored_council(_stored("GO", human_override="accepted"), _run(92.0)) + + assert council.recommendation == "GO" + assert council.pass_rate_bands is None and council.band_held_back is False + + +@pytest.mark.asyncio +async def test_the_band_floor_still_applies_from_the_same_policy(world): + """The P0 cap of the one resolved policy still forces No-Go.""" + world.p0 = 2 + world.policy = _policy({"pass_rate_bands": GREEN_BANDS, "hard_caps": {"max_p0_defects": 0}}) + result = await _quick_look(_run(100.0)) + + assert result.recommendation == "NO_GO" + assert result.band_downgrades == ["p0_defects:2>0"] + assert result.policy_level == "project" diff --git a/backend/tests/regression/test_release_gate_policy_delete_draft.py b/backend/tests/regression/test_release_gate_policy_delete_draft.py new file mode 100644 index 000000000..66b7b218c --- /dev/null +++ b/backend/tests/regression/test_release_gate_policy_delete_draft.py @@ -0,0 +1,411 @@ +"""D-141: a release-gate policy DRAFT that was never published can be deleted. + +Published versions stay (past verdicts and the version history name them, so +they are deactivated instead), and so does a draft a stored decision points +at. The route is ``DELETE /api/v1/release-gate-policies/{policy_id}``: ADMIN, +the same project-bound key confinement as publish / deactivate, and one +``policy.updated`` activity row (``changed: draft deleted``) committed with +the delete. + +The handler is driven directly against a fake session that answers by +statement text (the pattern of ``test_release_gate_policy_single_active.py``); +the role floor goes through the real app's dependency tree. +""" +from __future__ import annotations + +import asyncio +import uuid +from datetime import datetime, timezone +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import HTTPException +from sqlalchemy.dialects import postgresql +from sqlalchemy.exc import InvalidRequestError +from sqlalchemy.orm.exc import StaleDataError + +from app.core import deps +from app.models.postgres import ReleaseGatePolicy, UserRole +from app.routers import release_gate_policies as router + +pytestmark = pytest.mark.regression + + +class _Result: + def __init__(self, rows=None): + self._rows = list(rows or []) + + def scalar_one_or_none(self): + return self._rows[0] if self._rows else None + + def scalars(self): + return SimpleNamespace(all=lambda: list(self._rows)) + + +class _Db: + """Answers by statement text and records the order of everything.""" + + def __init__(self, *, policy, decision_refs=(), gate_refs=()): + self.policy = policy + self.decision_refs = list(decision_refs) + self.gate_refs = list(gate_refs) + self.log: list[str] = [] + self.deleted: list = [] + + async def execute(self, stmt, params=None): + sql = ( + " ".join(str(stmt.compile(dialect=postgresql.dialect())).split()) + if hasattr(stmt, "compile") else str(stmt) + ) + if "pg_advisory_xact_lock" in sql: + self.log.append(f"lock:{(params or {}).get('key')}") + return _Result() + if "FROM release_gate_policies WHERE release_gate_policies.id =" in sql: + self.log.append("load-policy") + return _Result([self.policy] if self.policy is not None else []) + if "FROM release_decisions" in sql: + self.log.append("decision-refs") + return _Result(self.decision_refs) + if "FROM release_gate_decisions" in sql: + self.log.append("gate-refs") + return _Result(self.gate_refs) + raise AssertionError(f"unexpected statement: {sql}") + + async def delete(self, obj): + self.log.append("delete") + self.deleted.append(obj) + + async def commit(self): + self.log.append("commit") + + async def rollback(self): + self.log.append("rollback") + + +class _RaceDb(_Db): + """A publish / PATCH session whose draft another admin deletes mid-request. + + ``deleted_after_lock``: the DELETE committed while this request waited for + the scope lock, so the re-read (``refresh``) finds no row -- SQLAlchemy + raises ``InvalidRequestError`` ("Could not refresh instance"). + ``deleted_before_commit``: the DELETE committed between PATCH's read and + its commit, so the UPDATE matches 0 rows -- ``StaleDataError``. (Both + exception types checked against a real SQLite session while writing this.) + """ + + def __init__(self, *, policy, deleted_after_lock=False, deleted_before_commit=False): + super().__init__(policy=policy) + self.deleted_after_lock = deleted_after_lock + self.deleted_before_commit = deleted_before_commit + + async def execute(self, stmt, params=None): + sql = ( + " ".join(str(stmt.compile(dialect=postgresql.dialect())).split()) + if hasattr(stmt, "compile") else str(stmt) + ) + if sql.startswith("SELECT release_gate_policies.id FROM"): + self.log.append("active-ids") + return _Result() + if "FROM projects" in sql: # a system-default publish bumps every project + return _Result() + return await super().execute(stmt, params) + + def add(self, obj): + self.log.append("add") + + async def flush(self): + self.log.append("flush") + + async def refresh(self, obj): + self.log.append("refresh") + if self.deleted_after_lock: + raise InvalidRequestError(f"Could not refresh instance '{obj!r}'") + + async def commit(self): + if self.deleted_before_commit: + self.log.append("commit-refused") + raise StaleDataError( + "UPDATE statement on table 'release_gate_policies' expected to update 1 row(s); 0 were matched." + ) + self.log.append("commit") + + +ADMIN = SimpleNamespace(id=uuid.uuid4(), role="ADMIN", username="admin", is_active=True) + + +def _policy(project_id, *, draft=True, active=False, activated_at=None): + return ReleaseGatePolicy( + id=uuid.uuid4(), project_id=project_id, version=3, name="Checkout gate", rules={}, + is_draft=draft, is_active=active, activated_at=activated_at, created_by=ADMIN.id, + ) + + +@pytest.fixture +def events(monkeypatch): + """Every activity row the route stages, instead of the ledger write.""" + recorded: list[dict] = [] + + async def _record(db, **kwargs): + db.log.append("activity") + recorded.append(kwargs) + + monkeypatch.setattr(router, "record_activity", _record) + return recorded + + +@pytest.fixture(autouse=True) +def _admin_scope(): + # An ADMIN resolves to every project: no membership read. + with patch("app.core.deps.get_accessible_project_ids", AsyncMock(return_value=None)): + yield + + +def _delete(policy_id, db, user=ADMIN): + return asyncio.run(router.delete_policy(policy_id, current_user=user, db=db)) + + +@pytest.mark.parametrize("scope", ["project", "system"]) +def test_a_never_published_draft_is_deleted_with_one_activity_row(scope, events): + pid = uuid.uuid4() if scope == "project" else None + draft = _policy(pid) + db = _Db(policy=draft) + + response = _delete(draft.id, db) + + assert response.status_code == 204 + assert db.deleted == [draft] + key = f"lock:release_gate_policy:{pid if pid else 'system'}" + # Locked, then re-read under the lock, before anything is decided. + assert db.log.index(key) < db.log.index("load-policy", 1) + assert db.log.index("delete") < db.log.index("commit") + if pid is None: + # The system default has no project feed (as for publish / deactivate). + assert events == [] + else: + assert db.log.index("activity") < db.log.index("delete") + assert len(events) == 1 + assert events[0]["event_type"] == "policy.updated" + assert events[0]["context"] == {"changed": "draft deleted"} + assert events[0]["entity_id"] == draft.id + assert events[0]["entity_label"] == "Checkout gate v3" + + +@pytest.mark.parametrize( + "state", + [ + {"draft": False, "active": True}, + {"draft": False, "active": False}, + # Defensive: a row that was activated once is not a never-published draft. + {"draft": True, "active": False, "activated_at": datetime(2026, 11, 1, tzinfo=timezone.utc)}, + ], + ids=["active", "past-version", "activated-once"], +) +def test_a_version_that_was_ever_published_is_refused_with_409(state, events): + policy = _policy(uuid.uuid4(), **state) + db = _Db(policy=policy) + + with pytest.raises(HTTPException) as exc: + _delete(policy.id, db) + + assert exc.value.status_code == 409 + assert exc.value.detail == router.DELETE_PUBLISHED_DETAIL + assert db.deleted == [] and "commit" not in db.log and events == [] + + +@pytest.mark.parametrize("table", ["decision", "gate"]) +def test_a_draft_a_stored_decision_names_is_refused_with_409(table, events): + draft = _policy(uuid.uuid4()) + refs = {"decision_refs": [uuid.uuid4()]} if table == "decision" else {"gate_refs": [uuid.uuid4()]} + db = _Db(policy=draft, **refs) + + with pytest.raises(HTTPException) as exc: + _delete(draft.id, db) + + assert exc.value.status_code == 409 + assert exc.value.detail == router.DELETE_REFERENCED_DETAIL + assert db.deleted == [] and "commit" not in db.log and events == [] + + +def test_a_draft_published_while_waiting_for_the_lock_is_refused(events): + draft = _policy(uuid.uuid4()) + db = _Db(policy=draft) + real = db.execute + + async def _execute(stmt, params=None): + result = await real(stmt, params) + if db.log[-1].startswith("lock:"): + # Another admin's publish committed before this request got the lock. + draft.is_draft, draft.is_active = False, True + return result + + db.execute = _execute + with pytest.raises(HTTPException) as exc: + _delete(draft.id, db) + assert exc.value.status_code == 409 + assert db.deleted == [] + + +def test_an_unknown_policy_is_404(events): + db = _Db(policy=None) + with pytest.raises(HTTPException) as exc: + _delete(uuid.uuid4(), db) + assert exc.value.status_code == 404 + + +def _bound_key(project_id: uuid.UUID) -> SimpleNamespace: + user = SimpleNamespace(id=uuid.uuid4(), role="ADMIN", username="ci-key", is_active=True) + setattr(user, deps._API_KEY_BOUND_PROJECT_ATTR, project_id) + return user + + +def test_a_key_bound_to_another_project_is_refused_403(events): + draft = _policy(uuid.uuid4()) + db = _Db(policy=draft) + with pytest.raises(HTTPException) as exc: + _delete(draft.id, db, user=_bound_key(uuid.uuid4())) + assert exc.value.status_code == 403 + assert db.log == ["load-policy"] and db.deleted == [] + + +def test_a_bound_key_may_not_delete_a_system_default_draft(events): + draft = _policy(None) + db = _Db(policy=draft) + with pytest.raises(HTTPException) as exc: + _delete(draft.id, db, user=_bound_key(uuid.uuid4())) + assert exc.value.status_code == 403 + assert exc.value.detail == router.SYSTEM_DEFAULT_REFUSED_DETAIL + assert db.deleted == [] + + +def test_a_key_bound_to_the_drafts_own_project_may_delete_it(events): + pid = uuid.uuid4() + draft = _policy(pid) + db = _Db(policy=draft) + with patch("app.core.deps.get_accessible_project_ids", AsyncMock(return_value={pid})): + response = _delete(draft.id, db, user=_bound_key(pid)) + assert response.status_code == 204 + assert db.deleted == [draft] + + +# ── review F4: publish / PATCH racing the delete answer 404, not 500 ──────── + + +@pytest.fixture +def _no_cache_bump(monkeypatch): + import app.services.cache_service as cache_service + + async def _noop(*_a, **_kw): + return None + + monkeypatch.setattr(cache_service, "bump_analytics_epochs", _noop) + + +def test_a_publish_whose_draft_was_deleted_while_it_waited_for_the_lock_is_404(events, _no_cache_bump): + pid = uuid.uuid4() + draft = _policy(pid) + db = _RaceDb(policy=draft, deleted_after_lock=True) + + with pytest.raises(HTTPException) as exc: + asyncio.run(router.publish_policy(draft.id, current_user=ADMIN, db=db)) + + assert exc.value.status_code == 404 + assert exc.value.detail == router.DRAFT_DELETED_DETAIL == "This draft was deleted." + # The lock came first, then the re-read that found the row gone; nothing written. + assert db.log.index(f"lock:release_gate_policy:{pid}") < db.log.index("refresh") + assert "commit" not in db.log and events == [] + + +def test_an_edit_whose_draft_was_deleted_before_its_commit_is_404(events): + from app.models.schemas import ReleaseGatePolicyUpdate + + draft = _policy(uuid.uuid4()) + db = _RaceDb(policy=draft, deleted_before_commit=True) + + with pytest.raises(HTTPException) as exc: + asyncio.run(router.update_policy( + draft.id, ReleaseGatePolicyUpdate(name="Renamed"), current_user=ADMIN, db=db, + )) + + assert exc.value.status_code == 404 + assert exc.value.detail == router.DRAFT_DELETED_DETAIL + assert db.log[-2:] == ["commit-refused", "rollback"] + + +# ── review F5: the system default records no activity, for every write ────── + + +def test_system_default_writes_record_nothing_publish_and_delete_alike(events, _no_cache_bump): + """Kept consistent on purpose: ``_record_policy_event`` skips a policy with + no project (the project activity ledger has no feed for it), for create, + edit, publish and deactivate alike; the delete follows the same rule and + leaves the ``logger.info`` line. If system-scope policy writes ever get an + audit home (``settings_audit_log``), all five move together.""" + publish_db = _RaceDb(policy=_policy(None)) + asyncio.run(router.publish_policy(publish_db.policy.id, current_user=ADMIN, db=publish_db)) + assert "commit" in publish_db.log + + delete_db = _Db(policy=_policy(None)) + _delete(delete_db.policy.id, delete_db) + assert delete_db.deleted + + assert events == [] + + +# ── the role floor, through the real app ──────────────────────────────────── + + +class _HandlerReached(Exception): + pass + + +class _Session: + def __init__(self): + self.touched = 0 + + def _reached(self, *_a, **_kw): + self.touched += 1 + raise _HandlerReached + + execute = scalar = scalars = get = commit = flush = delete = _reached + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "role", [UserRole.VIEWER, UserRole.TESTER, UserRole.QA_ENGINEER, UserRole.QA_LEAD], + ids=lambda r: r.value, +) +async def test_a_role_below_admin_is_refused_before_the_handler(role): + from httpx import ASGITransport, AsyncClient + + from app.core.deps import get_current_user_or_api_key + from app.db.postgres import get_db + from app.main import app + from app.models.postgres import User + + session = _Session() + uid = uuid.uuid4() + user = User( + id=uid, username=f"floor-{role.value.lower()}", email=f"floor-{uid.hex[:8]}@example.test", + role=role.value, is_active=True, must_change_password=False, hashed_password="!unusable", + ) + + async def _user(): + return user + + async def _db(): + yield session + + app.dependency_overrides[get_current_user_or_api_key] = _user + app.dependency_overrides[get_db] = _db + try: + transport = ASGITransport(app=app, raise_app_exceptions=False) + async with AsyncClient(transport=transport, base_url="http://floor.test") as client: + resp = await client.delete(f"/api/v1/release-gate-policies/{uuid.uuid4()}") + finally: + app.dependency_overrides.pop(get_current_user_or_api_key, None) + app.dependency_overrides.pop(get_db, None) + + assert resp.status_code == 403, resp.text + assert resp.json()["detail"] == "Requires at least ADMIN role" + assert session.touched == 0 diff --git a/backend/tests/regression/test_root_cause_stage_mixed_engine_d156.py b/backend/tests/regression/test_root_cause_stage_mixed_engine_d156.py new file mode 100644 index 000000000..1af8dc23f --- /dev/null +++ b/backend/tests/regression/test_root_cause_stage_mixed_engine_d156.py @@ -0,0 +1,177 @@ +"""D-156: the Root Cause stage says "mixed" when its tests ran on more than one engine. + +The defect +---------- +``AnalysisAgent.run`` summarised the stage with +``dominant_mode = max(mode_counts, key=mode_counts.get)`` and stored that one +engine as the stage's ``analysis_mode``. Three rules answers and one model +answer therefore read "rules" on the Deep Investigation page's Model routing +card; the full split sat in ``result_data.mode_distribution`` and was never +shown. + +What is guarded +--------------- +* more than one recorded engine -> ``analysis_mode == "mixed"``, with the split + kept in ``result_data.mode_distribution``; +* one engine keeps today's value (that engine), and a test whose engine was + not recorded ("unknown") is not a second engine; +* the decision trail exposes each stage's ``mode_distribution`` so the page + can print the split. +""" +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +pytest.importorskip("asyncpg") # skip module if the DB driver is absent + +from app.agents.analysis_agent import AnalysisAgent # noqa: E402 +from app.services.decision_trail_service import _summarize_stage # noqa: E402 + + +def _build_agent(outcomes: dict[str, dict]) -> AnalysisAgent: + """An AnalysisAgent whose per-test step returns ``outcomes`` verbatim.""" + agent = AnalysisAgent() + agent.mark_stage_running = AsyncMock() # type: ignore[method-assign] + agent.mark_stage_done = AsyncMock() # type: ignore[method-assign] + agent.broadcast_progress = AsyncMock() # type: ignore[method-assign] + agent.log_decision = AsyncMock() # type: ignore[method-assign] + agent._fetch_test_metadata = AsyncMock( # type: ignore[method-assign] + return_value={ + tc_id: {"test_name": f"name::{tc_id}", "suite_name": "checkout-suite"} + for tc_id in outcomes + } + ) + agent._fetch_human_corrections = AsyncMock(return_value={}) # type: ignore[method-assign] + agent._batch_upsert_analyses = AsyncMock() # type: ignore[method-assign] + agent._resolve_adaptive_concurrency = AsyncMock( # type: ignore[method-assign] + return_value={"concurrency": 2, "rationale": "pinned for the test"} + ) + + async def _fake_analyse(_semaphore, tc_id, _meta, _state): + return dict(outcomes[tc_id]) + + agent._analyse_with_retry = _fake_analyse # type: ignore[method-assign] + return agent + + +def _state(tc_ids) -> dict: + # A non-UUID project id keeps the LLM cost-budget check hermetic. + return { + "pipeline_run_id": "pipe-d156", + "project_id": "proj-d156", + "failed_test_ids": list(tc_ids), + } + + +def _analysis(mode: str | None, **audit) -> dict: + out: dict = {"confidence_score": 80, "failure_category": "PRODUCT_BUG"} + if mode is not None: + out["_audit"] = {"analysis_mode": mode, **audit} + return out + + +@pytest.mark.asyncio +async def test_one_model_and_three_rules_answers_store_mixed(): + outcomes = { + "tc-1": _analysis("llm"), + "tc-2": _analysis("rules", fallback_from="llm"), + "tc-3": _analysis("rules", fallback_from="llm"), + "tc-4": _analysis("rules", fallback_from="llm"), + } + agent = _build_agent(outcomes) + + await agent.run(_state(outcomes)) + + kwargs = agent.mark_stage_done.call_args.kwargs + assert kwargs["analysis_mode"] == "mixed" + assert kwargs["result_data"]["mode_distribution"] == {"llm": 1, "rules": 3} + assert kwargs["fallback_reason"] == "3/4 tests fell back from requested engine" + + +@pytest.mark.asyncio +async def test_one_engine_keeps_that_engine(): + outcomes = {"tc-1": _analysis("rules"), "tc-2": _analysis("rules")} + agent = _build_agent(outcomes) + + await agent.run(_state(outcomes)) + + kwargs = agent.mark_stage_done.call_args.kwargs + assert kwargs["analysis_mode"] == "rules" + assert kwargs["result_data"]["mode_distribution"] == {"rules": 2} + + +@pytest.mark.asyncio +async def test_an_unrecorded_engine_is_not_a_second_engine(): + outcomes = { + "tc-1": _analysis("llm"), + "tc-2": _analysis("llm"), + "tc-3": _analysis(None), + } + agent = _build_agent(outcomes) + + await agent.run(_state(outcomes)) + + kwargs = agent.mark_stage_done.call_args.kwargs + assert kwargs["analysis_mode"] == "llm" + assert kwargs["result_data"]["mode_distribution"] == {"llm": 2, "unknown": 1} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("non_engine", ["hint", "human_corrected"]) +async def test_a_hint_or_a_human_correction_is_not_a_second_engine(non_engine): + """Review F6: a rules-only run with a hint or a replayed correction is not "mixed".""" + outcomes = { + "tc-1": _analysis("rules"), + "tc-2": _analysis("rules"), + "tc-3": _analysis(non_engine), + } + agent = _build_agent(outcomes) + + await agent.run(_state(outcomes)) + + kwargs = agent.mark_stage_done.call_args.kwargs + assert kwargs["analysis_mode"] == "rules" + assert kwargs["result_data"]["mode_distribution"] == {"rules": 2, non_engine: 1} + + +@pytest.mark.asyncio +async def test_model_and_rules_with_a_correction_is_still_mixed(): + outcomes = { + "tc-1": _analysis("llm"), + "tc-2": _analysis("rules"), + "tc-3": _analysis("human_corrected"), + } + agent = _build_agent(outcomes) + + await agent.run(_state(outcomes)) + + assert agent.mark_stage_done.call_args.kwargs["analysis_mode"] == "mixed" + + +def _stage(**overrides) -> SimpleNamespace: + base = dict( + stage_name="root_cause_analysis", status="completed", started_at=None, + completed_at=None, analysis_mode="mixed", fallback_used=True, + fallback_reason="3/4 tests fell back from requested engine", + route_rationale=None, error_category=None, skipped_reason=None, + execution_path=None, confidence_score=None, evidence_count=None, + input_tokens=None, output_tokens=None, cost_usd=None, decision_log=None, + result_data={"analysed": 4, "mode_distribution": {"llm": 1, "rules": 3}}, + ) + base.update(overrides) + return SimpleNamespace(**base) + + +def test_the_decision_trail_exposes_each_stages_split(): + summary = _summarize_stage(_stage()) # type: ignore[arg-type] + assert summary["analysis_mode"] == "mixed" + assert summary["mode_distribution"] == {"llm": 1, "rules": 3} + + +def test_a_stage_without_a_split_exposes_none(): + assert _summarize_stage(_stage(result_data=None))["mode_distribution"] is None # type: ignore[arg-type] + junk = _stage(result_data={"mode_distribution": "junk"}) + assert _summarize_stage(junk)["mode_distribution"] is None # type: ignore[arg-type] diff --git a/backend/tests/security_role_floor_snapshot.json b/backend/tests/security_role_floor_snapshot.json index 43dea2d27..bf47fb90b 100644 --- a/backend/tests/security_role_floor_snapshot.json +++ b/backend/tests/security_role_floor_snapshot.json @@ -17,6 +17,7 @@ "DELETE /api/v1/projects/{project_id}/timeline-notes/{note_id}": {"role": "QA_ENGINEER"}, "DELETE /api/v1/projects/{project_id}/workflows/defaults/{base}": {"project_role": "QA_LEAD"}, "DELETE /api/v1/projects/{project_id}/workflows/{workflow_id}": {"project_role": "QA_LEAD"}, + "DELETE /api/v1/release-gate-policies/{policy_id}": {"role": "ADMIN"}, "DELETE /api/v1/releases/{release_id}": {"role": "ADMIN"}, "DELETE /api/v1/releases/{release_id}/phases/{phase_id}": {"role": "ADMIN"}, "DELETE /api/v1/releases/{release_id}/test-runs/{run_id}": {"role": "ADMIN"}, diff --git a/docs/reference/api-index.md b/docs/reference/api-index.md index e3f51837a..e807cb1d0 100644 --- a/docs/reference/api-index.md +++ b/docs/reference/api-index.md @@ -435,6 +435,7 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de | GET | `/api/v1/release-gate-policies/history/{project_id}` | Get Policy History | [Release Gate Policies](api/release-gate-policies.md) | | POST | `/api/v1/release-gate-policies/simulate` | Simulate Policy | [Release Gate Policies](api/release-gate-policies.md) | | GET | `/api/v1/release-gate-policies/system-history` | Get System Policy History | [Release Gate Policies](api/release-gate-policies.md) | +| DELETE | `/api/v1/release-gate-policies/{policy_id}` | Delete Policy | [Release Gate Policies](api/release-gate-policies.md) | | GET | `/api/v1/release-gate-policies/{policy_id}` | Get Policy | [Release Gate Policies](api/release-gate-policies.md) | | PATCH | `/api/v1/release-gate-policies/{policy_id}` | Update Policy | [Release Gate Policies](api/release-gate-policies.md) | | POST | `/api/v1/release-gate-policies/{policy_id}/deactivate` | Deactivate Policy | [Release Gate Policies](api/release-gate-policies.md) | @@ -763,4 +764,4 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de | POST | `/webhooks/minio` | Minio Webhook | [Webhooks](api/webhooks.md) | | POST | `/ws/events/{run_id}` | Ingest Live Event | [Live Reporting](api/live-reporting.md) | -Total: **754 HTTP operations**, **639 paths**, **92 domain pages**. +Total: **755 HTTP operations**, **639 paths**, **92 domain pages**. diff --git a/docs/reference/api/release-gate-policies.md b/docs/reference/api/release-gate-policies.md index 8fc746f34..42b75f2e9 100644 --- a/docs/reference/api/release-gate-policies.md +++ b/docs/reference/api/release-gate-policies.md @@ -10,7 +10,7 @@ List Policies List all release gate policies with optional filters. -Source: [backend/app/routers/release_gate_policies.py:160](../../../backend/app/routers/release_gate_policies.py#L160). +Source: [backend/app/routers/release_gate_policies.py:181](../../../backend/app/routers/release_gate_policies.py#L181). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -121,7 +121,7 @@ Create a new draft policy (ADMIN only). A project-bound API key may create drafts for its own project only, never for another project or the system default (re-audit N20). -Source: [backend/app/routers/release_gate_policies.py:299](../../../backend/app/routers/release_gate_policies.py#L299). +Source: [backend/app/routers/release_gate_policies.py:320](../../../backend/app/routers/release_gate_policies.py#L320). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -208,7 +208,7 @@ Get Effective Policy Get the resolved effective policy for a project (project → system → None). -Source: [backend/app/routers/release_gate_policies.py:197](../../../backend/app/routers/release_gate_policies.py#L197). +Source: [backend/app/routers/release_gate_policies.py:218](../../../backend/app/routers/release_gate_policies.py#L218). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`. @@ -297,7 +297,7 @@ Get Policy History Get all policy versions for a project scope, ordered by version desc. -Source: [backend/app/routers/release_gate_policies.py:245](../../../backend/app/routers/release_gate_policies.py#L245). +Source: [backend/app/routers/release_gate_policies.py:266](../../../backend/app/routers/release_gate_policies.py#L266). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`. @@ -382,7 +382,7 @@ Simulate Policy Simulate a draft policy against a past run's decision data. -Source: [backend/app/routers/release_gate_policies.py:511](../../../backend/app/routers/release_gate_policies.py#L511). +Source: [backend/app/routers/release_gate_policies.py:603](../../../backend/app/routers/release_gate_policies.py#L603). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -470,7 +470,7 @@ Get System Policy History Get all system default policy versions, ordered by version desc. -Source: [backend/app/routers/release_gate_policies.py:261](../../../backend/app/routers/release_gate_policies.py#L261). +Source: [backend/app/routers/release_gate_policies.py:282](../../../backend/app/routers/release_gate_policies.py#L282). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -539,13 +539,101 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md } ``` +## DELETE `/api/v1/release-gate-policies/{policy_id}` + +Delete Policy + +Delete a draft that was never published (ADMIN only) (D-141). + +A version that was ever published stays: past verdicts and the version +history name it, so it is deactivated instead (409). A draft a stored +release decision points at is kept too (409). Records ``policy.updated`` +with ``changed: draft deleted`` in the same transaction, the way +deactivate records its edit of the active flag. + +Source: [backend/app/routers/release_gate_policies.py:542](../../../backend/app/routers/release_gate_policies.py#L542). + +Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. + +Declared Python handler arguments (includes exact role/guard options): + +```python +policy_id: uuid.UUID, current_user: User=Depends(require_role(UserRole.ADMIN, allow_project_key=True)), db: AsyncSession=Depends(get_db) +``` + +Direct handler error branches (dependency/service errors can add others): + +```python +HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Policy not found') +HTTPException(status_code=status.HTTP_409_CONFLICT, detail=DELETE_PUBLISHED_DETAIL) +HTTPException(status_code=status.HTTP_409_CONFLICT, detail=DELETE_REFERENCED_DETAIL) +``` + +### Declared wire contract + +References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json). + +```json +{ + "operationId": "delete_policy_api_v1_release_gate_policies__policy_id__delete", + "parameters": [ + { + "in": "path", + "name": "policy_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Policy Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-API-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Api-Key" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "JWT": [] + } + ] +} +``` + ## GET `/api/v1/release-gate-policies/{policy_id}` Get Policy Get a single release gate policy by ID. -Source: [backend/app/routers/release_gate_policies.py:275](../../../backend/app/routers/release_gate_policies.py#L275). +Source: [backend/app/routers/release_gate_policies.py:296](../../../backend/app/routers/release_gate_policies.py#L296). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`. @@ -632,7 +720,7 @@ Update Policy Update a draft policy (ADMIN only). Fails if already published. -Source: [backend/app/routers/release_gate_policies.py:360](../../../backend/app/routers/release_gate_policies.py#L360). +Source: [backend/app/routers/release_gate_policies.py:381](../../../backend/app/routers/release_gate_policies.py#L381). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -646,6 +734,7 @@ Direct handler error branches (dependency/service errors can add others): ```python HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Policy not found') +HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=DRAFT_DELETED_DETAIL) HTTPException(status_code=status.HTTP_409_CONFLICT, detail='Cannot edit a published policy. Create a new version instead.') ``` @@ -730,7 +819,7 @@ Deactivate Policy Deactivate a policy (falls back to system default or hardcoded). -Source: [backend/app/routers/release_gate_policies.py:475](../../../backend/app/routers/release_gate_policies.py#L475). +Source: [backend/app/routers/release_gate_policies.py:506](../../../backend/app/routers/release_gate_policies.py#L506). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -817,7 +906,7 @@ Publish Policy Publish a draft policy: deactivates any previous active policy for the same scope. -Source: [backend/app/routers/release_gate_policies.py:403](../../../backend/app/routers/release_gate_policies.py#L403). +Source: [backend/app/routers/release_gate_policies.py:429](../../../backend/app/routers/release_gate_policies.py#L429). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`. @@ -831,6 +920,7 @@ Direct handler error branches (dependency/service errors can add others): ```python HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Policy not found') +HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=DRAFT_DELETED_DETAIL) HTTPException(status_code=status.HTTP_409_CONFLICT, detail=ALREADY_PUBLISHED_DETAIL) HTTPException(status_code=status.HTTP_409_CONFLICT, detail=PUBLISH_RACE_DETAIL) ``` diff --git a/docs/reference/api/release-readiness.md b/docs/reference/api/release-readiness.md index 961c4794d..936e9f833 100644 --- a/docs/reference/api/release-readiness.md +++ b/docs/reference/api/release-readiness.md @@ -12,7 +12,7 @@ Retrieve the release readiness decision with full council context: dimension scores, linked cluster insights, baseline diff, open defects, and override audit trail. -Source: [backend/app/routers/release_readiness.py:46](../../../backend/app/routers/release_readiness.py#L46). +Source: [backend/app/routers/release_readiness.py:51](../../../backend/app/routers/release_readiness.py#L51). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_run_access.._check`. @@ -113,7 +113,7 @@ Override Release Decision Override the AI release decision (QA Lead only). Records the override in an immutable audit trail with before/after values. -Source: [backend/app/routers/release_readiness.py:105](../../../backend/app/routers/release_readiness.py#L105). +Source: [backend/app/routers/release_readiness.py:121](../../../backend/app/routers/release_readiness.py#L121). Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`, `require_run_access.._check`. diff --git a/docs/reference/openapi.json b/docs/reference/openapi.json index 7dd574828..65b560cdd 100644 --- a/docs/reference/openapi.json +++ b/docs/reference/openapi.json @@ -34593,6 +34593,23 @@ "ReleaseCouncilResponse": { "description": "Extended release decision with council context.", "properties": { + "analysis_changed_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Analysis Changed At" + }, + "analysis_changed_since": { + "default": false, + "title": "Analysis Changed Since", + "type": "boolean" + }, "band_downgrades": { "default": [], "items": { @@ -34601,6 +34618,11 @@ "title": "Band Downgrades", "type": "array" }, + "band_held_back": { + "default": false, + "title": "Band Held Back", + "type": "boolean" + }, "band_policy_id": { "anyOf": [ { @@ -34805,6 +34827,18 @@ ], "title": "Pass Rate" }, + "pass_rate_bands": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Pass Rate Bands" + }, "policy_id": { "anyOf": [ { @@ -43748,6 +43782,20 @@ ], "title": "Input Tokens" }, + "mode_distribution": { + "anyOf": [ + { + "additionalProperties": { + "type": "integer" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Mode Distribution" + }, "output_tokens": { "anyOf": [ { @@ -86899,6 +86947,62 @@ } }, "/api/v1/release-gate-policies/{policy_id}": { + "delete": { + "description": "Delete a draft that was never published (ADMIN only) (D-141).\n\nA version that was ever published stays: past verdicts and the version\nhistory name it, so it is deactivated instead (409). A draft a stored\nrelease decision points at is kept too (409). Records ``policy.updated``\nwith ``changed: draft deleted`` in the same transaction, the way\ndeactivate records its edit of the active flag.", + "operationId": "delete_policy_api_v1_release_gate_policies__policy_id__delete", + "parameters": [ + { + "in": "path", + "name": "policy_id", + "required": true, + "schema": { + "format": "uuid", + "title": "Policy Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-API-Key", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Api-Key" + } + } + ], + "responses": { + "204": { + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "security": [ + { + "JWT": [] + } + ], + "summary": "Delete Policy", + "tags": [ + "Release Gate Policies" + ] + }, "get": { "description": "Get a single release gate policy by ID.", "operationId": "get_policy_api_v1_release_gate_policies__policy_id__get", diff --git a/docs/reference/schemas.md b/docs/reference/schemas.md index 58c94dae5..94955b0a6 100644 --- a/docs/reference/schemas.md +++ b/docs/reference/schemas.md @@ -37146,6 +37146,23 @@ These are the full generated JSON Schema definitions, including required fields, { "description": "Extended release decision with council context.", "properties": { + "analysis_changed_at": { + "anyOf": [ + { + "format": "date-time", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Analysis Changed At" + }, + "analysis_changed_since": { + "default": false, + "title": "Analysis Changed Since", + "type": "boolean" + }, "band_downgrades": { "default": [], "items": { @@ -37154,6 +37171,11 @@ These are the full generated JSON Schema definitions, including required fields, "title": "Band Downgrades", "type": "array" }, + "band_held_back": { + "default": false, + "title": "Band Held Back", + "type": "boolean" + }, "band_policy_id": { "anyOf": [ { @@ -37358,6 +37380,18 @@ These are the full generated JSON Schema definitions, including required fields, ], "title": "Pass Rate" }, + "pass_rate_bands": { + "anyOf": [ + { + "additionalProperties": true, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Pass Rate Bands" + }, "policy_id": { "anyOf": [ { @@ -46996,6 +47030,20 @@ These are the full generated JSON Schema definitions, including required fields, ], "title": "Input Tokens" }, + "mode_distribution": { + "anyOf": [ + { + "additionalProperties": { + "type": "integer" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "title": "Mode Distribution" + }, "output_tokens": { "anyOf": [ { diff --git a/frontend/src/content/guide/releases.md b/frontend/src/content/guide/releases.md index 45e2854f8..498fbdf54 100644 --- a/frontend/src/content/guide/releases.md +++ b/frontend/src/content/guide/releases.md @@ -116,9 +116,9 @@ Two captions sum up the 12 weeks, each a count over its own denominator: **Ready A policy has **thresholds** (**GO Threshold**, **NO_GO Threshold**, **Pass Rate Minimum**, **Hard Floor Factor**), **pass-rate bands** (orange, yellow and green lower bounds), **rules** (**+ Add Rule** offers five: **Flaky Recurrence Limit**, **Open Defect Limit** and **Performance regression** take an action of **BLOCK**, **WARN** or **INFO**; **Dimension Ceiling** takes **BLOCK** or **WARN**; **Override Restrictions** has no action and sets whether a NO_GO may be overridden to GO and how long the override reason must be. **Performance regression** is off until you add it: it reads the run's slower tests and suites, and a run whose durations were not measured never trips it), and optional hard caps and weights. **Policy Simulator** shows what a policy would decide for a run before you publish it: pick the run from the searchable list of the policy's project's runs (the top-bar project's for the system default), or **Paste run ID**. -Policies are versioned: **New Policy** or editing creates a draft, **Save Draft** keeps it, and **Publish** makes it active and deactivates the previous version. Published versions are read-only, and past verdicts keep the policy version they were decided with. Creating, publishing and simulating policies needs an **administrator**; QA leads can read them. Writing good policies is covered in the operator guide in the repository (`user-guide/release-gates.md`). +Policies are versioned: **New Policy** or editing creates a draft, **Save Draft** keeps it, and **Publish** makes it active and deactivates the previous version. Published versions are read-only, and past verdicts keep the policy version they were decided with. The list shows active policies and drafts first; older versions sit under **Past versions**, and when nothing is active it says `No active policy: the built-in rule applies.` A draft that was never published can be removed with **Delete**, which asks in place; a version that was ever published, or that a verdict names, is kept (deactivate it instead). Creating, publishing, deleting drafts and simulating policies needs an **administrator**; QA leads can read them. Writing good policies is covered in the operator guide in the repository (`user-guide/release-gates.md`). -**Versions**, a closed section under a policy's header, lists every version of that policy's scope, newest first (`v4 · Active`, `v3 · Published`, `v5 · Draft`), with its name, who created it and when, and when it was activated. **Open** goes to a version; the one you are on reads **This version**. Tick **Compare** on two versions and **Compare v3 → v4** lists each setting that differs (`GO threshold 20 → 25`, `Pass-rate band yellow_min 95 → 97`, `Hard cap max_flaky_count 10 → 5`, `Rule "Block on P0" added`), or `No settings differ.` Versions and Compare are read-only, for everyone who can open the policy. On a published version an administrator also has **New version from this**: it creates a draft with the same scope, name, description and settings, as the next version number, and opens it, so a change starts from what is in force (`Draft v5 created from v4.`). +**Versions**, a closed section under a policy's header, lists every version of that policy's scope, newest first (`v4 · Active`, `v3 · Published`, `v5 · Draft`), with its name, who created it and when, and when it was activated. **Open** goes to a version; the one you are on reads **This version**. Tick **Compare** on two versions and **Compare v3 → v4** lists each setting that differs (`GO threshold 20 → 25`, `Pass-rate band yellow_min 95 → 97`, `Hard cap max_flaky_count 10 → 5`, `Rule "Block on P0" added`), or `No settings differ.` Versions and Compare are read-only, for everyone who can open the policy. On a published version an administrator also has **New version from this**: after **Create draft** in the question that appears, it creates a draft with the same scope, name, description and settings, as the next version number, and opens it, so a change starts from what is in force (`Draft v5 created from v4.`). ### Which line is the target diff --git a/frontend/src/hooks/useRuns.ts b/frontend/src/hooks/useRuns.ts index bb31923e8..fa623d555 100644 --- a/frontend/src/hooks/useRuns.ts +++ b/frontend/src/hooks/useRuns.ts @@ -197,7 +197,9 @@ export function useRunStepFlips(runId?: string) { * Deliberately NOT polled. A verdict is composed from a nightly score, a * nightly cluster and the run's own commit range — none of which move while * someone reads the page — so re-fetching would cost queries and change - * nothing. + * nothing. The one exception is a run whose pipeline is still writing + * categories: the Run page's Tests tab calls ``mutate`` when a test on screen + * gets a new category (D-72, ``RunTestsTab.tsx``). */ export function useRunAttribution(runId?: string) { return useSWR( diff --git a/frontend/src/pages/DeepInvestigationPage.test.tsx b/frontend/src/pages/DeepInvestigationPage.test.tsx index 672d0d687..5a5a8861e 100644 --- a/frontend/src/pages/DeepInvestigationPage.test.tsx +++ b/frontend/src/pages/DeepInvestigationPage.test.tsx @@ -449,6 +449,8 @@ describe('DeepInvestigationPage — only what it really does', () => { findings?: Record[] /** Extra fields on the focused run (run-1). */ focused?: Record + /** Fields that replace the decision trail's (D-156: its stages). */ + trail?: Record } = {}) { const { useFailureClusters, useDeepFindings, usePipelineStatus } = await import('@/hooks/useDeepInvestigation') const { useRuns, useRun } = await import('@/hooks/useRuns') @@ -488,7 +490,7 @@ describe('DeepInvestigationPage — only what it really does', () => { ((runId: string | null) => { data: Record }) | undefined const base = impl?.('run-1') ?? { data: {} } ;(useDecisionTrail as ReturnType).mockReturnValue({ - data: { ...base.data, completed_at: opts.trailCompletedAt ?? null }, + data: { ...base.data, completed_at: opts.trailCompletedAt ?? null, ...opts.trail }, isLoading: false, }) @@ -502,6 +504,54 @@ describe('DeepInvestigationPage — only what it really does', () => { return screen.findByRole('region', { name: 'Investigation verdict' }) } + // D-156: one model answer and three rules answers read "rules"; the stage now says "mixed" and the card + // prints the split in words. + it('D-156: Model routing prints a mixed stage\'s split, and one engine as before', async () => { + const stage = { + stage_name: 'root_cause_analysis', status: 'completed', started_at: null, completed_at: null, + duration_seconds: 4, fallback_used: true, fallback_reason: '3/4 tests fell back from requested engine', + route_rationale: null, error_category: null, skipped_reason: null, execution_path: null, + confidence_score: null, evidence_count: null, input_tokens: null, output_tokens: null, cost_usd: null, + decision_log: [], + } + await renderPage({ + trail: { + stages: [ + { ...stage, analysis_mode: 'mixed', mode_distribution: { rules: 3, llm: 1 } }, + { ...stage, stage_name: 'failure_clustering', fallback_used: false, analysis_mode: 'ml', mode_distribution: null }, + ], + }, + }) + const card = screen.getByRole('heading', { name: 'Model routing' }).closest('.card') + expect(within(card as HTMLElement).getByText('1 model · 3 rules')).toBeInTheDocument() + expect(within(card as HTMLElement).queryByText('mixed')).toBeNull() + expect(within(card as HTMLElement).getByText('ml')).toBeInTheDocument() + expect(within(card as HTMLElement).getByText('fallback')).toBeInTheDocument() + }) + + // Review F6: a QA lead's hint or a replayed human correction is not an engine. A rules-only stage with + // them still reads "rules"; a real model + rules split names the correction as "corrected". + it('D-156 F6: a hint or a correction never makes a stage mixed; a mixed split names it "corrected"', async () => { + const stage = { + status: 'completed', started_at: null, completed_at: null, duration_seconds: 4, fallback_used: false, + fallback_reason: null, route_rationale: null, error_category: null, skipped_reason: null, + execution_path: null, confidence_score: null, evidence_count: null, input_tokens: null, + output_tokens: null, cost_usd: null, decision_log: [], + } + await renderPage({ + trail: { + stages: [ + { ...stage, stage_name: 'root_cause_analysis', analysis_mode: 'rules', mode_distribution: { rules: 8, hint: 1, human_corrected: 1 } }, + { ...stage, stage_name: 'summary', analysis_mode: 'mixed', mode_distribution: { human_corrected: 1, rules: 2, llm: 1 } }, + ], + }, + }) + const card = screen.getByRole('heading', { name: 'Model routing' }).closest('.card') as HTMLElement + expect(within(card).getByText('rules')).toBeInTheDocument() + expect(within(card).queryByText(/hint/)).toBeNull() + expect(within(card).getByText('1 model · 2 rules · 1 corrected')).toBeInTheDocument() + }) + // W14 AGT-07: "Run on selection" is real now (the run configuration; the case below posts its failure ids). it('renders no stub control: History, Configure, Dry run, Open cluster, Swap, Decision trail', async () => { await renderPage() diff --git a/frontend/src/pages/DeepInvestigationPage.tsx b/frontend/src/pages/DeepInvestigationPage.tsx index f8e4c3eb5..68602b5a0 100644 --- a/frontend/src/pages/DeepInvestigationPage.tsx +++ b/frontend/src/pages/DeepInvestigationPage.tsx @@ -1284,6 +1284,29 @@ function EvidenceSourcesCard({ // execution_path per stage plus a fallback flag. No static model catalog // and no fabricated per-token rates: when the run has no trail yet, an // explanatory empty state renders instead. +/** + * D-156: the words for a stage's split, in the order it is printed. Only the first three are engines + * (the backend's `_ANSWERING_ENGINES`); a QA lead's hint, a human correction and an unrecorded engine are + * printed in the split but never make a stage mixed (review F6). + */ +const ENGINE_WORDS: Record = { + llm: 'model', ml: 'ML', rules: 'rules', hint: 'hint', human_corrected: 'corrected', unknown: 'unknown', +} +const ENGINE_ORDER = ['llm', 'ml', 'rules', 'hint', 'human_corrected', 'unknown'] +const ANSWERING_ENGINES = new Set(['llm', 'ml', 'rules']) + +/** + * D-156: "1 model · 3 rules" for a stage whose tests ran on more than one engine, else null (the stage + * prints its one engine as before). + */ +function engineSplit(dist: Record | null | undefined): string | null { + const entries = Object.entries(dist ?? {}).filter(([, n]) => n > 0) + if (entries.filter(([m]) => ANSWERING_ENGINES.has(m)).length < 2) return null + const rank = (m: string) => (ENGINE_ORDER.includes(m) ? ENGINE_ORDER.indexOf(m) : ENGINE_ORDER.length) + entries.sort(([a], [b]) => rank(a) - rank(b)) + return entries.map(([m, n]) => `${n} ${ENGINE_WORDS[m] ?? m.replace(/_/g, ' ')}`).join(' · ') +} + function ModelRoutingCard({ trail, isLoading, }: { trail: DecisionTrailResponse | undefined; isLoading: boolean }) { @@ -1299,7 +1322,9 @@ function ModelRoutingCard({ ) : (
- {stages.map((s, i) => ( + {stages.map((s, i) => { + const split = engineSplit(s.mode_distribution) + return (
{s.stage_name.replace(/_/g, ' ')} @@ -1315,14 +1340,15 @@ function ModelRoutingCard({ )} - {s.analysis_mode ?? s.execution_path} + {split ?? s.analysis_mode ?? s.execution_path} {s.analysis_mode && s.execution_path && s.execution_path !== s.analysis_mode && ( {s.execution_path} )}
- ))} + ) + })}
)} diff --git a/frontend/src/pages/PolicyEditorPage.test.tsx b/frontend/src/pages/PolicyEditorPage.test.tsx index 622327372..4a20db652 100644 --- a/frontend/src/pages/PolicyEditorPage.test.tsx +++ b/frontend/src/pages/PolicyEditorPage.test.tsx @@ -59,9 +59,10 @@ const mockToastSuccess = vi.fn() const mockAppMutate = vi.fn() const mockDeactivatePolicy = vi.fn() const mockRefreshPolicies = vi.fn() +const mockDeletePolicy = vi.fn() /** Every `usePolicies(enabled)` call, so a test can see the list asked for after a refused publish; * `policies` is what the list shows (empty unless a test lists some). */ -const listHook = vi.hoisted(() => ({ enabledCalls: [] as boolean[], policies: [] as unknown[] })) +const listHook = vi.hoisted(() => ({ enabledCalls: [] as boolean[], policies: [] as unknown[], isError: false })) vi.mock('react-hot-toast', () => ({ default: { error: (m: string) => mockToastError(m), success: (m: string) => mockToastSuccess(m) }, @@ -73,7 +74,7 @@ const policyHook = vi.hoisted(() => ({ policy: null as unknown })) vi.mock('@/hooks/usePolicyEditor', () => ({ usePolicies: (enabled: boolean) => { listHook.enabledCalls.push(enabled) - return { policies: listHook.policies, isLoading: false, isError: false, mutate: mockRefreshPolicies } + return { policies: listHook.policies, isLoading: false, isError: listHook.isError, mutate: mockRefreshPolicies } }, usePolicy: () => ({ policy: policyHook.policy, isLoading: false, isError: false }), })) @@ -110,6 +111,7 @@ vi.mock('../services/policyService', async () => { updatePolicy: vi.fn(), publishPolicy: (...a: unknown[]) => mockPublishPolicy(...a), deactivatePolicy: (...a: unknown[]) => mockDeactivatePolicy(...a), + deletePolicy: (...a: unknown[]) => mockDeletePolicy(...a), simulatePolicy: vi.fn(), } }) @@ -168,6 +170,7 @@ beforeEach(() => { vi.clearAllMocks() listHook.enabledCalls.length = 0 listHook.policies = [] + listHook.isError = false // Every write on this page is ADMIN on the API; these tests author policies. // What a QA lead sees is PolicyEditorPage.roles.test.tsx. useAuthStore.setState({ user: { id: 'admin', role: 'ADMIN' } as never }) @@ -698,6 +701,8 @@ describe('a published policy: its versions, a new version from it, the simulator renderPolicy() expect(screen.getByRole('heading', { name: 'View: Payments gate' })).toBeInTheDocument() fireEvent.click(screen.getByRole('button', { name: 'New version from this' })) + // D-140: the header button only asks; the strip's Create draft sends. + fireEvent.click(within(strip() as HTMLElement).getByRole('button', { name: 'Create draft' })) await waitFor(() => expect(mockCreatePolicy).toHaveBeenCalledTimes(1)) expect(mockCreatePolicy).toHaveBeenCalledWith({ project_id: 'proj-pay', name: 'Payments gate', description: 'Nightly gate', rules: DOC_V4, @@ -706,6 +711,24 @@ describe('a published policy: its versions, a new version from it, the simulator expect(mockToastSuccess).toHaveBeenCalledWith('Draft v5 created from v4.') }) + it('D-140: New version from this asks under the header first; Cancel and Escape create nothing', () => { + const { container } = renderPolicy() + fireEvent.click(screen.getByRole('button', { name: 'New version from this' })) + expect(mockCreatePolicy).not.toHaveBeenCalled() + const asked = strip() as HTMLElement + expect(asked.querySelector('p')?.textContent).toBe( + 'Create a draft copy of v4? It opens in the editor and changes nothing until you publish it.', + ) + expect(container.querySelector('[data-page-header]')?.nextElementSibling).toBe(asked) + + fireEvent.click(within(asked).getByRole('button', { name: 'Cancel' })) + expect(strip()).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'New version from this' })) + fireEvent.keyDown(within(strip() as HTMLElement).getByRole('button', { name: 'Cancel' }), { key: 'Escape' }) + expect(strip()).toBeNull() + expect(mockCreatePolicy).not.toHaveBeenCalled() + }) + it('as a QA lead: no New version from this, but Versions and Compare read', () => { useAuthStore.setState({ user: { id: 'lead', role: 'QA_LEAD' } as never }) renderPolicy() @@ -735,3 +758,105 @@ describe('a published policy: its versions, a new version from it, the simulator expect(runPicker.props[runPicker.props.length - 1].projectId).toBeNull() }) }) + +// ── D-141: the list puts the active policy and the drafts first; a draft can be deleted ── +describe('D-141: active and drafts first, past versions closed, a draft can be deleted', () => { + const listRow = (id: string, name: string, over: Record) => ({ + id, name, version: 1, project_id: null, created_at: '2026-10-01T00:00:00Z', description: '', rules: {}, + is_active: false, is_draft: false, ...over, + }) + const ACTIVE = listRow('p-on', 'Live gate', { version: 4, is_active: true }) + const DRAFT = listRow('p-draft', 'Next gate', { version: 5, is_draft: true }) + const PAST = listRow('p-old', 'Old gate', { version: 3 }) + const NO_ACTIVE = 'No active policy: the built-in rule applies.' + const past = () => document.querySelector('[data-policy-past-versions]') as HTMLElement | null + const primary = () => document.querySelector('[data-primary]') as HTMLElement | null + + it('with only a past version: says the built-in rule applies, and the version is under a closed Past versions', () => { + listHook.policies = [PAST] + renderAt('/policies') + expect(screen.getByText(NO_ACTIVE)).toBeInTheDocument() + expect(primary()).toBeNull() + const toggle = within(past() as HTMLElement).getByRole('button', { name: /^Past versions/ }) + expect(toggle).toHaveAttribute('aria-expanded', 'false') + expect(toggle).toHaveTextContent('1 version') + expect(screen.queryByText('Old gate')).toBeNull() + fireEvent.click(toggle) + expect(within(past() as HTMLElement).getByText('Old gate')).toBeInTheDocument() + expect(within(past() as HTMLElement).getByText('Inactive')).toBeInTheDocument() + // Kept: a past version offers View, not Delete or Deactivate. + expect(within(past() as HTMLElement).getByRole('button', { name: 'View' })).toBeInTheDocument() + expect(within(past() as HTMLElement).queryByRole('button', { name: /Delete|Deactivate/ })).toBeNull() + }) + + it('with an active policy: active first, then the draft; the past version waits behind the section; no built-in sentence', () => { + listHook.policies = [DRAFT, PAST, ACTIVE] + renderAt('/policies') + expect(screen.queryByText(NO_ACTIVE)).toBeNull() + const names = Array.from((primary() as HTMLElement).querySelectorAll('.card .font-medium')).map(n => n.textContent) + expect(names).toEqual(['Live gate', 'Next gate']) + expect(within(past() as HTMLElement).getByRole('button', { name: /^Past versions/ })).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByText('Old gate')).toBeNull() + }) + + it('a failed list read does not claim that nothing is active', () => { + listHook.isError = true + renderAt('/policies') + expect(screen.getByText('Could not load policies')).toBeInTheDocument() + expect(screen.queryByText(NO_ACTIVE)).toBeNull() + }) + + it('a draft\'s Delete asks under its card; the strip deletes once, toasts, re-reads the list', async () => { + listHook.policies = [ACTIVE, DRAFT] + mockDeletePolicy.mockResolvedValue(undefined) + renderAt('/policies') + // Only the draft offers Delete; only the active policy offers Deactivate. + expect(screen.getAllByRole('button', { name: 'Delete' })).toHaveLength(1) + expect(screen.getAllByRole('button', { name: 'Deactivate' })).toHaveLength(1) + + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + expect(mockDeletePolicy).not.toHaveBeenCalled() + const asked = strip() as HTMLElement + expect(asked.querySelector('p')?.textContent).toBe( + 'Delete this draft? It was never published, so no verdict used it. This cannot be undone.', + ) + const card = screen.getByText('Next gate').closest('.card') as HTMLElement + expect(card.nextElementSibling).toBe(asked.closest('[data-in-page-row]')) + + fireEvent.click(within(asked).getByRole('button', { name: 'Delete' })) + expect(strip()).toBeNull() + await waitFor(() => expect(mockToastSuccess).toHaveBeenCalledWith('Draft deleted')) + expect(mockDeletePolicy).toHaveBeenCalledTimes(1) + expect(mockDeletePolicy).toHaveBeenCalledWith('p-draft') + expect(mockRefreshPolicies).toHaveBeenCalledTimes(1) + }) + + it('a refused delete toasts the server sentence and re-reads the list', async () => { + listHook.policies = [DRAFT] + mockDeletePolicy.mockRejectedValue({ + response: { status: 409, data: { detail: 'This draft is named by a stored release decision, so it is kept.' } }, + }) + renderAt('/policies') + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + fireEvent.click(within(strip() as HTMLElement).getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('This draft is named by a stored release decision, so it is kept.')) + expect(mockRefreshPolicies).toHaveBeenCalledTimes(1) + }) + + it('Cancel on the Delete question deletes nothing', () => { + listHook.policies = [DRAFT] + renderAt('/policies') + fireEvent.click(screen.getByRole('button', { name: 'Delete' })) + fireEvent.click(within(strip() as HTMLElement).getByRole('button', { name: 'Cancel' })) + expect(strip()).toBeNull() + expect(mockDeletePolicy).not.toHaveBeenCalled() + }) + + it('a QA lead sees the draft with no Delete', () => { + useAuthStore.setState({ user: { id: 'lead', role: 'QA_LEAD' } as never }) + listHook.policies = [DRAFT] + renderAt('/policies') + expect(screen.getByText('Next gate')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Delete' })).toBeNull() + }) +}) diff --git a/frontend/src/pages/PolicyEditorPage.tsx b/frontend/src/pages/PolicyEditorPage.tsx index d8e74b9e1..79d7f3393 100644 --- a/frontend/src/pages/PolicyEditorPage.tsx +++ b/frontend/src/pages/PolicyEditorPage.tsx @@ -14,6 +14,13 @@ * W27b PAN-05: Publish and Deactivate ask in the page (`InlineConfirm`), not * with the browser's prompt: Publish right under the page header, Deactivate * right under its policy card. The strip's own button is the only sender. + * D-140: "New version from this" asks the same way (it creates a draft), and + * D-141: a never-published draft's Delete asks under its card. + * + * D-141: the list shows the active policies and the drafts first; versions + * that were published and later replaced or deactivated sit under a closed + * "Past versions" section (they are kept: past verdicts name them). With no + * active policy the list says the built-in rule applies. */ import { Fragment, useState } from 'react'; import { useProjectStore } from '@/store/projectStore'; @@ -37,8 +44,10 @@ import { DEFAULT_PASS_RATE_BANDS, DEFAULT_HARD_CAPS, DEFAULT_KIND_RULES, + type PolicySummary, createPolicy, deactivatePolicy, + deletePolicy, publishPolicy, simulatePolicy, updatePolicy, @@ -259,6 +268,11 @@ export default function PolicyEditorPage() { // (one policy card of the list at a time). const [confirmingPublish, setConfirmingPublish] = useState(false); const [confirmingDeactivate, setConfirmingDeactivate] = useState(null); + // D-141: the draft whose Delete is being asked about (one card at a time, + // shared with Deactivate's question so only one strip is open). + const [confirmingDelete, setConfirmingDelete] = useState(null); + // D-140: "New version from this" creates a draft, so it asks first. + const [confirmingBranch, setConfirmingBranch] = useState(false); // Tracks which policy id the editable form fields below were seeded from, so // the "adjust state during render" seeding (below) runs once per loaded // policy instead of from a set-state-in-effect. @@ -391,6 +405,21 @@ export default function PolicyEditorPage() { } }; + /** + * D-141: delete a never-published draft. A refusal (it was published in the + * meantime, or a stored decision names it) toasts the server's sentence and + * re-reads the list, so the reader sees the row's real state. + */ + const handleDelete = async (id: string) => { + try { + await deletePolicy(id); + toast.success('Draft deleted'); + } catch (err) { + toast.error(serverError(err, 'Could not delete the draft')); + } + refreshPolicies(); + }; + const addRule = (type: string) => { const tmpl = RULE_TYPES.find(r => r.type === type); if (!tmpl) return; @@ -425,6 +454,77 @@ export default function PolicyEditorPage() { // ── List mode ───────────────────────────────────────────────────────────── if (isNew && !policyId) { + // D-141: active policies and drafts first; a version that was published + // and is no longer active is a past version (kept, under a closed section). + const currentPolicies = [ + ...policies.filter(p => p.is_active), + ...policies.filter(p => !p.is_active && p.is_draft), + ]; + const pastPolicies = policies.filter(p => !p.is_active && !p.is_draft); + // Only on a list that loaded: a failed read is not "nothing is active". + const noneActive = !loading && !policiesError && !policies.some(p => p.is_active); + + const renderRow = (p: PolicySummary) => ( + +
+
+
+ {p.name} + v{p.version} + + {p.is_active ? 'Active' : p.is_draft ? 'Draft' : 'Inactive'} + +
+

+ {p.project_id ? `Project: ${projectLabel(p.project_id)}` : 'System Default'} + {' · '}Created: {formatDay(p.created_at)} +

+
+
+ + {p.is_active && isAdmin && ( + + )} + {p.is_draft && !p.is_active && isAdmin && ( + + )} +
+
+ {confirmingDeactivate === p.id && p.is_active && isAdmin && ( +
+ { setConfirmingDeactivate(null); void handleDeactivate(p.id); }} + onCancel={() => setConfirmingDeactivate(null)} + /> +
+ )} + {confirmingDelete === p.id && p.is_draft && !p.is_active && isAdmin && ( +
+ { setConfirmingDelete(null); void handleDelete(p.id); }} + onCancel={() => setConfirmingDelete(null)} + /> +
+ )} +
+ ); + return (
{displayError}
} + {noneActive && ( +

+ No active policy: the built-in rule applies. +

+ )} + {loading ? (
Loading…
) : policies.length === 0 ? ( @@ -453,52 +559,28 @@ export default function PolicyEditorPage() { No policies configured. Create one to customize release gate thresholds per project. ) : ( -
- {policies.map(p => ( - -
-
-
- {p.name} - v{p.version} - - {p.is_active ? 'Active' : p.is_draft ? 'Draft' : 'Inactive'} - -
-

- {p.project_id ? `Project: ${projectLabel(p.project_id)}` : 'System Default'} - {' · '}Created: {formatDay(p.created_at)} -

-
-
- - {p.is_active && isAdmin && ( - - )} -
-
- {confirmingDeactivate === p.id && p.is_active && isAdmin && ( -
- { setConfirmingDeactivate(null); void handleDeactivate(p.id); }} - onCancel={() => setConfirmingDeactivate(null)} - /> + <> + {currentPolicies.length > 0 && ( +
+ {currentPolicies.map(renderRow)} +
+ )} + {/* Kept, not deletable: past verdicts name these versions. Closed + on load; the active policy and the drafts are what a reader + comes here for. */} + {pastPolicies.length > 0 && ( +
+ +
+ {pastPolicies.map(renderRow)}
- )} - - ))} -
+ +
+ )} + )}
); @@ -539,7 +621,7 @@ export default function PolicyEditorPage() { )} ) : canBranch ? ( - ) : undefined} @@ -554,6 +636,15 @@ export default function PolicyEditorPage() { /> )} + {confirmingBranch && canBranch && loadedPolicy && ( + { setConfirmingBranch(false); void handleNewVersion(); }} + onCancel={() => setConfirmingBranch(false)} + /> + )} + {displayError &&
{displayError}
} {!isAdmin && ( diff --git a/frontend/src/pages/ReleaseGatePage.test.tsx b/frontend/src/pages/ReleaseGatePage.test.tsx index 38e855baf..9801219f2 100644 --- a/frontend/src/pages/ReleaseGatePage.test.tsx +++ b/frontend/src/pages/ReleaseGatePage.test.tsx @@ -495,7 +495,8 @@ describe('ReleaseGatePage — the risk score explains itself', () => { it('states the floor percentage it actually applied', async () => { await renderGate(flooredDecision()) - expect(await screen.findByText(/63%/)).toBeInTheDocument() + // The thresholds line (D-104) says "under 63%" too: this pins the floor note's own sentence. + expect(await screen.findByText(/below 63%/)).toBeInTheDocument() }) it('stays silent when the score really is the dimension total', async () => { @@ -1319,3 +1320,145 @@ describe('ReleaseGatePage — the band policy and the top-bar release (W11)', () await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent('/release-gate/run-of-2026-10')) }) }) + +// Batch 8: D-104 (the thresholds the verdict used), D-142 (one policy named once, the rules a quick look could +// not check) and D-97 (a correction saved after the stored decision). +describe('ReleaseGatePage — batch 8: the card says what it was decided with', () => { + const STORED_SNAPSHOT = { + assembled_at: '2026-11-20T09:00:00+00:00', + policy_snapshot: { + policy_level: 'project', + document: { + thresholds: { go_threshold: 20, no_go_threshold: 55, pass_rate_minimum: 90, pass_rate_hard_floor_factor: 0.7 }, + }, + }, + } + + async function marked(selector: string): Promise { + return waitFor(() => { + const found = document.querySelector(selector) as HTMLElement | null + if (!found) throw new Error(`no ${selector}`) + return found + }) + } + + it('D-104: a stored decision states its four thresholds from the frozen policy', async () => { + await renderGate(flooredDecision({ + recommendation: 'GO', risk_score: 12, composite_risk: 12, pass_rate: 96, + input_snapshot: STORED_SNAPSHOT, + })) + expect(await marked('[data-verdict-thresholds]')).toHaveTextContent( + 'Go under risk 20 and at 90% or more · No-Go at risk 55 or under 63%', + ) + }) + + it('D-104: a quick look states its own numbers, and a missing one is left out', async () => { + await renderGate(flooredDecision({ + synthesized: true, + input_snapshot: { verdict_driver: 'pass_rate_floor', threshold: 95, no_go_floor_pct: 66.5, go_threshold: 20 }, + })) + const line = await marked('[data-verdict-thresholds]') + // No `no_go_threshold` in the snapshot: no invented "risk 55". + expect(line).toHaveTextContent('Go under risk 20 and at 95% or more · No-Go under 66.5%') + expect(line).not.toHaveTextContent('risk 55') + }) + + it('D-104: a snapshot without thresholds shows no line', async () => { + await renderGate(flooredDecision({ input_snapshot: { verdict_driver: 'composite_risk' } })) + await screen.findByText(/Evaluated with/) + expect(document.querySelector('[data-verdict-thresholds]')).toBeNull() + }) + + it('D-142: a quick look evaluated with the policy whose bands it applied names that policy once, bands included', async () => { + await renderGate(flooredDecision({ + synthesized: true, + policy_id: 'pol-1', policy_level: 'project', policy_version: 2, + ...({ band_policy_id: 'pol-1', band_policy_level: 'project', band_policy_version: 2 } as object), + })) + const footer = (await screen.findByText(/Evaluated with/)).parentElement ?? document.body + // The pieces sit in an inline-flex row (its gap spaces them), as the band label always did. + expect(footer).toHaveTextContent('Evaluated with project policy v2') + expect(document.querySelector('[data-band-policy]')).toHaveTextContent('· including its pass-rate bands') + expect(footer).not.toHaveTextContent('pass-rate bands: project policy') + expect(screen.queryByText(/system defaults/)).toBeNull() + }) + + // Review F1: every policy saved from the editor carries bands (red under 90, orange 90-95). The card must not + // state thresholds the band contradicts, and must say when the band set the verdict. + const EDITOR_BANDS = { orange_min: 90, yellow_min: 95, green_min: 99 } + const banded = (overrides: Partial & Record) => flooredDecision({ + risk_score: 10, composite_risk: 10, input_snapshot: STORED_SNAPSHOT, + policy_id: 'pol-1', policy_level: 'project', policy_version: 1, + ...({ band_policy_id: 'pol-1', band_policy_level: 'project', band_policy_version: 1, pass_rate_bands: EDITOR_BANDS } as object), + ...overrides, + } as Partial) + + it('F1: a 92% run at risk 10 reads Conditional, and the card names the band that made it so', async () => { + await renderGate(banded({ + recommendation: 'CONDITIONAL_GO', pass_rate: 92, + release_readiness_band: 'orange', band_held_back: true, original_recommendation: 'GO', + })) + expect(await marked('[data-verdict-thresholds]')).toHaveTextContent( + 'Go under risk 20 and at 90% or more · No-Go at risk 55 or under 63% · Pass-rate bands: No-Go under 90%, Conditional under 95%', + ) + expect(await marked('[data-band-hold]')).toHaveTextContent('Held back by the pass-rate band: 92.0% is under 95% (Conditional).') + expect(document.querySelector('[data-band-policy]')).toHaveTextContent('including its pass-rate bands') + }) + + it('F1: an 85% run reads No-Go from the red band, and says so', async () => { + await renderGate(banded({ + recommendation: 'NO_GO', pass_rate: 85, + release_readiness_band: 'red', band_held_back: true, original_recommendation: 'CONDITIONAL_GO', + })) + expect(await marked('[data-verdict-thresholds]')).toHaveTextContent('Pass-rate bands: No-Go under 90%, Conditional under 95%') + expect(await marked('[data-band-hold]')).toHaveTextContent('Held back by the pass-rate band: 85.0% is under 90% (No-Go).') + }) + + it('F1: no hold line when the band did not move the verdict', async () => { + await renderGate(banded({ recommendation: 'GO', pass_rate: 99.5, release_readiness_band: 'green', band_held_back: false })) + expect(await marked('[data-verdict-thresholds]')).toHaveTextContent('Pass-rate bands:') + expect(document.querySelector('[data-band-hold]')).toBeNull() + }) + + it('D-142: a quick look names the policy rules it could not check', async () => { + await renderGate(flooredDecision({ + synthesized: true, policy_level: 'project', policy_version: 2, + input_snapshot: { + verdict_driver: 'composite_risk', + rules_not_checked: [ + { id: 'r1', name: 'Flaky test limit', type: 'flaky_recurrence' }, + { id: 'r2', name: 'Slower tests', type: 'perf_regression' }, + ], + }, + })) + expect(await marked('[data-rules-not-checked]')).toHaveTextContent( + 'Not checked until deep investigation runs: Flaky test limit, Slower tests', + ) + }) + + it('D-97: a correction saved after the stored decision is said, with Re-evaluate', async () => { + await renderGate(flooredDecision({ + input_snapshot: STORED_SNAPSHOT, + ...({ analysis_changed_since: true, analysis_changed_at: '2026-11-20T12:30:00Z' } as object), + })) + const note = await marked('[data-analysis-changed]') + expect(note).toHaveTextContent(/^A test's category was corrected after this decision \(.+\)\. Re-evaluate to include it\.$/) + expect(within(note).getByRole('link', { name: 'Re-evaluate' })).toHaveAttribute('href', '/runs/run-1?tab=analysis') + // The stored verdict is shown as it is. + expect(screen.getByText('No-Go')).toBeInTheDocument() + }) + + it('D-97: no note without the flag, and never on a quick look', async () => { + await renderGate(flooredDecision({ input_snapshot: STORED_SNAPSHOT })) + await screen.findByText(/Evaluated with/) + expect(document.querySelector('[data-analysis-changed]')).toBeNull() + cleanup() + + await renderGate(flooredDecision({ + synthesized: true, + ...({ analysis_changed_since: true, analysis_changed_at: '2026-11-20T12:30:00Z' } as object), + })) + await screen.findByText(/Evaluated with/) + expect(document.querySelector('[data-analysis-changed]')).toBeNull() + }) +}) diff --git a/frontend/src/pages/ReleaseGatePage.tsx b/frontend/src/pages/ReleaseGatePage.tsx index 3e56732f1..e807b8dd8 100644 --- a/frontend/src/pages/ReleaseGatePage.tsx +++ b/frontend/src/pages/ReleaseGatePage.tsx @@ -41,6 +41,13 @@ import { lazyWithRetry } from '@/utils/lazyWithRetry' import { formatCompactDateTime, formatDay } from '@/utils/formatters' import { runName, runSeqLabel } from '@/utils/formatters' import { DECISION_LABEL } from '@/components/ui/statusVocabulary' +import { + describeBandHold, + describeVerdictThresholds, + rulesNotChecked, + type AnalysisChanged, + type BandFloor, +} from './releaseGateModel' /** * The catalogue's "Context" group (VIZ-408), in its own chunk: it arrives @@ -155,11 +162,23 @@ function policyLabel(decision: ReleaseCouncilDecision): string { * carried both; the page names the band policy beside the stored one. */ type BandProvenance = { + band_policy_id?: string | null band_policy_level?: string | null band_policy_version?: number | null band_downgrades?: string[] | null } +/** + * D-142: the quick look now evaluates with the same policy whose bands it applies. The footer still says the + * bands applied (review F1: they can decide the verdict), as "including its pass-rate bands" when they came + * from the policy the verdict was evaluated with, and by name when they came from another one. + */ +function bandsFromEvaluatedPolicy(decision: ReleaseCouncilDecision & BandProvenance): boolean { + if (!decision.band_policy_level || decision.band_policy_level !== decision.policy_level) return false + if ((decision.band_policy_version ?? null) !== (decision.policy_version ?? null)) return false + return !decision.policy_id || !decision.band_policy_id || decision.policy_id === decision.band_policy_id +} + function bandPolicyLabel(decision: BandProvenance): string | null { if (!decision.band_policy_level) return null const level = decision.band_policy_level === 'system' ? 'system policy' : 'project policy' @@ -365,7 +384,22 @@ export default function ReleaseGatePage() { // response has carried these fields since TL-2026-09-19-01-008). const bandProvenance = decision as ReleaseCouncilDecision & BandProvenance const bandLabel = bandPolicyLabel(bandProvenance) + const bandsSamePolicy = bandsFromEvaluatedPolicy(bandProvenance) const bandDowngrades = Array.isArray(bandProvenance.band_downgrades) ? bandProvenance.band_downgrades : [] + // D-104: the numbers the verdict used, from the decision's own snapshot (a missing one is left out), plus + // the pass-rate bands the gate applied at read time (review F1: they can floor the verdict). + const bandFloor = decision as ReleaseCouncilDecision & BandFloor + const appliedBands = bandFloor.pass_rate_bands ?? null + const thresholdsLine = describeVerdictThresholds(decision.input_snapshot, appliedBands) + const bandHold = bandFloor.band_held_back + ? describeBandHold(decision.pass_rate, bandFloor.release_readiness_band, appliedBands) + : null + // D-142: the policy rules a quick look had no input for. + const uncheckedRules = decision.synthesized ? rulesNotChecked(decision.input_snapshot) : [] + // D-97: a category was corrected in this run after the stored decision read it (read-time; never on a + // quick look, which is computed from today's categories). + const changed = decision as ReleaseCouncilDecision & AnalysisChanged + const analysisChanged = !decision.synthesized && changed.analysis_changed_since === true // Linked cluster insights, placed under the Context group whose share chart // summarises them. @@ -484,6 +518,19 @@ export default function ReleaseGatePage() { {hasEvidence && decision.pass_rate != null && (

Pass rate: {decision.pass_rate.toFixed(1)}%

)} + {hasEvidence && thresholdsLine && ( +

{thresholdsLine}

+ )} + {hasEvidence && bandHold && ( +

{bandHold}

+ )} + {analysisChanged && ( +

+ A test's category was corrected after this decision + {changed.analysis_changed_at ? ` (${formatCompactDateTime(changed.analysis_changed_at)})` : ''}.{' '} + Re-evaluate to include it. +

+ )} {hasEvidence && decision.original_recommendation && decision.original_recommendation !== decision.recommendation && (

Original recommendation: {decision.original_recommendation} @@ -553,7 +600,10 @@ export default function ReleaseGatePage() { Evaluated with{' '} {policyLabel(decision)} - {bandLabel && ( + {bandLabel && bandsSamePolicy && ( + · including its pass-rate bands + )} + {bandLabel && !bandsSamePolicy && ( · pass-rate bands:{' '} {bandLabel} @@ -568,6 +618,11 @@ export default function ReleaseGatePage() { {bandLabel} )} + {uncheckedRules.length > 0 && ( + + Not checked until deep investigation runs: {uncheckedRules.join(', ')} + + )} {!overrideMode && (