diff --git a/docs/architecture.md b/docs/architecture.md index 8348510..074dd85 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -500,6 +500,28 @@ output/ ## Design Intent +The 2026-07-10 elegance review ratified four design rules for all future work. They exist to +stop the three debts that phase-by-phase growth created: callable-threaded extractions, +template-stamped control modules, and lazy-import cycles. + +1. **No new callable-threaded extractions.** When logic is extracted from a large module, + the shared primitives it needs move to a leaf support module (for the operator layer, + `src/operator_trend_support.py`) and are imported by the extracted module. Threading the + parent's helpers back in as `Callable` parameters is no longer an accepted way to avoid a + circular import — fix the dependency direction instead. +2. **No new stamped control modules.** A new closure-forecast or trend control may not be + added by copying the seven-function template (`*_side_from_status` / `*_path_label` / + `*_recovery_for_target` / `apply_*_control` / `*_hotspots` / `*_summary` / `*_reason`) + into a new module. New controls wait for (or drive) the parametrized control core; until + that core exists, adding one requires an explicit maintainer decision recorded here. +3. **No new function-level internal imports outside the CLI dispatch layer.** `src/cli.py` + may defer imports for startup latency. Everywhere else, a deferred `from src...` import + inside a function body marks a layering bug; fix the direction rather than hiding the + import. +4. **Overlays merge or die.** An advisory overlay that survives two further phases is either + merged into the core it overlays or deleted. Overlay status is a transition state, not a + destination — this keeps "bounded overlay" from being a one-way ratchet on module count. + ## Automation Guidance Phase 92 adds one bounded execution-guidance layer on top of the existing Action Sync and historical stack: `Automation Guidance`. diff --git a/src/app/__init__.py b/src/app/__init__.py new file mode 100644 index 0000000..282ec44 --- /dev/null +++ b/src/app/__init__.py @@ -0,0 +1 @@ +"""Application-layer mode handlers dispatched by :mod:`src.cli`.""" diff --git a/src/app/acknowledgments.py b/src/app/acknowledgments.py new file mode 100644 index 0000000..bf8fc75 --- /dev/null +++ b/src/app/acknowledgments.py @@ -0,0 +1,59 @@ +"""Acknowledgment-capture application flow.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.cli_output import print_info +from src.diff import diff_reports +from src.history import find_previous +from src.operator_acknowledgments import ( + build_acknowledgment_record, + find_matching_change, + find_sibling_changes, + load_acknowledgments, + save_acknowledgment, +) +from src.recurring_review import MATERIALITY_THRESHOLDS, evaluate_material_changes +from src.report_state import load_latest_report + + +def run_acknowledgment_capture_mode(args: Any, parser: Any) -> None: + if not args.acknowledge_target: + parser.error("--acknowledge-target is required for acknowledgment capture") + if not args.acknowledge_kind: + parser.error("--acknowledge-kind is required for acknowledgment capture") + if not (args.acknowledge_note or "").strip(): + parser.error("--acknowledge-note is required and must explain the acknowledgment") + output_dir = Path(args.output_dir) + report_path, report_data = load_latest_report(output_dir) + if not report_path or not report_data: + parser.error("No existing audit report found in output directory") + diff_dict = None + previous_path = find_previous(report_path.name) + if previous_path: + diff_dict = diff_reports( + previous_path, report_path, portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ).to_dict() + material_changes = evaluate_material_changes( + report_data, diff_data=diff_dict, thresholds=MATERIALITY_THRESHOLDS["standard"] + ) + acknowledgments = load_acknowledgments(output_dir, args.username) + matched = find_matching_change( + repo_name=args.acknowledge_target, change_kind=args.acknowledge_kind, + material_changes=material_changes, acknowledgments=acknowledgments, + ) + if not matched: + parser.error(f"No open '{args.acknowledge_kind}' change found for '{args.acknowledge_target}' in the latest report") + reviewer = args.acknowledge_reviewer or args.approval_reviewer + record = build_acknowledgment_record(matched, reviewer=reviewer, note=args.acknowledge_note) + saved_path = save_acknowledgment(output_dir, args.username, record) + print_info(f"Acknowledged {args.acknowledge_kind} for {args.acknowledge_target} (change_key={record['change_key'][:12]}…, reviewer={reviewer})") + for sibling in find_sibling_changes(matched, material_changes): + sibling_record = build_acknowledgment_record(sibling, reviewer=reviewer, note=args.acknowledge_note) + save_acknowledgment(output_dir, args.username, sibling_record) + print_info(f"Acknowledged sibling {sibling.get('change_type')} for {sibling.get('repo_name')} (change_key={sibling_record['change_key'][:12]}…)") + print_info(f"Acknowledgment store: {saved_path}") + print_info("Run --control-center to confirm the item is filtered from the queue.") diff --git a/src/app/approval_center.py b/src/app/approval_center.py new file mode 100644 index 0000000..f3d805f --- /dev/null +++ b/src/app/approval_center.py @@ -0,0 +1,102 @@ +"""Approval-center application flow.""" + +from __future__ import annotations + +import logging +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from src.cli_output import print_info +from src.control_center_report_state import refresh_latest_report_state +from src.operator_approval_artifacts import write_approval_center_artifacts +from src.operator_approval_artifacts import ( + write_approval_receipt, + write_followup_review_receipt, +) +from src.operator_prefs import load_rejection_events, post_process_approval_session +from src.approval_ledger import ( + build_approval_followup_record, + build_approval_record, + load_approval_ledger_bundle, +) +from src.report_shared_artifacts import refresh_shared_artifacts_from_report +from src.warehouse import save_approval_followup_event, save_approval_record + + +def _utcnow() -> datetime: + return datetime.now(timezone.utc) + + +def _post_process_approval_center_prefs(payload: dict, output_dir: Path) -> None: + try: + rejection_records = load_rejection_events(output_dir) + total, newly_added = post_process_approval_session(rejection_records, output_dir) + print_info(f"Suppressions: {total} action type(s) suppressed ({newly_added} newly added).") + except Exception as exc: # noqa: BLE001 + logging.getLogger(__name__).warning( + "operator_prefs post-process failed (non-fatal): %s", exc + ) + + +def run_approval_center_mode(args: Any, parser: Any) -> None: + report_output_dir = Path(args.output_dir) + try: + _report_path, _diff_dict, report = refresh_latest_report_state(report_output_dir, args) + except FileNotFoundError: + parser.error("No existing audit report found in output directory") + approval_json, approval_md, payload = write_approval_center_artifacts( + report, report_output_dir, approval_view=args.approval_view + ) + print_info(payload.get("approval_workflow_summary", {}).get("summary", "No current approval needs review yet.")) + print_info(payload.get("next_approval_review", {}).get("summary", "Stay local for now; no current approval needs review.")) + print_info(f"Approval center JSON: {approval_json}") + print_info(f"Approval center Markdown: {approval_md}") + _post_process_approval_center_prefs(payload, report_output_dir) + + +def run_approval_capture_mode(args: Any, parser: Any) -> None: + report_output_dir = Path(args.output_dir) + try: + _report_path, diff_dict, report = refresh_latest_report_state(report_output_dir, args) + except FileNotFoundError: + parser.error("No existing audit report found in output directory") + bundle = load_approval_ledger_bundle(report_output_dir, report.to_dict(), list(report.operator_queue or []), approval_view="all") + ledger = {str(item.get("approval_id") or ""): item for item in bundle.get("approval_ledger", [])} + approval_id = f"governance:{args.governance_scope}" if args.approve_governance or args.review_governance else f"campaign:{args.campaign}" + ledger_record = ledger.get(approval_id) + if not ledger_record: + parser.error("No matching approval subject is surfaced in the latest report.") + if args.approve_governance or args.approve_packet: + if ledger_record.get("approval_state") == "blocked": + parser.error("That approval subject is blocked by non-approval prerequisites and cannot be approved yet.") + if ledger_record.get("approval_state") == "not-applicable": + parser.error("That approval subject is not part of the current approval workflow.") + approval_record = build_approval_record(ledger_record, reviewer=args.approval_reviewer, note=args.approval_note or "") + save_approval_record(report_output_dir, approval_record) + else: + if ledger_record.get("approval_state") in {"ready-for-review", "needs-reapproval", "blocked", "not-applicable"}: + parser.error("That approval subject is not currently eligible for a recurring local follow-up review.") + if str(ledger_record.get("follow_up_command") or "").strip() == "": + parser.error("That approval subject does not currently expose a follow-up review command.") + followup_event = build_approval_followup_record(ledger_record, reviewer=args.approval_reviewer, note=args.approval_note or "") + save_approval_followup_event(report_output_dir, followup_event) + _report_path, diff_dict, report = refresh_latest_report_state(report_output_dir, args) + refresh_shared_artifacts_from_report(report, report_output_dir, args, diff_dict=diff_dict) + approval_json, approval_md, _payload = write_approval_center_artifacts(report, report_output_dir, approval_view="all") + updated_bundle = load_approval_ledger_bundle(report_output_dir, report.to_dict(), list(report.operator_queue or []), approval_view="all") + updated_record = next((item for item in updated_bundle.get("approval_ledger", []) if item.get("approval_id") == approval_id), ledger_record) + if args.approve_governance or args.approve_packet: + receipt_payload = {**updated_record, **approval_record} + receipt_json, receipt_md = write_approval_receipt(report_output_dir, report.username, generated_at=_utcnow(), receipt=receipt_payload) + print_info(receipt_payload.get("summary", "Local approval captured.")) + print_info(f"Approval receipt JSON: {receipt_json}") + print_info(f"Approval receipt Markdown: {receipt_md}") + else: + receipt_payload = {**updated_record, **followup_event} + receipt_json, receipt_md = write_followup_review_receipt(report_output_dir, report.username, generated_at=_utcnow(), receipt=receipt_payload) + print_info(receipt_payload.get("summary", "Local follow-up review captured.")) + print_info(f"Approval follow-up receipt JSON: {receipt_json}") + print_info(f"Approval follow-up receipt Markdown: {receipt_md}") + print_info(f"Approval center JSON: {approval_json}") + print_info(f"Approval center Markdown: {approval_md}") diff --git a/src/app/auto_apply.py b/src/app/auto_apply.py new file mode 100644 index 0000000..3fe968b --- /dev/null +++ b/src/app/auto_apply.py @@ -0,0 +1,143 @@ +"""Approved-campaign auto-apply flow. + +Imports remain local to the flow so optional operator dependencies keep their +existing mode-specific loading behavior. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from src.cli_output import print_info +from src.control_center_report_state import refresh_latest_report_state +from src.portfolio_truth_types import truth_latest_path + + +def run_auto_apply_approved_mode(args, output_dir: Path) -> None: + """Apply approved campaign packets for repos that pass the automation trust bar.""" + from src.approval_ledger import load_approval_ledger_bundle + from src.auto_apply import ( + build_trust_bar_index, + filter_safe_actions, + filter_trusted_repo_actions, + get_approved_manual_campaigns, + summarize_trust_bar, + ) + from src.github_client import GitHubClient + from src.ops_writeback import ( + apply_github_writeback, + build_campaign_bundle, + summarize_writeback_results, + ) + from src.warehouse import load_latest_campaign_state + + cache = None if getattr(args, "no_cache", False) else None + client: GitHubClient | None = ( + GitHubClient(token=args.token, cache=cache) if getattr(args, "token", None) else None + ) + + try: + _report_path, _diff_dict, report = refresh_latest_report_state(output_dir, args) + except FileNotFoundError: + print_info("No existing audit report found in output directory. Run a normal audit first.") + return + + truth_path = truth_latest_path(output_dir) + if not truth_path.exists(): + print_info("No portfolio truth snapshot found. Run --portfolio-truth first.") + return + + truth_snapshot = json.loads(truth_path.read_text()) + decision_quality_status = ( + (report.operator_summary or {}) + .get("decision_quality_v1", {}) + .get("decision_quality_status", "") + ) + trust_bar_index = build_trust_bar_index(truth_snapshot, decision_quality_status) + trust_bar_summary = summarize_trust_bar(truth_snapshot, decision_quality_status) + print_info( + "Automation trust bar: " + f"{trust_bar_summary['automation_eligible_count']} opted-in repos; " + f"{trust_bar_summary['baseline_eligible_count']} baseline opted-in repos; " + f"{trust_bar_summary['trusted_repo_count']} repos pass the full trust bar " + f"(decision quality: {trust_bar_summary['decision_quality_status']})." + ) + if trust_bar_summary["automation_eligible_repos"]: + print_info( + "Automation-eligible repos: " + + ", ".join(trust_bar_summary["automation_eligible_repos"]) + ) + + bundle = load_approval_ledger_bundle( + output_dir, + report.to_dict(), + list(report.operator_queue or []), + approval_view="all", + ) + approved_campaigns = get_approved_manual_campaigns(bundle) + + if not approved_campaigns: + print_info("No approved-manual campaign packets found.") + return + + total_applied = 0 + total_skipped = 0 + for record in approved_campaigns: + campaign_type = str(record.get("subject_key") or "") + if not campaign_type: + continue + _campaign_summary, actions = build_campaign_bundle( + report.to_dict(), + campaign_type=campaign_type, + portfolio_profile=getattr(args, "portfolio_profile", None), + collection_name=getattr(args, "collection", None), + max_actions=None, + writeback_target="github", + ) + safe_actions = filter_safe_actions(actions) + trusted_actions = filter_trusted_repo_actions(safe_actions, trust_bar_index) + + if not trusted_actions: + skipped_repos = {str(a.get("repo") or "") for a in actions} - { + str(a.get("repo") or "") for a in trusted_actions + } + print_info( + f"Campaign {campaign_type!r}: 0 eligible actions " + f"(skipped repos: {', '.join(sorted(skipped_repos)) or 'none'})" + ) + total_skipped += len(actions) + continue + + if getattr(args, "dry_run", False): + print_info( + f"Campaign {campaign_type!r}: {len(trusted_actions)} eligible actions " + "but dry-run mode is enabled; no GitHub writes were attempted." + ) + continue + + if client is None: + print_info( + f"Campaign {campaign_type!r}: {len(trusted_actions)} eligible actions " + "but no GitHub client available (dry run)." + ) + continue + + previous_state = load_latest_campaign_state(output_dir, campaign_type) + github_results, _refs, _drift, _closure = apply_github_writeback( + client, + trusted_actions, + previous_state=previous_state, + sync_mode=str(record.get("sync_mode") or "reconcile"), + campaign_summary=_campaign_summary, + github_projects_config=None, + operator_context={}, + ) + summary = summarize_writeback_results(github_results, "github", apply=True) + applied_count = int(summary.get("applied_count", 0)) + total_applied += applied_count + print_info( + f"Campaign {campaign_type!r}: applied {applied_count} / {len(trusted_actions)} actions." + ) + + print_info(f"Auto-apply complete: {total_applied} applied, {total_skipped} skipped.") diff --git a/src/app/automation_proposals.py b/src/app/automation_proposals.py new file mode 100644 index 0000000..4025412 --- /dev/null +++ b/src/app/automation_proposals.py @@ -0,0 +1,146 @@ +"""Bounded-automation proposal queue flow. + +Mode-specific imports stay local to preserve the command's existing dependency +loading and its approval/execution safety boundaries. +""" + +from __future__ import annotations + +from pathlib import Path + +from src.cli_output import print_info, print_warning +from src.control_center_report_state import refresh_latest_report_state + +DEFAULT_PORTFOLIO_WORKSPACE = Path.home() / "Projects" + + +def run_automation_proposals_mode(args) -> None: + """Triage the durable bounded-automation proposal queue (Arc D phase 3b).""" + from datetime import datetime, timezone + + from src.automation_proposals import ( + ACTION_CATALOG_SEED, + ACTION_CONTEXT_PR, + ProposalApprovalError, + ProposalNotFoundError, + approve_proposal, + build_automation_proposals, + load_proposals, + reject_proposal, + save_proposals, + ) + from src.portfolio_automation import select_automation_candidates + + output_dir = Path(args.output_dir) + proposals_path = output_dir / "pending-proposals.json" + now = datetime.now(timezone.utc).isoformat() + + if getattr(args, "approve_proposal", None) or getattr(args, "reject_proposal", None): + try: + proposals = load_proposals(proposals_path) + if getattr(args, "approve_proposal", None): + updated = approve_proposal( + proposals, + args.approve_proposal, + approved_by="local-operator", + approved_at=now, + ) + label = f"Approved proposal {args.approve_proposal!r}." + else: + updated = reject_proposal(proposals, args.reject_proposal, rejected_at=now) + label = f"Rejected proposal {args.reject_proposal!r}." + except (ProposalNotFoundError, ProposalApprovalError, ValueError) as exc: + print_warning(str(exc)) + return + save_proposals(proposals_path, updated) + print_info(label) + return + + if getattr(args, "list_proposals", False): + proposals = load_proposals(proposals_path) + if not proposals: + print_info("No bounded-automation proposals in the queue.") + return + print_info(f"Bounded-automation proposal queue ({len(proposals)} total):") + for proposal in proposals: + print_info(f" {proposal.status}: {proposal.proposal_id} — {proposal.description}") + return + + if getattr(args, "propose_automation", False): + from src.weekly_command_center import load_latest_portfolio_truth + + _truth_path, truth = load_latest_portfolio_truth(output_dir) + if not truth: + print_warning("No portfolio truth snapshot found. Run --portfolio-truth first.") + return + try: + _report_path, _diff, report = refresh_latest_report_state(output_dir, args) + decision_quality_status = ( + (report.operator_summary or {}) + .get("decision_quality_v1", {}) + .get("decision_quality_status", "") + ) + except FileNotFoundError: + decision_quality_status = "" + candidates = select_automation_candidates( + truth, decision_quality_status=decision_quality_status + ) + existing = load_proposals(proposals_path) + merged = build_automation_proposals( + candidates, action_type=ACTION_CONTEXT_PR, created_at=now, existing=existing + ) + merged = build_automation_proposals( + candidates, action_type=ACTION_CATALOG_SEED, created_at=now, existing=merged + ) + save_proposals(proposals_path, merged) + print_info( + f"Proposal queue: {len(merged)} total ({len(merged) - len(existing)} new) " + f"from {len(candidates)} eligible candidate(s)." + ) + return + + if getattr(args, "execute_proposals", False): + from src.automation_proposals import executable_proposals + from src.automation_workflow import execute_approved_proposals + from src.portfolio_truth_reconcile import build_portfolio_truth_snapshot + + if not executable_proposals(load_proposals(proposals_path)): + print_info("No approved bounded-automation proposals to execute.") + return + + workspace_root = Path(getattr(args, "workspace_root", None) or DEFAULT_PORTFOLIO_WORKSPACE) + catalog_path = ( + Path(args.catalog) + if getattr(args, "catalog", None) + else Path("config/portfolio-catalog.yaml") + ) + registry_output = ( + Path(args.registry_output) + if getattr(args, "registry_output", None) + else workspace_root / "project-registry.md" + ) + legacy_registry_path = ( + Path(args.registry) if getattr(args, "registry", None) else registry_output + ) + build_result = build_portfolio_truth_snapshot( + workspace_root=workspace_root, + catalog_path=catalog_path if catalog_path.exists() else None, + legacy_registry_path=legacy_registry_path, + include_notion=True, + ) + apply = bool(getattr(args, "apply", False)) + results = execute_approved_proposals( + proposals_path=proposals_path, + snapshot=build_result.snapshot, + workspace_root=workspace_root, + catalog_path=catalog_path, + executed_at=now, + dry_run=not apply, + ) + if not results: + print_info("No approved bounded-automation proposals to execute.") + return + for result in results: + print_info(f" {result.outcome}: {result.proposal_id} — {result.detail}") + mode = "apply" if apply else "dry-run" + print_info(f"Execute proposals ({mode}): {len(results)} approved proposal(s) processed.") diff --git a/src/app/campaign_workflow.py b/src/app/campaign_workflow.py new file mode 100644 index 0000000..9fddbaa --- /dev/null +++ b/src/app/campaign_workflow.py @@ -0,0 +1,396 @@ +"""Campaign planning, ledger execution, and README drafting flows. + +Function-local imports deliberately preserve optional integration behavior. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from src.cli_output import print_info +from src.portfolio_truth_types import truth_latest_path + + +def _run_campaign_from_ledger_mode(args) -> None: + """Dispatch for --campaign-from-ledger [--writeback-apply] [--dry-run]. + + Loads approved campaign-plan packets from the ledger and executes each + action via the existing apply executor map. Dry-run mode prints what would + be executed without calling the GitHub API. + """ + from src.cache import ResponseCache + from src.github_client import GitHubClient + from src.plan_campaign import ( + dispatch_action, + load_approved_campaign_plans, + mark_campaign_applied, + record_campaign_apply_failure, + ) + + output_dir = Path(args.output_dir) + dry_run = getattr(args, "dry_run", False) + username = getattr(args, "username", "") or "" + + cache = None if args.no_cache else ResponseCache() + client = GitHubClient(token=args.token, cache=cache) + + packets = load_approved_campaign_plans(output_dir) + + if not packets: + print_info("campaign-from-ledger: 0 approved packets found — nothing to apply.") + return + + verb = "preview" if dry_run else "apply" + print_info(f"campaign-from-ledger: {len(packets)} approved packet(s) to {verb}.") + + for packet in packets: + print_info(f" packet goal: {packet.goal[:80]!r} ({len(packet.actions)} actions)") + + action_results: list[tuple[bool, str]] = [] + for action in packet.actions: + # 7B.5 — only dispatch actions that have been explicitly approved; + # skip pending and rejected actions. + action_state = getattr(action, "state", "pending") or "pending" + if action_state != "approved": + skip_label = "rejected" if action_state == "rejected" else "pending" + print_info(f" [skip:{skip_label}] {action.action_type} {action.repo_name}") + action_results.append((True, f"skipped ({skip_label})")) + continue + + if dry_run: + # Dry-run: print preview, record as success for state purposes + msg = ( + f"would execute: {action.action_type} {action.repo_name}" + f" (target={action.target!r}, rationale={action.rationale[:60]!r})" + ) + print_info(f" [dry-run] {msg}") + action_results.append((True, msg)) + else: + ok, msg = dispatch_action( + action, + client=client, + owner=username, + dry_run=False, + ) + status = "ok" if ok else "FAIL" + print_info(f" [{status}] {action.action_type} {action.repo_name}: {msg}") + action_results.append((ok, msg)) + + if dry_run: + # Do not mutate ledger state on dry-run + continue + + # 7B.5 — only mark applied when every action is terminal (approved+applied or rejected). + # If any action is still pending, leave as approved-manual for the operator to revisit. + has_pending = any( + (getattr(a, "state", "pending") or "pending") == "pending" for a in packet.actions + ) + if has_pending: + print_info( + " packet kept approved-manual — some actions still pending per-action review" + ) + continue + + # Determine overall packet success: + # "applied" only when every supported action succeeded AND every + # unsupported/pending action is in the packet as pending_human_action. + # Mixed-result packets (a supported action failed) stay approved-manual + # with a failure event listing the failed actions. + supported_results = [ + (ok, msg) + for (ok, msg), action in zip(action_results, packet.actions) + if action.action_type + not in ("pending_human_action", "add_license", "add_codeowners", "enable_dependabot") + and (getattr(action, "state", "pending") or "pending") != "rejected" + ] + unsupported_results = [ + (ok, msg) + for (ok, msg), action in zip(action_results, packet.actions) + if action.action_type in ("add_license", "add_codeowners", "enable_dependabot") + ] + + # Unimplemented-handler actions are expected failures — don't penalise the packet + # as long as no genuinely-supported action failed. + failed_supported = [(ok, msg) for ok, msg in supported_results if not ok] + + if not failed_supported: + mark_campaign_applied(packet, output_dir) + print_info( + f" packet marked applied " + f"(supported={len(supported_results)}, skipped={len(unsupported_results)})" + ) + else: + error_summary = "; ".join(msg for _, msg in failed_supported) + record_campaign_apply_failure(packet, error_summary, output_dir) + print_info( + f" packet kept approved-manual — {len(failed_supported)} failure(s): {error_summary[:120]}" + ) + +def _run_plan_campaign_mode(args) -> None: + """Dispatch for --plan-campaign: generate a goal-driven campaign plan packet.""" + from src.approval_ledger import default_approval_reviewer as _default_reviewer + from src.llm_cost import BudgetExceededError, CostTracker + from src.narrative import _resolve_provider + from src.operator_prefs import load_prefs, prefs_path + from src.plan_campaign import generate_plan, narrow_candidates, write_packet_to_ledger + from src.warehouse import WAREHOUSE_FILENAME + + output_dir = Path(args.output_dir) + goal: str = str(args.plan_campaign).strip() + max_repos: int = int(getattr(args, "max_repos", 50) or 50) + reviewer: str = getattr(args, "approval_reviewer", None) or _default_reviewer() + + # ── Load audit results from portfolio-truth-latest.json ─────────────────── + truth_path = truth_latest_path(output_dir) + if not truth_path.exists(): + print_info( + f"portfolio-truth-latest.json not found in {output_dir}. " + "Run `audit report --portfolio-truth` first to generate repo data. " + "--plan-campaign requires a truth snapshot to select candidates." + ) + return + + try: + raw = json.loads(truth_path.read_text(encoding="utf-8")) + audit_results: list[dict] = list(raw.get("repos", raw.get("results", []))) + except (OSError, json.JSONDecodeError) as exc: + print_info(f"Error reading portfolio-truth-latest.json: {exc}") + return + + # ── Semantic index (optional — fallback to alphabetical if unavailable) ──── + semantic_index = None + warehouse_path = output_dir / WAREHOUSE_FILENAME + if warehouse_path.exists(): + try: + from src.semantic_index import SemanticIndex + + semantic_index = SemanticIndex(output_dir) + except Exception as exc: # noqa: BLE001 + print_info( + f"Warning: could not load SemanticIndex: {exc} — using alphabetical fallback." + ) + + # ── LLM provider ────────────────────────────────────────────────────────── + provider_result = _resolve_provider( + getattr(args, "narrative_provider", None), + getattr(args, "narrative_model", None), + getattr(args, "token", None), + ) + if provider_result is None: + print_info( + "No LLM provider available for --plan-campaign. " + "Set ANTHROPIC_API_KEY or GITHUB_TOKEN, or pass --narrative-provider." + ) + return + provider, model = provider_result + + # ── Cost tracker ────────────────────────────────────────────────────────── + budget_usd = getattr(args, "max_llm_spend", None) + cost_tracker: CostTracker = CostTracker(budget_usd=budget_usd, output_path=output_dir) + + # ── Operator prefs ──────────────────────────────────────────────────────── + pref_file = prefs_path(output_dir) + prefs = load_prefs(pref_file) + + # ── Narrow candidates ───────────────────────────────────────────────────── + candidates = narrow_candidates( + audit_results, + goal=goal, + semantic_index=semantic_index, + max_repos=max_repos, + ) + if not candidates: + print_info("No candidate repos found. Check that portfolio-truth-latest.json has data.") + return + + # ── Generate plan ───────────────────────────────────────────────────────── + import sys + + try: + packet = generate_plan( + candidates, + goal=goal, + provider=provider, + model=model, + cost_tracker=cost_tracker, + prefs=prefs, + ) + except BudgetExceededError as exc: + print(f"\nERROR: LLM budget exceeded during campaign planning: {exc}", file=sys.stderr) + return + + # ── Persist packet to ledger ────────────────────────────────────────────── + record_id = write_packet_to_ledger(packet, output_dir=output_dir, reviewer=reviewer) + + cost_tracker.write_telemetry() + + pending_count = sum(1 for a in packet.actions if a.action_type == "pending_human_action") + print_info( + f"Goal: {goal}. " + f"Considered {packet.candidate_count}. " + f"Qualified {packet.qualified_count}. " + f"{pending_count} pending human review. " + f"LLM cost: ${packet.llm_cost_usd:.4f}. " + f"Packet ID: {record_id}." + ) + +def _run_draft_readmes_mode(args) -> None: + """Dispatch for --draft-readmes: generate LLM-authored README draft packets.""" + import sys + + from src.approval_ledger import default_approval_reviewer as _default_reviewer + from src.draft_readmes import ( + build_context, + generate_draft, + qualify_repos, + write_packets_to_ledger, + ) + from src.llm_cost import BudgetExceededError, CostTracker + from src.narrative import _resolve_provider + from src.operator_prefs import ( + is_suppressed, + load_prefs, + post_process_approval_session, + prefs_path, + ) + + output_dir = Path(args.output_dir) + opt_in_repos: list[str] = list(getattr(args, "draft_readmes_repos", None) or []) + all_qualifying: bool = bool(getattr(args, "draft_readmes_all", False)) + reviewer: str = getattr(args, "approval_reviewer", None) or _default_reviewer() + + if not opt_in_repos and not all_qualifying: + print_info( + "--draft-readmes requires --draft-readmes-all or at least one --draft-readmes-repo. " + "No repos selected." + ) + return + + # ── Load audit results (portfolio-truth-latest.json or warehouse) ───────── + audit_results: list[dict] = [] + truth_path = truth_latest_path(output_dir) + if truth_path.exists(): + try: + raw = json.loads(truth_path.read_text(encoding="utf-8")) + audit_results = list(raw.get("repos", raw.get("results", []))) + except (OSError, json.JSONDecodeError) as exc: + print_info(f"Warning: could not read portfolio-truth-latest.json: {exc}") + else: + print_info( + f"portfolio-truth-latest.json not found in {output_dir}. " + "Run `audit report --portfolio-truth` first to populate repo data. " + "Proceeding with empty repo list — only explicit --draft-readmes-repo repos will be drafted." + ) + + # ── Qualify repos ────────────────────────────────────────────────────────── + repo_names = qualify_repos( + audit_results, opt_in_repos=opt_in_repos, all_qualifying=all_qualifying + ) + if not repo_names: + print_info("No repos qualify for --draft-readmes with current flags.") + return + + # Build a name → dict lookup for fast access + repo_by_name: dict[str, dict] = { + str(r.get("repo_name") or r.get("name") or ""): r for r in audit_results + } + # Repos requested via --draft-readmes-repo may not exist in audit_results — create stubs + for name in repo_names: + if name not in repo_by_name: + repo_by_name[name] = {"repo_name": name, "name": name} + + # ── Semantic index (optional — proceed without neighbors if unavailable) ──── + semantic_index = None + warehouse_path = output_dir / "portfolio-warehouse.db" + if warehouse_path.exists(): + try: + from src.semantic_index import SemanticIndex + + semantic_index = SemanticIndex(output_dir) + except Exception as exc: # noqa: BLE001 + print_info( + f"Warning: could not load SemanticIndex: {exc} — proceeding without neighbors." + ) + + # ── LLM provider ────────────────────────────────────────────────────────── + provider_result = _resolve_provider( + getattr(args, "narrative_provider", None), + getattr(args, "narrative_model", None), + getattr(args, "token", None), + ) + if provider_result is None: + print_info( + "No LLM provider available for --draft-readmes. " + "Set ANTHROPIC_API_KEY or GITHUB_TOKEN, or pass --narrative-provider." + ) + return + provider, model = provider_result + + # ── Cost tracker ────────────────────────────────────────────────────────── + cost_tracker: CostTracker | None = None + budget_usd = getattr(args, "max_llm_spend", None) + if budget_usd is not None or True: # always track telemetry + cost_tracker = CostTracker(budget_usd=budget_usd, output_path=output_dir) + + # ── Operator prefs ──────────────────────────────────────────────────────── + pref_file = prefs_path(output_dir) + prefs = load_prefs(pref_file) + + # ── Main loop ───────────────────────────────────────────────────────────── + packets = [] + skipped_suppressed = 0 + skipped_budget = 0 + errors = 0 + + for repo_name in repo_names: + # 5.3 — suppression check + if is_suppressed(prefs, action_type="draft-readme", target_context=repo_name): + print_info(f" skip {repo_name}: suppressed by operator prefs") + skipped_suppressed += 1 + continue + + repo = repo_by_name[repo_name] + context = build_context(repo, semantic_index=semantic_index) + + try: + packet = generate_draft( + repo, context=context, provider=provider, model=model, cost_tracker=cost_tracker + ) + packets.append(packet) + print_info(f" drafted {repo_name} ({packet.diff_summary})") + except BudgetExceededError as exc: + print(f"\nERROR: LLM budget exceeded at {repo_name}: {exc}", file=sys.stderr) + skipped_budget = len(repo_names) - len(packets) - skipped_suppressed - 1 + break + except Exception as exc: # noqa: BLE001 + print_info(f" error drafting {repo_name}: {exc}") + errors += 1 + + # ── Persist packets ──────────────────────────────────────────────────────── + if packets: + write_packets_to_ledger(packets, output_dir, reviewer) + + # ── Refresh suppressions from rejection history ──────────────────────────── + # We pass an empty list here — newly-generated drafts have no decision yet, + # so detect_suppressions would find zero consecutive rejections. The real + # suppression update happens when the operator rejects via approval_request_reject. + # Calling post_process_approval_session with [] is a no-op but keeps the prefs + # file consistent and auto-prunes stale hints if any exist. + if pref_file.parent.exists(): + try: + post_process_approval_session([], output_dir) + except Exception as exc: # noqa: BLE001 + print_info(f"Warning: could not refresh suppression hints: {exc}") + + if cost_tracker is not None: + cost_tracker.write_telemetry() + + total_cost = cost_tracker.total_usd() if cost_tracker is not None else 0.0 + print_info( + f"Drafted {len(packets)} packet(s) for {len(packets)} repo(s). " + f"{skipped_suppressed} skipped (prefs). " + f"{skipped_budget} skipped (budget). " + f"{errors} error(s). " + f"LLM cost: ${total_cost:.4f}." + ) diff --git a/src/app/control_center.py b/src/app/control_center.py new file mode 100644 index 0000000..7bac32d --- /dev/null +++ b/src/app/control_center.py @@ -0,0 +1,62 @@ +"""Control-center application flow.""" + +from __future__ import annotations + +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from src.cli_output import print_info +from src.control_center_presentation import ( + _control_center_next_step_hint, + _print_control_center_summary, +) +from src.control_center_snapshot import enrich_control_center_snapshot_from_report +from src.diff import diff_reports +from src.governance_activation import build_governance_summary +from src.history import find_previous +from src.operator_control_center import build_operator_snapshot, normalize_review_state +from src.operator_control_center_artifacts import write_control_center_artifacts +from src.report_state import load_latest_report, parse_iso_datetime, report_artifact_datetime + + +def run_control_center_mode(args: Any, parser: Any) -> None: + output_dir = Path(args.output_dir) + report_path, report_data = load_latest_report(output_dir) + if not report_path or not report_data: + parser.error("No existing audit report found in output directory") + diff_dict = None + previous_path = find_previous(report_path.name) + if previous_path: + diff_dict = diff_reports( + previous_path, report_path, portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ).to_dict() + report_data["latest_report_path"] = str(report_path) + normalized = normalize_review_state( + report_data, output_dir=output_dir, diff_data=diff_dict, + portfolio_profile=args.portfolio_profile, collection_name=args.collection, + ) + normalized["governance_summary"] = build_governance_summary(normalized) + snapshot = build_operator_snapshot(normalized, output_dir=output_dir, triage_view=args.triage_view) + snapshot = enrich_control_center_snapshot_from_report(normalized, snapshot, args) + artifact_generated_at = report_artifact_datetime( + report_path, parse_iso_datetime(normalized.get("generated_at")) or datetime.now(timezone.utc) + ) + json_artifact, md_artifact, weekly_json, weekly_md, payload = write_control_center_artifacts( + normalized, snapshot, output_dir, username=normalized.get("username", args.username), + generated_at=artifact_generated_at, report_reference=str(report_path), diff_dict=diff_dict, + ) + weekly_digest = payload.get("weekly_command_center_digest_v1", {}) + source_freshness = weekly_digest.get("source_freshness", {}) + if source_freshness.get("status") and source_freshness.get("status") != "current": + print_info(weekly_digest.get("headline") or "Refresh the audit report before acting.") + print_info(source_freshness.get("summary") or "Control-center source freshness could not be proven.") + print_info(weekly_digest.get("decision") or "Refresh the audit report, then rerun.") + else: + _print_control_center_summary(snapshot) + print_info(f"Control center JSON: {json_artifact}") + print_info(f"Control center Markdown: {md_artifact}") + print_info(f"Weekly command center JSON: {weekly_json}") + print_info(f"Weekly command center Markdown: {weekly_md}") + print_info(_control_center_next_step_hint()) diff --git a/src/app/doctor.py b/src/app/doctor.py new file mode 100644 index 0000000..a1b53a1 --- /dev/null +++ b/src/app/doctor.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.cli_output import print_info +from src.diagnostics import ( + format_diagnostics_report, + run_diagnostics, + write_diagnostics_report, +) + + +def doctor_next_step_hint(username: str) -> str: + return ( + f"Next step: run `audit {username} --html` for the standard workbook, then " + f"`audit {username} --control-center` for read-only weekly triage." + ) + + +def run_doctor_mode(args: Any, config_inspection: Any) -> None: + result = run_diagnostics(args, config_inspection=config_inspection, full=True) + output_dir = Path(args.output_dir) + artifact_path = write_diagnostics_report(result, output_dir, args.username) + print(format_diagnostics_report(result)) + print_info(f"Diagnostics artifact: {artifact_path}") + print_info(doctor_next_step_hint(args.username)) + if result.blocking_errors: + raise SystemExit(1) diff --git a/src/app/improvement_application.py b/src/app/improvement_application.py new file mode 100644 index 0000000..621b4fb --- /dev/null +++ b/src/app/improvement_application.py @@ -0,0 +1,160 @@ +"""Improvement application flow with dry-run and ledger transitions.""" + +from __future__ import annotations + +from pathlib import Path + +from src.cache import ResponseCache +from src.cli_output import print_info +from src.github_client import GitHubClient + + +def _run_apply_improvements_mode(args, parser) -> None: + from src.repo_improver import ( + apply_metadata_updates, + apply_readme_updates, + generate_execution_report, + load_improvements, + ) + + improvements_file = getattr(args, "improvements_file", None) + apply_readmes = getattr(args, "apply_readmes", False) + apply_metadata = getattr(args, "apply_metadata", False) + + # --apply-metadata always needs a file; --apply-readmes can read from ledger instead. + if apply_metadata and not improvements_file: + parser.error("--apply-metadata requires --improvements-file") + if not apply_readmes and not apply_metadata: + parser.error("--apply-metadata / --apply-readmes requires --improvements-file") + + cache = None if args.no_cache else ResponseCache() + client = GitHubClient(token=args.token, cache=cache) + output_dir = Path(args.output_dir) + dry_run = getattr(args, "dry_run", False) + + # Load file-based updates (may be empty if no file supplied) + file_updates: list[dict] = [] + if improvements_file: + file_updates = list(load_improvements(improvements_file).values()) + + all_results: list[dict] = [] + + if apply_metadata: + results = apply_metadata_updates(client, args.username, file_updates, dry_run=dry_run) + all_results.extend(results) + ok_count = sum( + 1 for r in results for a in r.get("actions", []) if a.get("ok") or a.get("dry_run") + ) + print_info(f"Metadata updates: {ok_count} actions {'previewed' if dry_run else 'applied'}") + + if apply_readmes: + # Build the merged update list: + # 1) file-based packets (if --improvements-file provided) + # 2) approved ledger packets (if any, de-duplicated by repo name) + readme_updates: list[dict] = list(file_updates) + ledger_packets_by_repo: dict[str, object] = {} + + from src.draft_readmes import ( + assemble_readme_from_approved_sections, + load_approved_drafts, + load_approved_sectioned_packets, + mark_draft_applied, + mark_section_packet_applied, + record_draft_apply_failure, + ) + + # ── Path A: per-section sub-records (Sprint 8.5) ───────────────────── + sectioned_packets = load_approved_sectioned_packets(output_dir) + sectioned_updates_by_repo: dict[str, tuple[str, str]] = {} # repo → (packet_id, readme) + for pid, sections in sectioned_packets.items(): + repo_name_sec: str = str((sections[0].get("repo_name") or "") if sections else "") + if not repo_name_sec: + continue + assembled = assemble_readme_from_approved_sections(sections) + if assembled is None: + print_info(f"sectioned packet {pid} has no approved sections; skipping") + continue + pending = [s for s in sections if s.get("state", "pending") == "pending"] + if pending: + print_info(f"sectioned packet {pid} has {len(pending)} pending sections; skipping") + continue + sectioned_updates_by_repo[repo_name_sec] = (pid, assembled) + + for repo_name_sec, (pid, assembled_readme) in sectioned_updates_by_repo.items(): + file_names = {(u.get("name") or u.get("repo", "").split("/")[-1]) for u in file_updates} + if repo_name_sec not in file_names: + readme_updates.append({"name": repo_name_sec, "readme": assembled_readme}) + if dry_run: + char_count = len(assembled_readme) + print_info( + f" [dry-run] would push sectioned README to {repo_name_sec}: " + f"{char_count} chars" + ) + + # ── Path B: legacy whole-packet records ─────────────────────────────── + ledger_packets = load_approved_drafts(output_dir, getattr(args, "username", None)) + for pkt in ledger_packets: + # Convert DraftReadmePacket → shape expected by apply_readme_updates + # apply_readme_updates expects: {name: str, readme: str} + # De-duplicate: file-based takes precedence (already present in readme_updates). + file_names = {(u.get("name") or u.get("repo", "").split("/")[-1]) for u in file_updates} + if pkt.repo_name not in file_names: + readme_updates.append({"name": pkt.repo_name, "readme": pkt.proposed_readme}) + ledger_packets_by_repo[pkt.repo_name] = pkt + + if not readme_updates: + print_info("README updates: 0 repos to apply (no file and no approved ledger packets).") + else: + if dry_run: + # Print per-repo preview lines for ledger-sourced packets so the operator + # can see what would be pushed. File-based packets are also covered because + # apply_readme_updates returns {"dry_run": True} records when dry_run=True. + for pkt_repo, _pkt in ledger_packets_by_repo.items(): + upd = next( + ( + u + for u in readme_updates + if (u.get("name") or u.get("repo", "").split("/")[-1]) == pkt_repo + ), + None, + ) + if upd is not None: + char_count = len(upd.get("readme", "")) + print_info( + f" [dry-run] would push README to {pkt_repo}: {char_count} chars" + ) + + results = apply_readme_updates(client, args.username, readme_updates, dry_run=dry_run) + all_results.extend(results) + + # State transitions for ledger-sourced packets (live apply only) + if not dry_run: + for result in results: + repo_name = result.get("repo", "") + # Path A: sectioned packets + if repo_name in sectioned_updates_by_repo: + pid, _assembled = sectioned_updates_by_repo[repo_name] + if result.get("ok"): + mark_section_packet_applied(pid, output_dir) + # Path B: legacy whole-packet records + elif repo_name in ledger_packets_by_repo: + pkt = ledger_packets_by_repo[repo_name] + if result.get("ok"): + mark_draft_applied(output_dir, pkt, apply_result=result) # type: ignore[arg-type] + else: + error_msg = str(result.get("error") or "unknown error") + record_draft_apply_failure(output_dir, pkt, error=error_msg) # type: ignore[arg-type] + + ok_count = sum(1 for r in results if r.get("ok") or r.get("dry_run")) + verb = "previewed" if dry_run else "pushed" + print_info( + f"README updates: {ok_count} repos {verb}" + + ( + f" ({len(ledger_packets_by_repo)} from ledger)" + if ledger_packets_by_repo + else "" + ) + ) + + report_path = generate_execution_report(all_results, output_dir) + print_info(f"Execution report: {report_path}") diff --git a/src/app/initiative_suggestions.py b/src/app/initiative_suggestions.py new file mode 100644 index 0000000..2d4d7af --- /dev/null +++ b/src/app/initiative_suggestions.py @@ -0,0 +1,183 @@ +"""Optional LLM initiative-suggestion and dismissal commands. + +Local imports inside each flow preserve mode-specific dependency loading and +the established error behavior. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from src.cli_output import print_info, print_warning +from src.portfolio_truth_types import truth_latest_path + + +def _run_suggest_initiatives_mode(args) -> None: + """LLM-rank repos closest to qualifying for their next maturity tier (Arc G S8.4).""" + from pathlib import Path as _Path + + from src.llm_cost import BudgetExceededError + from src.maturity_tiers import tier_name + from src.suggest_initiatives import generate_suggestions + + truth_path = truth_latest_path(_Path(args.output_dir)) + if not truth_path.exists(): + print_warning( + "portfolio-truth-latest.json not found. " + "Run `audit triage USERNAME --portfolio-truth` first." + ) + return + + truth = json.loads(truth_path.read_text()) + projects = truth.get("projects", []) + + # 0 is the const sentinel meaning "use per-repo next tier" + target = args.suggest_initiatives if args.suggest_initiatives else None + budget = args.llm_budget if args.llm_budget is not None else 0.10 + + try: + suggestions, cost = generate_suggestions(projects, target_tier=target, budget_usd=budget) + except BudgetExceededError as exc: + print(f"\nERROR: LLM budget exceeded: {exc}", file=sys.stderr) + return + + if not suggestions: + print_info("No suggestions: no repos are close to qualifying for the next tier.") + return + + print_info(f"Suggested Initiatives ({len(suggestions)} candidates, ${cost:.4f} spent)") + print() + for s in suggestions: + print( + f" {s.repo_name:<30} {tier_name(s.current_tier)} → {tier_name(s.target_tier):<10} " + f"[{s.estimated_effort}]" + ) + print(f" Missing: {', '.join(s.missing_requirements)}") + print(f" Rationale: {s.rationale}") + print() + +def _run_accept_suggestion_mode(args) -> None: + """Accept a suggestion: convert it into a tier-upgrade initiative (Arc G S9.1).""" + import sys + + from src.suggest_initiatives import accept_suggestion + + output_dir = Path(args.output_dir) + truth_path = truth_latest_path(output_dir) + if not truth_path.exists(): + print_warning( + "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." + ) + return + + try: + truth = json.loads(truth_path.read_text()) + except (OSError, json.JSONDecodeError) as exc: + print_warning(f"Failed to read portfolio-truth: {exc}") + return + + projects = truth.get("projects", []) + + try: + initiative = accept_suggestion( + repo_name=args.accept_suggestion, + projects=projects, + output_dir=output_dir, + deadline=getattr(args, "deadline", None), + target_tier=getattr(args, "target_tier", None), + ) + except ValueError as exc: + print_warning(str(exc)) + sys.exit(2) + + print_info( + f"Initiative accepted: {initiative.repo_name} → " + f"Tier {initiative.target_tier} by {initiative.deadline}" + ) + +def _run_dismiss_suggestion_mode(args) -> None: + """Dismiss a repo from future LLM-suggested initiatives (Arc G S11.4).""" + import sys + from pathlib import Path + + from src.suggest_initiatives import dismiss_suggestion_record, dismissed_path + + output_dir = Path(args.output_dir) + try: + entry = dismiss_suggestion_record( + dismissed_path(output_dir), + repo_name=args.dismiss_suggestion, + reason=getattr(args, "reason", "") or "", + expires_days=getattr(args, "dismiss_expires_days", None), + ) + except ValueError as exc: + print_warning(str(exc)) + sys.exit(2) + expiry_note = f" (expires {entry.expires_at})" if entry.expires_at else "" + print_info( + f"✗ Dismissed: {entry.repo_name}" + + (f" — {entry.reason}" if entry.reason else "") + + expiry_note + ) + +def _run_undo_dismiss_mode(args) -> None: + """Restore a dismissed repo to the suggestion pool (Arc G S11.4).""" + from pathlib import Path + + from src.suggest_initiatives import dismissed_path, undo_dismiss + + output_dir = Path(args.output_dir) + removed = undo_dismiss(dismissed_path(output_dir), args.undo_dismiss) + if removed: + print_info(f"✓ Restored: {args.undo_dismiss}") + else: + print_warning(f"{args.undo_dismiss} was not dismissed; nothing to undo") + +def _run_list_dismissed_mode(args) -> None: + """List all currently dismissed suggestion repos (Arc G S11.4).""" + from pathlib import Path + + from src.suggest_initiatives import dismissed_path, load_dismissed + + output_dir = Path(args.output_dir) + items = load_dismissed(dismissed_path(output_dir)) + if not items: + print_info("No dismissed suggestions.") + return + print_info(f"Dismissed Suggestions ({len(items)})") + for d in items: + reason = f" — {d.reason}" if d.reason else "" + print(f" {d.repo_name:<30} dismissed {d.dismissed_at[:10]} by {d.dismissed_by}{reason}") + +def _run_expire_dismissals_mode(args) -> None: + """Remove dismissals whose expiry date has passed (Arc G S12.1).""" + from pathlib import Path + + from src.suggest_initiatives import dismissed_path, expire_dismissals + + output_dir = Path(args.output_dir) + expired = expire_dismissals(dismissed_path(output_dir)) + if not expired: + print_info("No dismissals to expire.") + return + print_info(f"Expired {len(expired)} dismissal(s):") + for d in expired: + print(f" {d.repo_name:<30} (was set to expire {d.expires_at})") + +def _run_dismissal_history_mode(args) -> None: + """Show audit trail of dismissal events (Arc G S12.1).""" + from pathlib import Path + + from src.suggest_initiatives import dismissed_path, load_dismissal_events + + output_dir = Path(args.output_dir) + events = load_dismissal_events(dismissed_path(output_dir)) + if not events: + print_info("No dismissal history.") + return + print_info(f"Dismissal History ({len(events)} event(s))") + for e in events: + reason = f" — {e.reason}" if e.reason else "" + print(f" {e.occurred_at[:19]} {e.event_type:<10} {e.repo_name:<30} by {e.actor}{reason}") diff --git a/src/app/initiatives.py b/src/app/initiatives.py new file mode 100644 index 0000000..6bf815e --- /dev/null +++ b/src/app/initiatives.py @@ -0,0 +1,128 @@ +"""Deterministic initiative-management commands.""" + +from __future__ import annotations + +import json +import sys +from datetime import date, datetime, timezone +from pathlib import Path + +from src.cli_output import print_info, print_warning +from src.portfolio_truth_types import TRUTH_LATEST_FILENAME, truth_latest_path + + +def run_set_initiative_mode(args) -> None: + """Validate and persist a tier-upgrade initiative for a repo.""" + from src.initiatives import Initiative, initiatives_path, operator_identity, upsert_initiative + from src.maturity_tiers import TIER_DEFINITIONS, compute_tier + + repo_name: str = args.set_initiative + target_tier: int | None = getattr(args, "target_tier", None) + deadline_str: str | None = getattr(args, "deadline", None) + output_dir = Path(args.output_dir) + if target_tier is None: + print_warning("--target-tier is required with --set-initiative (choices: 2, 3, 4)") + sys.exit(2) + if deadline_str is None: + print_warning("--deadline YYYY-MM-DD is required with --set-initiative") + sys.exit(2) + try: + deadline_date = date.fromisoformat(deadline_str) + except ValueError: + print_warning(f"--deadline must be YYYY-MM-DD, got: {deadline_str!r}") + sys.exit(2) + if deadline_date < date.today(): + print_warning(f"--deadline {deadline_str} is in the past. Provide a future date.") + sys.exit(2) + pt_candidates = sorted(output_dir.glob(TRUTH_LATEST_FILENAME)) + if not pt_candidates: + pt_candidates = sorted(output_dir.glob("portfolio-truth-*.json")) + if not pt_candidates: + print_warning(f"Portfolio truth not found in {output_dir}. Run `audit report --portfolio-truth` first.") + sys.exit(2) + pt_path = truth_latest_path(output_dir) + if not pt_path.exists(): + pt_path = pt_candidates[-1] + try: + pt_data = json.loads(pt_path.read_text(encoding="utf-8")) + except (OSError, ValueError) as exc: + print_warning(f"Could not read portfolio truth: {exc}") + sys.exit(2) + repo_dict = next( + (project for project in pt_data.get("projects", []) + if project.get("identity", {}).get("display_name", "").lower() == repo_name.lower()), + None, + ) + if repo_dict is None: + print_warning(f"Repo {repo_name!r} not found in portfolio truth. Run `audit report --portfolio-truth` first.") + sys.exit(2) + current_tier = compute_tier(repo_dict) + if target_tier <= current_tier: + target_name = TIER_DEFINITIONS[target_tier].name + current_name = TIER_DEFINITIONS[current_tier].name if current_tier > 0 else "Untracked" + print_warning(f"Target tier {target_tier} ({target_name}) is not greater than current tier {current_tier} ({current_name}) for {repo_name!r}.") + sys.exit(2) + initiative = Initiative(repo_name=repo_name, target_tier=target_tier, deadline=deadline_str, + set_at=datetime.now(tz=timezone.utc).isoformat(), set_by=operator_identity()) + upsert_initiative(initiatives_path(output_dir), initiative) + print_info(f"Initiative set: {repo_name} → Tier {target_tier} ({TIER_DEFINITIONS[target_tier].name}) by {deadline_str}") + + +def run_list_initiatives_mode(args) -> None: + """Print a status table for all initiatives.""" + from src.initiatives import derive_status, initiatives_path, load_initiatives + from src.maturity_tiers import TIER_DEFINITIONS, compute_tier, tier_name + + output_dir = Path(args.output_dir) + initiatives = load_initiatives(initiatives_path(output_dir)) + projects_by_name: dict[str, dict] = {} + pt_path = truth_latest_path(output_dir) + if pt_path.exists(): + try: + for project in json.loads(pt_path.read_text(encoding="utf-8")).get("projects", []): + name = project.get("identity", {}).get("display_name", "") + if name: + projects_by_name[name.lower()] = project + except (OSError, ValueError): + # Listing remains useful without optional portfolio-truth tier context. + pass + open_initiatives = [item for item in initiatives if item.closed_at is None] + closed_initiatives = [item for item in initiatives if item.closed_at is not None] + print_info("Initiative Tracker") + print_info("══════════════════") + if not open_initiatives: + print_info("No open initiatives.") + else: + header = f"{'REPO':<30} {'TARGET':<12} {'CURRENT':<12} {'DEADLINE':<12} {'STATUS'}" + print_info(header) + print_info("-" * len(header)) + for initiative in open_initiatives: + repo_dict = projects_by_name.get(initiative.repo_name.lower(), {}) + current = compute_tier(repo_dict) if repo_dict else 0 + status = derive_status(initiative, repo_dict) + target_label = f"{TIER_DEFINITIONS[initiative.target_tier].name}({initiative.target_tier})" if initiative.target_tier in TIER_DEFINITIONS else str(initiative.target_tier) + current_label = f"{tier_name(current)}({current})" if current > 0 else "Untracked" + status_detail = status + if status == "at-risk": + try: + status_detail = f"at-risk (deadline ≤ {(date.fromisoformat(initiative.deadline) - date.today()).days}d)" + except ValueError: + # Preserve the generic status for malformed historical deadlines. + pass + elif status == "on-track": + status_detail = "on-track" + print_info(f"{initiative.repo_name:<30} {target_label:<12} {current_label:<12} {initiative.deadline:<12} {status_detail}") + if closed_initiatives: + print_info(f"\nClosed: {len(closed_initiatives)}") + + +def run_close_initiative_mode(args) -> None: + """Close the open initiative for a repo.""" + from src.initiatives import close_initiative, initiatives_path + + repo_name: str = args.close_initiative + closed = close_initiative(initiatives_path(Path(args.output_dir)), repo_name, reason="met") + if closed is None: + print_warning(f"No open initiative found for {repo_name!r}.") + sys.exit(2) + print_info(f"Initiative closed: {repo_name} → Tier {closed.target_tier} (reason: {closed.closed_reason}, closed_at: {closed.closed_at})") diff --git a/src/app/portfolio_analysis.py b/src/app/portfolio_analysis.py new file mode 100644 index 0000000..717661f --- /dev/null +++ b/src/app/portfolio_analysis.py @@ -0,0 +1,188 @@ +"""Standalone portfolio-analysis reporting flows.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from src.cli_output import print_info, print_warning +from src.portfolio_truth_types import truth_latest_path + + +def _run_tier_gaps_export_mode(args) -> None: + """Dump per-repo tier-gap data as JSON or markdown (Arc G S12.4).""" + from datetime import datetime, timezone + from pathlib import Path + + from src.maturity_tiers import compute_tier, tier_gap, tier_name + + output_dir = Path(args.output_dir) + truth_path = truth_latest_path(output_dir) + if not truth_path.exists(): + print_warning( + "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." + ) + return + + try: + truth = json.loads(truth_path.read_text()) + except (OSError, json.JSONDecodeError) as exc: + print_warning(f"Failed to read portfolio-truth: {exc}") + sys.exit(2) + + projects = truth.get("projects", []) + target_override = getattr(args, "tier_gaps_target", None) + if target_override is not None and target_override not in (2, 3, 4): + print_warning(f"Invalid --tier-gaps-target {target_override}; must be 2, 3, or 4.") + sys.exit(2) + + gaps: list[dict] = [] + for project in projects: + name = (project.get("identity") or {}).get("display_name") or "" + if not name: + continue + current = compute_tier(project) + if current == 0 or current == 4: + continue # no-git or already-Platinum: no next tier + target = target_override if target_override is not None else (current + 1) + if target <= current: + continue # operator's override is below or equal to current + gap = tier_gap(project, target) + gaps.append( + { + "repo_name": name, + "current_tier": current, + "current_tier_name": tier_name(current), + "target_tier": target, + "target_tier_name": tier_name(target), + "missing_requirements": list(gap.missing_requirements), + "requirement_sources": list(gap.requirement_sources), + } + ) + + fmt = getattr(args, "format", "json") + if fmt == "markdown": + _print_tier_gaps_markdown(gaps) + else: + envelope = { + "version": 1, + "generated_at": datetime.now(timezone.utc).isoformat(), + "gaps": gaps, + } + print(json.dumps(envelope, indent=2)) + +def _print_tier_gaps_markdown(gaps: list[dict]) -> None: + """Human-readable tier-gap table (Arc G S12.4).""" + if not gaps: + print_info("No tier gaps to report (all repos either at Platinum or no git).") + return + print_info(f"Tier Gaps ({len(gaps)} repo(s))") + print() + print("| REPO | CURRENT → TARGET | MISSING | SOURCE |") + print("|------|------------------|---------|--------|") + for g in gaps: + missing = ", ".join(g["missing_requirements"]) if g["missing_requirements"] else "—" + sources = ", ".join(g["requirement_sources"]) if g["requirement_sources"] else "—" + print( + f"| {g['repo_name']} | {g['current_tier_name']} → {g['target_tier_name']} | {missing} | {sources} |" + ) + +def _run_tier_recalibration_report_mode(args) -> None: + """Generate tier distribution report and flag bunching (Arc H A4).""" + from datetime import date, datetime, timezone + + from src.tier_recalibration import tier_distribution_report + + output_dir = Path(args.output_dir) + truth_path = truth_latest_path(output_dir) + if not truth_path.exists(): + print_warning( + "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." + ) + return + + try: + truth = json.loads(truth_path.read_text()) + except (OSError, json.JSONDecodeError) as exc: + print_warning(f"Failed to read portfolio-truth: {exc}") + sys.exit(2) + + projects = truth.get("projects", []) + report = tier_distribution_report(projects) + out_path = output_dir / f"tier-recalibration-{date.today()}.json" + envelope = { + "version": 1, + "generated_at": datetime.now(timezone.utc).isoformat(), + **report, + } + out_path.write_text(json.dumps(envelope, indent=2)) + print_info(f"Tier recalibration report written to {out_path}") + if report["bunching_detected"]: + print_warning( + "Bunching detected: at least one tier holds >60% of repos. " + "Consider adjusting tier thresholds." + ) + else: + print_info("No bunching detected — tier distribution looks healthy.") + +def _run_context_triage_mode(args) -> None: + """Run context quality triage across the portfolio (Arc H B1).""" + from datetime import date, datetime, timezone + + from src.catalog_validator import validate_catalog + from src.portfolio_context_triage import run_triage + + output_dir = Path(args.output_dir) + truth_path = truth_latest_path(output_dir) + if not truth_path.exists(): + print_warning( + "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." + ) + return + + try: + truth = json.loads(truth_path.read_text()) + except (OSError, json.JSONDecodeError) as exc: + print_warning(f"Failed to read portfolio-truth: {exc}") + sys.exit(2) + + projects = truth.get("projects", []) + catalog_path = ( + Path(args.catalog) + if getattr(args, "catalog", None) + else Path("config/portfolio-catalog.yaml") + ) + repo_keys: list[str] = [] + for project in projects: + identity = project.get("identity") or {} + project_key = identity.get("project_key") or "" + name = identity.get("display_name") or project.get("name", "") + repo_keys.extend(key for key in (project_key, name) if key) + catalog_scores = ( + validate_catalog(catalog_path, sorted(set(repo_keys))) if catalog_path.exists() else {} + ) + + enriched: list[dict] = [] + for project in projects: + identity = project.get("identity") or {} + name = identity.get("display_name") or project.get("name", "") + project_key = identity.get("project_key") or name + row = dict(project) + row["catalog_completeness"] = max( + catalog_scores.get(project_key, 0.0), + catalog_scores.get(name, 0.0), + ) + enriched.append(row) + + entries = run_triage(enriched) + out = [e.to_dict() for e in entries] + out_path = output_dir / f"context-triage-{date.today()}.json" + envelope = { + "version": 1, + "generated_at": datetime.now(timezone.utc).isoformat(), + "total_flagged": len(out), + "triage": out, + } + out_path.write_text(json.dumps(envelope, indent=2)) + print_info(f"Context triage written to {out_path} — {len(out)} repos flagged") diff --git a/src/app/portfolio_truth.py b/src/app/portfolio_truth.py new file mode 100644 index 0000000..9b70f95 --- /dev/null +++ b/src/app/portfolio_truth.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.cache import ResponseCache +from src.cli_output import print_info +from src.portfolio_context_recovery import ( + apply_context_recovery_plan, + build_context_recovery_plan, + write_context_recovery_plan_artifacts, +) +from src.portfolio_truth_publish import PortfolioTruthPublishError, publish_portfolio_truth +from src.portfolio_truth_reconcile import build_portfolio_truth_snapshot +from src.portfolio_truth_status import ( + load_live_repo_status_by_name, + load_release_count_by_name, + load_repo_status_from_audit_by_name, + load_security_alerts_by_name, + warn_if_warehouse_report_stale, +) + + +def run_portfolio_truth_mode(args: Any) -> None: + output_dir = Path(args.output_dir) + workspace_root = Path(args.workspace_root) + registry_output = ( + Path(args.registry_output) + if args.registry_output + else workspace_root / "project-registry.md" + ) + portfolio_report_output = ( + Path(args.portfolio_report_output) + if args.portfolio_report_output + else workspace_root / "PORTFOLIO-AUDIT-REPORT.md" + ) + legacy_registry_path = Path(args.registry) if args.registry else registry_output + release_count_by_name: dict[str, int] | None = None + if getattr(args, "portfolio_truth_include_release_count", False): + release_count_by_name = load_release_count_by_name( + output_dir=output_dir, + username=args.username, + ) + security_alerts_by_name: dict[str, dict] | None = None + if getattr(args, "portfolio_truth_include_security", False): + security_alerts_by_name = load_security_alerts_by_name( + output_dir=output_dir, + username=args.username, + ) + repo_status_by_name = load_live_repo_status_by_name( + username=args.username, + token=getattr(args, "token", None), + cache=None if getattr(args, "no_cache", False) else ResponseCache(), + ) + if repo_status_by_name is None: + repo_status_by_name = load_repo_status_from_audit_by_name( + output_dir=output_dir, + username=args.username, + ) + try: + result = publish_portfolio_truth( + workspace_root=workspace_root, + output_dir=output_dir, + registry_output=registry_output, + portfolio_report_output=portfolio_report_output, + catalog_path=Path(args.catalog) if args.catalog else None, + legacy_registry_path=legacy_registry_path, + include_notion=True, + allow_empty_notion=getattr(args, "portfolio_truth_allow_empty_notion", False), + release_count_by_name=release_count_by_name, + security_alerts_by_name=security_alerts_by_name, + repo_status_by_name=repo_status_by_name, + ) + except PortfolioTruthPublishError as exc: + raise SystemExit(str(exc)) from exc + print_info(f"Portfolio truth snapshot: {result.latest_path}") + print_info(f"Portfolio truth history snapshot: {result.snapshot_path}") + print_info(f"Project registry compatibility output: {result.registry_output}") + print_info(f"Portfolio audit compatibility output: {result.portfolio_report_output}") + print_info( + f"Portfolio truth generated for {result.project_count} projects " + f"(registry {'updated' if result.registry_changed else 'unchanged'}, " + f"report {'updated' if result.report_changed else 'unchanged'})" + ) + warn_if_warehouse_report_stale(output_dir, args.username) + + +def run_portfolio_context_recovery_mode(args: Any) -> None: + output_dir = Path(args.output_dir) + workspace_root = Path(args.workspace_root) + registry_output = ( + Path(args.registry_output) + if args.registry_output + else workspace_root / "project-registry.md" + ) + portfolio_report_output = ( + Path(args.portfolio_report_output) + if args.portfolio_report_output + else workspace_root / "PORTFOLIO-AUDIT-REPORT.md" + ) + legacy_registry_path = Path(args.registry) if args.registry else registry_output + catalog_path = Path(args.catalog) if args.catalog else None + build_result = build_portfolio_truth_snapshot( + workspace_root=workspace_root, + catalog_path=catalog_path, + legacy_registry_path=legacy_registry_path, + include_notion=True, + ) + plan = build_context_recovery_plan( + build_result.snapshot, + workspace_root=workspace_root, + allow_dirty=bool(getattr(args, "allow_dirty_worktree", False)), + ) + plan_json, plan_markdown = write_context_recovery_plan_artifacts(plan, output_dir=output_dir) + print_info(f"Context recovery plan JSON: {plan_json}") + print_info(f"Context recovery plan Markdown: {plan_markdown}") + eligible_count = sum(project.status == "eligible" for project in plan.projects) + skipped_count = sum(project.status == "skipped" for project in plan.projects) + excluded_count = sum(project.status == "excluded" for project in plan.projects) + print_info( + f"Frozen context-recovery cohort: {plan.target_project_count} targets " + f"({eligible_count} eligible, {skipped_count} skipped, {excluded_count} excluded)" + ) + if not args.apply_context_recovery: + return + apply_result = apply_context_recovery_plan( + build_result.snapshot, + plan, + workspace_root=workspace_root, + catalog_path=catalog_path, + limit=args.context_recovery_limit, + ) + if apply_result.failed_projects: + raise SystemExit("Context recovery failed for: " + ", ".join(apply_result.failed_projects)) + truth_result = publish_portfolio_truth( + workspace_root=workspace_root, + output_dir=output_dir, + registry_output=registry_output, + portfolio_report_output=portfolio_report_output, + catalog_path=catalog_path, + legacy_registry_path=legacy_registry_path, + include_notion=True, + ) + print_info( + f"Applied context recovery to {len(apply_result.updated_projects)} projects " + f"(skipped/excluded {len(apply_result.skipped_projects)})." + ) + print_info(f"Portfolio truth snapshot: {truth_result.latest_path}") + print_info(f"Project registry compatibility output: {truth_result.registry_output}") + print_info(f"Portfolio audit compatibility output: {truth_result.portfolio_report_output}") diff --git a/src/app/report_only.py b/src/app/report_only.py new file mode 100644 index 0000000..5a4b49c --- /dev/null +++ b/src/app/report_only.py @@ -0,0 +1,20 @@ +"""Standalone report-only application flows.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.cli_output import print_info +from src.repo_improver import generate_manifest, write_manifest +from src.report_state import load_latest_report + + +def run_generate_manifest_mode(args: Any, parser: Any) -> None: + output_dir = Path(args.output_dir) + _report_path, report_data = load_latest_report(output_dir) + if not report_data: + parser.error("No existing audit report found in output directory") + manifest = generate_manifest(report_data) + manifest_path = write_manifest(manifest, output_dir) + print_info(f"Improvement manifest: {manifest_path} ({len(manifest)} repos)") diff --git a/src/app/run_audit.py b/src/app/run_audit.py new file mode 100644 index 0000000..e8505b0 --- /dev/null +++ b/src/app/run_audit.py @@ -0,0 +1,1718 @@ +"""Audit execution application flow. + +Conditional imports inside this module preserve optional-feature behavior. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from collections import Counter +from concurrent.futures import ThreadPoolExecutor, as_completed +from datetime import datetime, timezone +from pathlib import Path +from time import perf_counter +from src.analyzers import run_all_analyzers +from src.baseline_context import ( + build_baseline_context_from_args, + build_watch_state, + compare_baseline_context, + extract_baseline_context, + format_mismatch_value, + normalize_scoring_profile, +) +from src.cache import ResponseCache +from src.cli_output import create_progress, print_info, print_status, print_warning +from src.cloner import clone_workspace +from src.control_center_presentation import ( + _normal_audit_next_step_hint, +) +from src.github_client import GitHubClient +from src.models import AuditReport, RepoAudit, RepoMetadata +from src.recurring_review import FULL_REFRESH_DAYS +from src.report_enrichment import build_run_change_counts, build_run_change_summary +from src.report_state import ( + audit_from_dict as _audit_from_dict, + load_latest_report as _load_latest_report, + report_from_dict as _report_from_dict, +) +from src.report_operating_paths import apply_operating_paths as _apply_operating_paths +from src.report_portfolio_catalog import apply_portfolio_catalog as _apply_portfolio_catalog +from src.report_scorecards import apply_scorecards as _apply_scorecards +from src.report_operator_state import enrich_report_with_operator_state as _enrich_report_with_operator_state +from src.reporter import ( + write_json_report, + write_markdown_report, + write_pcc_export, + write_raw_metadata, +) +from src.scorer import score_repo +from src.terminology import ACTION_SYNC_CANONICAL_LABELS +DEFAULT_ANALYSIS_WORKERS = 1 +MAX_ANALYSIS_WORKERS = 8 +DEFAULT_PORTFOLIO_WORKSPACE = Path.home() / "Projects" +CLI_MODE_GUIDE = """GitHub portfolio operating system with four product modes: + First Run setup, baseline creation, first workbook, first control-center read + Weekly Review normal workbook-first operator loop + Deep Dive repo-level drilldown and investigation + Action Sync campaign, writeback, GitHub Projects, and Notion mirroring + +Recommended defaults: + - Start with --doctor before the first real run + - Prefer --excel-mode standard for the stable workbook path + - Use --control-center for read-only daily triage + - Treat campaigns, writeback, catalog overrides, scorecards overrides, and GitHub Projects as advanced workflows""" +CLI_MODE_EXAMPLES = """Subcommands: run, triage, report, serve + Run `audit run --help`, `audit triage --help`, or `audit report --help` for flags. + +Subcommand form (preferred): + audit run --html + audit run --repos + audit triage --control-center + audit triage --approval-center + audit report --portfolio-truth + audit report --campaign security-review --writeback-target github + audit security-gate --output-dir output + audit serve [--port 8080] + +Legacy flat form (deprecated, still supported): + audit --doctor + audit --html + audit --control-center + audit --campaign security-review --writeback-target all --github-projects""" +def _date_str(dt: datetime) -> str: + return dt.strftime("%Y-%m-%d") + +def _filter_repos( + repos: list[RepoMetadata], + *, + skip_forks: bool = False, + skip_archived: bool = False, +) -> list[RepoMetadata]: + """Apply exclusion filters to the repo list.""" + filtered = repos + if skip_forks: + filtered = [r for r in filtered if not r.fork] + if skip_archived: + filtered = [r for r in filtered if not r.archived] + return filtered + +def _write_json( + username: str, + repos: list[RepoMetadata], + errors: list[dict], + total_fetched: int, + output_dir: Path, + audits: list[RepoAudit] | None = None, +) -> Path: + """Write audit results JSON and return the file path.""" + output_dir.mkdir(parents=True, exist_ok=True) + output_path = output_dir / "raw_metadata.json" + + if audits: + # Compute tier distribution + tier_dist: dict[str, int] = {} + for a in audits: + tier_dist[a.completeness_tier] = tier_dist.get(a.completeness_tier, 0) + 1 + avg_score = sum(a.overall_score for a in audits) / len(audits) if audits else 0.0 + + report = { + "username": username, + "generated_at": datetime.now(timezone.utc).isoformat(), + "total_repos": total_fetched, + "repos_audited": len(audits), + "average_score": round(avg_score, 3), + "tier_distribution": tier_dist, + "audits": [a.to_dict() for a in audits], + "errors": errors, + } + else: + report = { + "username": username, + "generated_at": datetime.now(timezone.utc).isoformat(), + "total_repos": total_fetched, + "repos_included": len(repos), + "repos": [r.to_dict() for r in repos], + "errors": errors, + } + + with open(output_path, "w") as f: + json.dump(report, f, indent=2) + + return output_path + +def _print_verbose(audit: RepoAudit) -> None: + """Print per-dimension score breakdown for a repo.""" + print(f"\n {'─' * 50}", file=sys.stderr) + print( + f" {audit.metadata.name} " + f"score={audit.overall_score:.2f} " + f"tier={audit.completeness_tier}" + f"{' flags=' + ','.join(audit.flags) if audit.flags else ''}", + file=sys.stderr, + ) + for r in audit.analyzer_results: + bar = "█" * int(r.score * 10) + "░" * (10 - int(r.score * 10)) + print( + f" {r.dimension:<17} {bar} {r.score:.2f}", + file=sys.stderr, + ) + for finding in r.findings[:3]: + print(f" · {finding}", file=sys.stderr) + +def _resolve_repo_names(repos_arg: list[str]) -> list[str]: + """Extract repo names from URLs or bare names.""" + names = [] + seen: set[str] = set() + for r in repos_arg: + r = r.strip().rstrip("/") + if "/" in r: + # URL like https://github.com/user/RepoName + name = r.split("/")[-1] + else: + name = r + if name and name not in seen: + names.append(name) + seen.add(name) + return names + +def _normalize_profile_name(profile_name: str | None) -> str: + return normalize_scoring_profile(profile_name) + +def _run_main_audit_cycle(args, config_inspection) -> None: + from src.diagnostics import format_preflight_summary, run_diagnostics, should_block_run + + if args.preflight_mode != "off": + preflight = run_diagnostics(args, config_inspection=config_inspection, full=False) + setattr(args, "_preflight_summary", preflight.to_preflight_summary()) + print_info(format_preflight_summary(preflight)) + if preflight.status != "ok": + for check in [item for item in preflight.checks if item.status != "ok"][:5]: + print_warning(f"{check.summary} ({check.category})") + if should_block_run(preflight, args.preflight_mode): + raise SystemExit(1) + + custom_weights, scoring_profile_name = _load_scoring_profile(args.scoring_profile) + + if not args.token: + print_warning( + "No token provided. Only public repos will be fetched.\n" + " Set GITHUB_TOKEN or pass --token for private repo access." + ) + + cache = None if args.no_cache else ResponseCache() + client = GitHubClient(token=args.token, cache=cache) + output_dir = Path(args.output_dir) + + all_repos, errors = _fetch_repo_metadata(args, client) + total_fetched = len(all_repos) + repos = _filter_repos( + all_repos, + skip_forks=args.skip_forks, + skip_archived=args.skip_archived, + ) + _print_filter_summary(all_repos, repos, args) + + if getattr(args, "dry_run", False): + _print_dry_run_summary(repos) + return + + if args.repos: + _run_targeted_audit( + args, + client, + output_dir, + all_repos=all_repos, + errors=errors, + custom_weights=custom_weights, + scoring_profile_name=scoring_profile_name, + watch_plan=getattr(args, "_watch_plan", None), + latest_trusted_baseline=getattr(args, "_latest_trusted_watch_baseline", None), + ) + return + + if args.incremental: + _run_incremental_audit( + args, + client, + output_dir, + all_repos=all_repos, + errors=errors, + custom_weights=custom_weights, + scoring_profile_name=scoring_profile_name, + watch_plan=getattr(args, "_watch_plan", None), + latest_trusted_baseline=getattr(args, "_latest_trusted_watch_baseline", None), + ) + return + + resumed_names: set[str] = set() + resumed_audits: list[RepoAudit] = [] + if getattr(args, "resume", False): + from src.progress import load_progress + + saved = load_progress(output_dir) + if saved: + completed_dicts, _run_meta = saved + for audit_dict in completed_dicts: + try: + resumed_audits.append(_audit_from_dict(audit_dict)) + resumed_names.add(audit_dict.get("metadata", {}).get("name", "")) + except Exception: + # Skip corrupt resume entries and continue with the rest. + pass + if resumed_audits: + print_info(f"Resumed {len(resumed_audits)} previously completed repo(s)") + repos = [r for r in repos if r.name not in resumed_names] + + runtime_stats: dict[str, float] = {} + audits = _analyze_repos( + repos, + args=args, + client=client, + portfolio_lang_freq=_portfolio_lang_freq_for_filtered_baseline(repos), + custom_weights=custom_weights, + runtime_stats=runtime_stats, + ) + all_audits = resumed_audits + audits + + if all_audits: + audits = all_audits + baseline_context = build_baseline_context_from_args( + args, + scoring_profile=scoring_profile_name, + portfolio_baseline_size=len(repos), + ) + report = AuditReport.from_audits( + args.username, + audits, + errors, + total_fetched, + scoring_profile=scoring_profile_name, + run_mode="full", + portfolio_baseline_size=len(repos), + baseline_signature=baseline_context["baseline_signature"], + baseline_context=baseline_context, + ) + report.watch_state = build_watch_state( + args, + scoring_profile=scoring_profile_name, + portfolio_baseline_size=len(repos), + run_mode="full", + watch_plan=getattr(args, "_watch_plan", None), + latest_trusted_baseline=getattr(args, "_latest_trusted_watch_baseline", None), + full_refresh_interval_days=FULL_REFRESH_DAYS, + ) + report.preflight_summary = getattr(args, "_preflight_summary", {}) + report.runtime_breakdown = runtime_stats + _apply_requested_reconciliation(report, args, audits) + outputs = _write_report_outputs(report, args, output_dir, client=client, cache=cache) + _print_output_summary( + f"Audited {report.repos_audited} repos for {report.username}", report, outputs + ) + + if getattr(args, "create_issues", False): + from src.issue_creator import create_audit_issues + from src.quick_wins import find_quick_wins + + quick_wins = find_quick_wins(audits) + issue_result = create_audit_issues( + quick_wins, + args.username, + client, + dry_run=getattr(args, "dry_run", False), + ) + print_info( + f"Issues: {len(issue_result['created'])} created, " + f"{len(issue_result['skipped'])} skipped (already exist)" + ) + + if getattr(args, "summary", False) and outputs.get("json_path"): + from src.diff import diff_reports, print_diff_summary + from src.history import find_previous + + prev_path = find_previous(outputs["json_path"].name) + if prev_path: + diff = diff_reports( + prev_path, + outputs["json_path"], + portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ) + print_diff_summary(diff) + + return + + raw_path = _write_json( + args.username, + repos, + errors, + total_fetched, + output_dir, + ) + print( + f"\n✓ Fetched {total_fetched} repos for {args.username}\n" + f" Included: {len(repos)} | Errors: {len(errors)}\n" + f" Output: {raw_path}", + ) + +def _run_watch_mode(args, config_inspection) -> None: + from src.recurring_review import choose_watch_plan + from src.watch import run_watch_loop + + def _run_watch_once() -> None: + watch_plan = choose_watch_plan( + Path(args.output_dir), + args, + scoring_profile=normalize_scoring_profile(args.scoring_profile), + ) + print_info(f"Watch decision: {watch_plan.mode} ({watch_plan.reason})") + original_incremental = args.incremental + original_repos = args.repos + setattr(args, "_watch_plan", watch_plan) + setattr(args, "_latest_trusted_watch_baseline", watch_plan.latest_trusted_baseline) + try: + args.incremental = watch_plan.mode == "incremental" + args.repos = None + _run_main_audit_cycle(args, config_inspection) + finally: + args.incremental = original_incremental + args.repos = original_repos + + run_watch_loop(_run_watch_once, interval=args.watch_interval) + +def _fetch_repo_metadata(args, client: GitHubClient) -> tuple[list[RepoMetadata], list[dict]]: + if args.graphql and args.token: + from src.graphql_client import bulk_fetch_repos + + print_info("Using GraphQL bulk fetch...") + raw_repos = bulk_fetch_repos(args.username, args.token) + all_repos: list[RepoMetadata] = [] + errors: list[dict] = [] + for repo_data in raw_repos: + try: + langs = repo_data.pop("_languages", {}) + repo_data.pop("_releases", None) + meta = RepoMetadata.from_api_response(repo_data, languages=langs) + all_repos.append(meta) + except Exception as exc: + errors.append({"repo": repo_data.get("full_name", "?"), "error": str(exc)}) + print_info(f"GraphQL: {len(all_repos)} repos fetched") + return all_repos, errors + + return client.get_repo_metadata(args.username) + +def _print_filter_summary(all_repos: list[RepoMetadata], repos: list[RepoMetadata], args) -> None: + forks_excluded = sum(1 for r in all_repos if r.fork) if args.skip_forks else 0 + archived_excluded = sum(1 for r in all_repos if r.archived) if args.skip_archived else 0 + skipped = len(all_repos) - len(repos) + if skipped: + parts = [] + if forks_excluded: + parts.append(f"{forks_excluded} forks") + if archived_excluded: + parts.append(f"{archived_excluded} archived") + print_info(f"Filtered out {skipped} repos ({', '.join(parts) or 'forks/archived'})") + +def _compute_portfolio_lang_freq(repos: list[RepoMetadata]) -> dict[str, float]: + lang_counts = Counter(repo.language for repo in repos if repo.language) + return {lang: count / len(repos) for lang, count in lang_counts.items()} if repos else {} + +def _portfolio_lang_freq_for_filtered_baseline(repos: list[RepoMetadata]) -> dict[str, float]: + """Compute novelty baseline from the full filtered portfolio, never only the rerun subset.""" + return _compute_portfolio_lang_freq(repos) + +def _analysis_worker_count(args) -> int: + """Return the bounded repo-analysis worker count for this run.""" + raw_value = getattr(args, "analysis_workers", None) + if raw_value is None: + raw_value = os.environ.get("GITHUB_REPO_AUDITOR_ANALYSIS_WORKERS") + + if raw_value in {None, ""}: + return DEFAULT_ANALYSIS_WORKERS + + try: + requested = int(raw_value) + except (TypeError, ValueError): + print_warning("Invalid analysis worker count; using the reliable single-worker default.") + return DEFAULT_ANALYSIS_WORKERS + + if requested < 1: + print_warning( + "Analysis worker count must be at least 1; using the reliable single-worker default." + ) + return DEFAULT_ANALYSIS_WORKERS + + if requested > MAX_ANALYSIS_WORKERS: + print_warning( + f"Analysis worker count capped at {MAX_ANALYSIS_WORKERS} to avoid GitHub API stalls." + ) + return MAX_ANALYSIS_WORKERS + + return requested + +def _use_analysis_progress(workers: int) -> bool: + """Use rich progress only when it can render visibly for the operator.""" + return workers > 1 and sys.stderr.isatty() + +def _use_analyzer_cache(args, workers: int) -> bool: + """Use the SQLite analyzer cache only for single-worker analysis.""" + return not getattr(args, "no_analyzer_cache", False) and workers == 1 + +def _select_target_repos( + target_names: list[str], repos: list[RepoMetadata] +) -> tuple[list[RepoMetadata], list[str]]: + exact = {repo.name: repo for repo in repos} + lower = {repo.name.lower(): repo for repo in repos} + selected: list[RepoMetadata] = [] + missing: list[str] = [] + + for name in target_names: + repo = exact.get(name) or lower.get(name.lower()) + if repo: + selected.append(repo) + else: + missing.append(name) + + return selected, missing + +def _analyze_repos( + repos: list[RepoMetadata], + *, + args, + client: GitHubClient, + portfolio_lang_freq: dict[str, float], + custom_weights: dict[str, float] | None, + runtime_stats: dict | None = None, +) -> list[RepoAudit]: + from src.analyzers import load_custom_analyzers + + if args.skip_clone: + print_warning("Audit modes that score repos do not support --skip-clone.") + return [] + + extra_analyzers = [] + if getattr(args, "analyzers_dir", None): + extra_analyzers = load_custom_analyzers(Path(args.analyzers_dir)) + if extra_analyzers: + print_info( + f"Loaded {len(extra_analyzers)} custom analyzer(s) from {args.analyzers_dir}" + ) + + audits: list[RepoAudit] = [] + requested_workers = _analysis_worker_count(args) + + # Open a warehouse connection for the analyzer result cache unless disabled. + _warehouse_conn = None + if not _use_analyzer_cache(args, requested_workers): + if requested_workers > 1 and not getattr(args, "no_analyzer_cache", False): + print_warning( + "Analyzer result cache disabled for parallel analysis; " + "rerun with one analysis worker to use the SQLite cache." + ) + else: + import sqlite3 as _sqlite3 + + from src.warehouse import WAREHOUSE_FILENAME + from src.warehouse import _ensure_schema as _warehouse_ensure_schema + + _output_dir = Path(getattr(args, "output_dir", "output")) + _db_path = _output_dir / WAREHOUSE_FILENAME + try: + _output_dir.mkdir(parents=True, exist_ok=True) + _warehouse_conn = _sqlite3.connect(str(_db_path)) + _warehouse_ensure_schema(_warehouse_conn) + except Exception as _cache_err: + print_warning(f"Could not open warehouse for analyzer cache: {_cache_err}") + _warehouse_conn = None + + def _analyze_one(repo_meta: RepoMetadata, repo_path: Path) -> RepoAudit: + worker_client = GitHubClient(token=client.token, cache=client.cache) + _commit_sha = repo_meta.pushed_at.isoformat() if repo_meta.pushed_at else "" + results = run_all_analyzers( + repo_path, + repo_meta, + worker_client, + extra_analyzers=extra_analyzers, + conn=_warehouse_conn, + commit_sha=_commit_sha, + sbom_source=getattr(args, "sbom_source", "lockfile"), + ) + return score_repo( + repo_meta, + results, + repo_path=repo_path, + portfolio_lang_freq=portfolio_lang_freq, + custom_weights=custom_weights, + github_client=worker_client, + scorecard_enabled=args.scorecard, + security_offline=args.security_offline, + ) + + # ── Optional async enrichment prefetch ─────────────────────────────────── + _fetch_mode: str = getattr(args, "fetch_mode", "sync") + if _fetch_mode == "async" and repos: + from src.github_client_async import fetch_enrichment_sync as _async_prefetch + + _fetch_workers: int = max(1, getattr(args, "fetch_workers", 10)) + print_info( + f"Pre-fetching enrichment for {len(repos)} repos " + f"(async, concurrency={_fetch_workers})..." + ) + _prefetch_start = perf_counter() + try: + _repo_pairs = [(r.full_name.split("/")[0], r.name) for r in repos if "/" in r.full_name] + _async_prefetch( + _repo_pairs, + token=client.token, + max_concurrency=_fetch_workers, + cache=client.cache, + ) + _prefetch_elapsed = perf_counter() - _prefetch_start + print_info(f"Async enrichment prefetch complete in {_prefetch_elapsed:.1f}s.") + if runtime_stats is not None: + runtime_stats["async_prefetch_seconds"] = round(_prefetch_elapsed, 3) + except Exception as _prefetch_err: + print_warning( + f"Async enrichment prefetch failed ({_prefetch_err!r}); " + "falling back to per-repo sync fetch." + ) + + _reconcile_diverged: bool = False + clone_start = perf_counter() + with clone_workspace( + repos, + token=args.token, + on_progress=lambda i, t, n: None, + on_error=lambda n, m: print_warning(f"Failed to clone {n}"), + ) as cloned: + clone_seconds = perf_counter() - clone_start + if runtime_stats is not None: + runtime_stats["clone_fetch_seconds"] = round(clone_seconds, 3) + print_info(f"Cloned {len(cloned)}/{len(repos)} repos. Analyzing...") + analyzable = [ + (index, repo_meta, cloned.get(repo_meta.name)) for index, repo_meta in enumerate(repos) + ] + analyzable = [ + (index, repo_meta, repo_path) for index, repo_meta, repo_path in analyzable if repo_path + ] + workers = min(requested_workers, max(1, len(analyzable))) + if workers == 1: + print_info("Analyzing with 1 worker for reliable full-audit progress.") + else: + print_info(f"Analyzing with {workers} workers.") + progress = create_progress() if _use_analysis_progress(workers) else None + analyze_start = perf_counter() + if progress: + with progress: + task = progress.add_task("Analyzing", total=len(repos)) + completed: dict[int, RepoAudit] = {} + skipped = len(repos) - len(analyzable) + for _ in range(skipped): + progress.advance(task) + if workers == 1: + for index, repo_meta, repo_path in analyzable: + progress.update(task, description=f"Analyzing {repo_meta.name}") + completed[index] = _analyze_one(repo_meta, repo_path) + if args.verbose: + _print_verbose(completed[index]) + progress.advance(task) + else: + with ThreadPoolExecutor(max_workers=workers) as executor: + futures = { + executor.submit(_analyze_one, repo_meta, repo_path): ( + index, + repo_meta.name, + ) + for index, repo_meta, repo_path in analyzable + } + for future in as_completed(futures): + index, repo_name = futures[future] + progress.update(task, description=f"Analyzing {repo_name}") + completed[index] = future.result() + if args.verbose: + _print_verbose(completed[index]) + progress.advance(task) + audits.extend(completed[index] for index in sorted(completed)) + else: + completed: dict[int, RepoAudit] = {} + if workers == 1: + for index, repo_meta, repo_path in analyzable: + print( + f" [{index + 1}/{len(repos)}] Analyzing {repo_meta.name}...", + file=sys.stderr, + ) + completed[index] = _analyze_one(repo_meta, repo_path) + if args.verbose: + _print_verbose(completed[index]) + else: + with ThreadPoolExecutor(max_workers=workers) as executor: + futures = { + executor.submit(_analyze_one, repo_meta, repo_path): (index, repo_meta.name) + for index, repo_meta, repo_path in analyzable + } + finished = 0 + for future in as_completed(futures): + index, repo_name = futures[future] + finished += 1 + print( + f" [{finished}/{len(analyzable)}] Analyzing {repo_name}...", + file=sys.stderr, + ) + completed[index] = future.result() + if args.verbose: + _print_verbose(completed[index]) + audits.extend(completed[index] for index in sorted(completed)) + if runtime_stats is not None: + runtime_stats["analyzer_seconds"] = round(perf_counter() - analyze_start, 3) + + # ── Cache reconcile gate ────────────────────────────────────────────── + _do_reconcile: bool = getattr(args, "reconcile_cache", False) + if _do_reconcile and _warehouse_conn is not None and audits: + from src.analyzer_cache import reconcile as _cache_reconcile + from src.analyzers import run_all_analyzers as _run_all + + _repo_path_map: dict[str, object] = { + repo_meta.name: cloned.get(repo_meta.name) for repo_meta in repos + } + _repo_meta_map: dict[str, object] = {repo_meta.name: repo_meta for repo_meta in repos} + _sha_map: dict[str, str] = { + repo_meta.name: (repo_meta.pushed_at.isoformat() if repo_meta.pushed_at else "") + for repo_meta in repos + } + + def _fresh_run(repo_path, meta, conn=None): + return _run_all( + repo_path, + meta, + conn=None, + commit_sha="", + sbom_source=getattr(args, "sbom_source", "lockfile"), + ) + + _reconcile_report = _cache_reconcile( + _repo_path_map, + _repo_meta_map, + _warehouse_conn, + _fresh_run, + commit_sha_map=_sha_map, + ) + _checked = _reconcile_report["checked"] + _matched = _reconcile_report["matched"] + _divergent = _reconcile_report["divergent"] + print_info( + f"Cache reconcile: {_matched}/{_checked} matched, {len(_divergent)} divergent" + ) + if _divergent: + _reconcile_diverged = True + for _entry in _divergent: + print_warning( + f" DIVERGE {_entry['repo']} {_entry['analyzer']}: {_entry['diff_summary']}" + ) + _output_dir_r = Path(getattr(args, "output_dir", "output")) + _output_dir_r.mkdir(parents=True, exist_ok=True) + import datetime as _dt + import json as _json + + _stamp = _dt.date.today().isoformat() + _report_path = _output_dir_r / f"cache-reconcile-{args.username}-{_stamp}.json" + try: + _report_path.write_text( + _json.dumps(_reconcile_report, indent=2), encoding="utf-8" + ) + print_warning(f" Full divergence report: {_report_path}") + except Exception as _write_err: + print_warning(f"Could not write reconcile report: {_write_err}") + + print_info("Clones cleaned up") + if _warehouse_conn is not None: + try: + _warehouse_conn.close() + except Exception: + # Warehouse close failures are non-actionable during final cleanup. + pass + if _reconcile_diverged: + sys.exit(1) + return audits + +def _apply_requested_reconciliation(report: AuditReport, args, audits: list[RepoAudit]) -> None: + if args.registry: + from src.registry_parser import parse_registry, reconcile, sync_new_repos + + registry = parse_registry(args.registry) + report.reconciliation = reconcile(registry, audits) + print_info( + f"Registry: {report.reconciliation.registry_total} projects, " + f"{len(report.reconciliation.matched)} matched" + ) + if args.sync_registry and report.reconciliation.on_github_not_registry: + added = sync_new_repos( + args.registry, + report.reconciliation.on_github_not_registry, + audits, + ) + if added: + print_info( + f"Synced {len(added)} repos to registry: {', '.join(added[:5])}" + + (f"... (+{len(added) - 5})" if len(added) > 5 else "") + ) + return + + if args.notion_registry: + from src.notion_registry import load_notion_registry + from src.registry_parser import reconcile + + notion_projects = load_notion_registry(Path("config")) + if notion_projects: + report.reconciliation = reconcile(notion_projects, audits) + print_info( + f"Notion registry: {len(notion_projects)} projects, " + f"{len(report.reconciliation.matched)} matched" + ) + +def _apply_governance_view_filter(report: AuditReport, governance_view: str) -> None: + if not isinstance(report.governance_preview, dict): + report.governance_preview = {} + report.governance_preview["selected_view"] = governance_view + if governance_view == "all": + return + + preview_actions = ( + report.governance_preview.get("actions", []) + if isinstance(report.governance_preview, dict) + else [] + ) + result_rows = ( + report.governance_results.get("results", []) + if isinstance(report.governance_results, dict) + else [] + ) + drift_rows = report.governance_drift if isinstance(report.governance_drift, list) else [] + + if governance_view == "ready": + filtered_preview = [item for item in preview_actions if item.get("applyable")] + report.governance_preview = { + **report.governance_preview, + "actions": filtered_preview, + "applyable_count": len(filtered_preview), + "action_count": len(filtered_preview), + } + return + + if governance_view == "drifted": + report.governance_drift = drift_rows + report.governance_results = { + **report.governance_results, + "results": [item for item in result_rows if item.get("status") == "drifted"], + } + return + + if governance_view == "approved": + if not report.governance_approval: + report.governance_preview = {**report.governance_preview, "actions": []} + report.governance_results = {**report.governance_results, "results": []} + return + + if governance_view == "applied": + report.governance_results = { + **report.governance_results, + "results": [item for item in result_rows if item.get("status") == "applied"], + } + +def _apply_ops_writeback( + report: AuditReport, args, client: GitHubClient | None, output_dir: Path +) -> None: + if not args.campaign: + return + + github_projects_config = None + operator_context: dict[str, dict] = {} + if getattr(args, "github_projects", False): + from src.github_projects import load_github_projects_config, operator_context_by_repo + from src.operator_control_center import build_operator_snapshot, normalize_review_state + + github_projects_config = load_github_projects_config( + Path(args.github_projects_config) + if getattr(args, "github_projects_config", None) + else None + ) + normalized = normalize_review_state( + report.to_dict(), + output_dir=output_dir, + diff_data=None, + portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ) + operator_snapshot = build_operator_snapshot( + normalized, + output_dir=output_dir, + triage_view="all", + ) + operator_context = operator_context_by_repo(operator_snapshot.get("operator_queue", [])) + + from src.notion_sync import sync_campaign_actions + from src.ops_writeback import ( + apply_github_writeback, + build_action_runs, + build_campaign_bundle, + build_campaign_run, + build_rollback_preview, + build_writeback_preview, + summarize_writeback_results, + ) + from src.warehouse import load_campaign_history, load_latest_campaign_state + + previous_state = load_latest_campaign_state(output_dir, args.campaign) + campaign_summary, actions = build_campaign_bundle( + report.to_dict(), + campaign_type=args.campaign, + portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + max_actions=args.max_actions, + writeback_target=args.writeback_target, + ) + campaign_summary["sync_mode"] = args.campaign_sync_mode + report.campaign_summary = campaign_summary + report.writeback_preview = build_writeback_preview( + campaign_summary, + actions, + writeback_target=args.writeback_target, + apply=args.writeback_apply, + previous_state=previous_state, + sync_mode=args.campaign_sync_mode, + github_projects_config=github_projects_config, + operator_context=operator_context, + ) + + results: list[dict] = [] + external_refs: dict[str, dict] = {} + managed_state_drift: list[dict] = [] + if args.writeback_apply and args.writeback_target: + if args.writeback_target in {"github", "all"} and client is not None: + github_results, github_refs, github_drift, _github_closure_events = ( + apply_github_writeback( + client, + actions, + previous_state=previous_state, + sync_mode=args.campaign_sync_mode, + campaign_summary=campaign_summary, + github_projects_config=github_projects_config, + operator_context=operator_context, + ) + ) + results.extend(github_results) + external_refs.update(github_refs) + managed_state_drift.extend(github_drift) + if args.writeback_target in {"notion", "all"}: + notion_results, notion_refs, notion_drift = sync_campaign_actions( + actions, + campaign_summary, + config_dir=Path("config"), + apply=True, + previous_state=previous_state, + sync_mode=args.campaign_sync_mode, + ) + results.extend(notion_results) + external_refs.update(notion_refs) + managed_state_drift.extend(notion_drift) + + report.writeback_results = summarize_writeback_results( + results, + args.writeback_target, + args.writeback_apply, + ) + report.writeback_results["campaign_run"] = build_campaign_run( + campaign_summary, + actions, + writeback_target=args.writeback_target, + apply=args.writeback_apply, + sync_mode=args.campaign_sync_mode, + ) + report.action_runs = build_action_runs( + actions, + results, + args.writeback_target, + args.writeback_apply, + previous_state=previous_state, + sync_mode=args.campaign_sync_mode, + ) + report.external_refs = external_refs + report.managed_state_drift = managed_state_drift + report.rollback_preview = build_rollback_preview(results) + historical_entries = load_campaign_history(output_dir, args.campaign, limit=20) + report.campaign_history = report.action_runs + historical_entries[:20] + +def _write_report_outputs( + report: AuditReport, + args, + output_dir: Path, + *, + client: GitHubClient | None = None, + cache: ResponseCache | None = None, + json_path: Path | None = None, + write_json: bool = True, + archive: bool = True, + save_fingerprint_data: bool = True, + diff_source: Path | None = None, +) -> dict[str, object]: + from src.diff import diff_reports, format_diff_markdown + from src.excel_export import export_excel + from src.history import ( + archive_report, + find_previous, + load_repo_score_history, + load_trend_data, + save_fingerprints, + ) + from src.warehouse import write_warehouse_snapshot + + output_start = perf_counter() + _apply_ops_writeback(report, args, client, output_dir) + _apply_governance_view_filter(report, args.governance_view) + if write_json: + json_path = write_json_report(report, output_dir) + elif json_path is None: + raise ValueError("json_path is required when write_json is False") + + if diff_source is None and write_json: + diff_source = find_previous(json_path.name) + + diff_dict = None + if diff_source: + diff = diff_reports( + diff_source, + json_path, + portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ) + diff_dict = diff.to_dict() + diff_md_path = ( + output_dir / f"audit-diff-{report.username}-{_date_str(report.generated_at)}.md" + ) + diff_md_path.write_text(format_diff_markdown(diff)) + diff_json_path = ( + output_dir / f"audit-diff-{report.username}-{_date_str(report.generated_at)}.json" + ) + diff_json_path.write_text(json.dumps(diff_dict, indent=2)) + print_info( + f"Diff: {len(diff.tier_changes)} tier changes, " + f"{len([c for c in diff.score_changes if abs(c['delta']) > 0.05])} significant score changes" + ) + + report = _apply_portfolio_catalog(report, args) + report = _enrich_report_with_operator_state( + report, + output_dir=output_dir, + diff_dict=diff_dict, + triage_view=getattr(args, "triage_view", "all"), + portfolio_profile=args.portfolio_profile, + collection=args.collection, + ) + report = _apply_portfolio_catalog(report, args) + report = _apply_scorecards(report, args) + report = _apply_operating_paths(report) + report.run_change_summary = build_run_change_summary(diff_dict) + report.run_change_counts = build_run_change_counts(diff_dict) + report_data = report.to_dict() + if write_json: + json_path = write_json_report(report, output_dir) + + trend_data = load_trend_data() + score_history = load_repo_score_history() + workbook_start = perf_counter() + excel_path = export_excel( + json_path, + output_dir / f"audit-dashboard-{report.username}-{_date_str(report.generated_at)}.xlsx", + trend_data=trend_data, + diff_data=diff_dict, + score_history=score_history, + portfolio_profile=args.portfolio_profile, + collection=args.collection, + excel_mode=args.excel_mode, + truth_dir=output_dir, + ) + report.runtime_breakdown["workbook_build_seconds"] = round(perf_counter() - workbook_start, 3) + md_path = write_markdown_report(report, output_dir, diff_data=diff_dict) + pcc_path = write_pcc_export(report, output_dir) + raw_path = write_raw_metadata(report, output_dir) + warehouse_path = write_warehouse_snapshot(report, output_dir, json_path) + + # ── Semantic reindex (Arc F S3.1) ────────────────────────────────── + if getattr(args, "reindex", False) or getattr(args, "reindex_force", False): + _maybe_run_reindex(report, warehouse_path, args) + + if archive and write_json: + archive_report(json_path) + if save_fingerprint_data: + save_fingerprints(report_data["audits"], output_dir / ".audit-fingerprints.json") + report.runtime_breakdown["report_output_seconds"] = round(perf_counter() - output_start, 3) + + badge_info = "" + if args.badges: + from src.badge_export import _write_badges_markdown, export_badges, upload_badge_gist + + badge_result = export_badges(report_data, output_dir) + badge_info = ( + f"\n {badge_result['badges_md']} ({badge_result['files_written']} badge files)" + ) + if args.upload_badges: + gist_urls = upload_badge_gist(output_dir / "badges", report.username) + if gist_urls: + _write_badges_markdown(report_data, output_dir / "badges", gist_urls) + + notion_info = "" + if args.notion: + from src.notion_client import get_notion_token, load_notion_config + from src.notion_export import _load_project_map, export_notion_events + from src.notion_sync import ( + check_recommendation_followup, + create_audit_action_requests, + create_audit_history_entry, + create_recommendation_run, + patch_project_completeness_cards, + patch_weekly_review, + sync_notion_events, + ) + + notion_result = export_notion_events(report_data, output_dir) + notion_info = ( + f"\n {notion_result['events_path']} " + f"({notion_result['event_count']} events, {len(notion_result['unmapped'])} unmapped)" + ) + if args.notion_sync: + sync_notion_events(notion_result["events_path"], Path("config")) + sync_token = get_notion_token() + sync_config = load_notion_config(Path("config")) + if sync_token and sync_config: + from src.notion_dashboard import create_notion_dashboard + from src.quick_wins import find_quick_wins + + quick_wins = find_quick_wins(report.audits) + project_map = _load_project_map(Path("config")) + create_recommendation_run(report_data, quick_wins, sync_token, sync_config) + create_audit_action_requests( + report_data.get("audits", []), + project_map, + sync_token, + sync_config, + ) + patch_weekly_review(report_data, diff_dict, quick_wins, sync_token, sync_config) + create_audit_history_entry(report_data, sync_token, sync_config) + patch_project_completeness_cards( + report_data.get("audits", []), + project_map, + sync_token, + sync_config, + ) + check_recommendation_followup(report_data, sync_token, sync_config) + create_notion_dashboard(report_data, sync_token, sync_config) + + readme_info = "" + if args.portfolio_readme: + from src.portfolio_readme import export_portfolio_readme + + readme_result = export_portfolio_readme(report_data, output_dir) + readme_info = f"\n {readme_result['readme_path']}" + + suggestions_info = "" + if args.readme_suggestions: + from src.readme_suggestions import generate_readme_suggestions + + sug_result = generate_readme_suggestions(report_data, output_dir) + suggestions_info = f"\n {sug_result['suggestions_path']} ({sug_result['total_suggestions']} suggestions)" + + html_info = "" + if args.html: + from src.web_export import export_html_dashboard + + html_result = export_html_dashboard( + report_data, + output_dir, + trend_data, + score_history, + diff_data=diff_dict, + portfolio_profile=args.portfolio_profile, + collection=args.collection, + ) + html_info = f"\n {html_result['html_path']}" + + pdf_info = "" + if args.pdf: + from src.pdf_export import export_pdf_report + + pdf_path = export_pdf_report(report_data, output_dir) + if pdf_path: + pdf_info = f"\n {pdf_path}" + + review_pack_info = "" + if args.review_pack: + from src.review_pack import export_review_pack + + review_pack_result = export_review_pack( + report_data, + output_dir, + diff_data=diff_dict, + portfolio_profile=args.portfolio_profile, + collection=args.collection, + ) + review_pack_info = f"\n {review_pack_result['review_pack_path']}" + + if args.auto_archive: + from src.archive_candidates import export_archive_report, find_archive_candidates + + candidates = find_archive_candidates(score_history) + if candidates: + archive_result = export_archive_report(candidates, report.username, output_dir) + print_info( + f"Archive candidates: {archive_result['count']} repos → {archive_result['report_path']}" + ) + + if getattr(args, "vuln_check", False): + from src.vuln_check import check_vulnerabilities, format_vuln_summary + + vulns = check_vulnerabilities(report_data.get("audits", []), cache=cache) + print_info(format_vuln_summary(vulns)) + if vulns: + vuln_path = ( + output_dir / f"vuln-report-{report.username}-{_date_str(report.generated_at)}.json" + ) + vuln_path.write_text(json.dumps(vulns, indent=2, default=str)) + print_info(f"Vulnerability report: {vuln_path}") + + if getattr(args, "ghas_alerts", False) or getattr(args, "vuln_check", False): + from src.ghas_alert_details import fetch_dependabot_details + from src.ghas_alerts import fetch_ghas_alerts, format_ghas_summary + + ghas_token: str | None = getattr(args, "token", None) or None + ghas_data = fetch_ghas_alerts( + report_data.get("audits", []), + token=ghas_token, + cache=cache, + ) + # Enrich each repo entry with per-alert detail for security-burndown. + # fetch_dependabot_details paginates the same endpoint as fetch_ghas_alerts + # but lives in a separate module to keep ghas_alerts.py byte-identical to + # main (editing it triggers ruff-format reflows that CodeQL flags). + dep_details = fetch_dependabot_details( + report_data.get("audits", []), + token=ghas_token, + cache=cache, + ) + for repo_name in ghas_data: + ghas_data[repo_name]["dependabot_details"] = dep_details.get(repo_name, []) + print_info(format_ghas_summary(ghas_data)) + if ghas_data: + ghas_path = ( + output_dir / f"ghas-alerts-{report.username}-{_date_str(report.generated_at)}.json" + ) + ghas_path.write_text(json.dumps(ghas_data, indent=2, default=str)) + print_info(f"GHAS alerts report: {ghas_path}") + + if getattr(args, "ossf_scorecard", False): + from src.ossf_scorecard import fetch_ossf_scorecards, format_ossf_summary + + ossf_data = fetch_ossf_scorecards( + report_data.get("audits", []), + cache=cache, + ) + # Wire per-repo data into audit JSON + ossf_by_repo: dict[str, dict] = {} + for full_name, scorecard in ossf_data.items(): + ossf_by_repo[full_name] = scorecard + for audit in report.audits: + fn = audit.metadata.full_name + if fn in ossf_by_repo: + audit.ossf_scorecard = ossf_by_repo[fn] + # Re-serialize after mutation + report_data = report.to_dict() + + print_info(format_ossf_summary(ossf_data)) + ossf_path = ( + output_dir / f"ossf-scorecard-{report.username}-{_date_str(report.generated_at)}.json" + ) + ossf_path.write_text(json.dumps(ossf_data, indent=2, default=str)) + print_info(f"OSSF Scorecard report: {ossf_path}") + + # ── LLM cost tracking ──────────────────────────────────────────────────── + _uses_llm = args.narrative or getattr(args, "briefing", False) + _cost_tracker = None + if _uses_llm: + from src.llm_cost import BudgetExceededError, CostTracker + + _cost_tracker = CostTracker( + budget_usd=getattr(args, "max_llm_spend", None), + output_path=output_dir, + ) + + if args.narrative: + from src.narrative import generate_narrative + + try: + generate_narrative( + report_data, + output_dir, + provider_name=args.narrative_provider, + model=args.narrative_model, + github_token=args.token, + cost_tracker=_cost_tracker, + ) + except BudgetExceededError as exc: + print(f"\nERROR: {exc}", file=sys.stderr) + if _cost_tracker is not None: + _cost_tracker.write_telemetry() + sys.exit(1) + + if getattr(args, "briefing", False): + from src.briefing import generate_briefing + + try: + generate_briefing( + report_data, + output_dir, + provider_name=args.narrative_provider, + model=args.narrative_model, + github_token=args.token, + write_voice=getattr(args, "briefing_voice", False), + cost_tracker=_cost_tracker, + include_suggestions=getattr(args, "include_suggestions", False), + ) + except BudgetExceededError as exc: + print(f"\nERROR: {exc}", file=sys.stderr) + if _cost_tracker is not None: + _cost_tracker.write_telemetry() + sys.exit(1) + + if _cost_tracker is not None: + _cost_tracker.write_telemetry() + + cache_info = "" + if cache: + cache_info = f"\n Cache: {cache.hits} hits, {cache.misses} misses" + + return { + "json_path": json_path, + "md_path": md_path, + "excel_path": excel_path, + "pcc_path": pcc_path, + "raw_path": raw_path, + "warehouse_path": warehouse_path, + "badge_info": badge_info, + "notion_info": notion_info, + "readme_info": readme_info, + "suggestions_info": suggestions_info, + "html_info": html_info, + "pdf_info": pdf_info, + "review_pack_info": review_pack_info, + "cache_info": cache_info, + } + +def _ensure_partial_run_baseline_compatible( + existing_report_data: dict | None, current_context: dict +) -> bool: + if not existing_report_data: + return True + + existing_context = extract_baseline_context(existing_report_data) + if not existing_context: + print_warning( + "Latest report does not include baseline context.\n" + " Run a full audit first so targeted and incremental reruns have a trustworthy baseline." + ) + return False + + mismatches = compare_baseline_context(current_context, existing_context) + if not mismatches: + return True + + details = "\n".join( + f" {item['label']}: existing={format_mismatch_value(item['actual'])} | requested={format_mismatch_value(item['expected'])}" + for item in mismatches + ) + print_warning( + "Latest report was generated with an incompatible baseline context.\n" + f"{details}\n" + " Run a full audit first before doing a partial rerun." + ) + return False + +def _print_output_summary( + headline: str, + report: AuditReport, + outputs: dict[str, object], +) -> None: + print( + f"\n✓ {headline}\n" + f" Average score: {report.average_score:.2f}\n" + f" Tiers: {report.tier_distribution}" + f"{outputs['cache_info']}\n" + f" Reports:\n" + f" {outputs['json_path']}\n" + f" {outputs['md_path']}\n" + f" {outputs['excel_path']}\n" + f" {outputs['pcc_path']}\n" + f" {outputs['raw_path']}\n" + f" {outputs['warehouse_path']}" + f"{outputs['badge_info']}" + f"{outputs['notion_info']}" + f"{outputs['readme_info']}" + f"{outputs['suggestions_info']}" + f"{outputs['html_info']}" + f"{outputs['pdf_info']}" + f"{outputs['review_pack_info']}", + ) + if report.campaign_outcomes_summary.get("summary"): + print_info(f"Post-apply monitoring: {report.campaign_outcomes_summary.get('summary')}") + if report.next_monitoring_step.get("summary"): + print_info(f"Next monitoring step: {report.next_monitoring_step.get('summary')}") + if report.campaign_tuning_summary.get("summary"): + print_info(f"Campaign tuning: {report.campaign_tuning_summary.get('summary')}") + if report.next_tuned_campaign.get("summary"): + print_info( + f"{ACTION_SYNC_CANONICAL_LABELS['next_tie_break_candidate']}: {report.next_tuned_campaign.get('summary')}" + ) + if report.intervention_ledger_summary.get("summary"): + print_info( + f"Historical portfolio intelligence: {report.intervention_ledger_summary.get('summary')}" + ) + if report.next_historical_focus.get("summary"): + print_info(f"Next historical focus: {report.next_historical_focus.get('summary')}") + if report.automation_guidance_summary.get("summary"): + print_info(f"Automation guidance: {report.automation_guidance_summary.get('summary')}") + if report.next_safe_automation_step.get("summary"): + print_info(f"Next safe automation step: {report.next_safe_automation_step.get('summary')}") + print_info(_normal_audit_next_step_hint(report.username)) + +def _run_targeted_audit( + args, + client: GitHubClient, + output_dir: Path, + *, + all_repos: list[RepoMetadata], + errors: list[dict], + custom_weights: dict[str, float] | None, + scoring_profile_name: str, + existing_report_path: Path | None = None, + existing_report_data: dict | None = None, + watch_plan=None, + latest_trusted_baseline: dict | None = None, +) -> None: + """Audit only specific repos and merge into the most recent full report.""" + target_names = _resolve_repo_names(args.repos) + print_status(f"Targeted audit: {len(target_names)} repos") + + if existing_report_path is None and existing_report_data is None: + existing_report_path, existing_report_data = _load_latest_report(output_dir) + + filtered_repos = _filter_repos( + all_repos, + skip_forks=args.skip_forks, + skip_archived=args.skip_archived, + ) + targeted_repos, missing = _select_target_repos(target_names, filtered_repos) + run_errors = list(errors) + for name in missing: + run_errors.append( + {"repo": f"{args.username}/{name}", "error": "Repo not found in fetched metadata"} + ) + print_warning(f"Repo not found: {name}") + + if not targeted_repos: + print_warning("No repos to audit.") + return + + baseline_context = build_baseline_context_from_args( + args, + scoring_profile=scoring_profile_name, + portfolio_baseline_size=len(filtered_repos), + ) + if not _ensure_partial_run_baseline_compatible(existing_report_data, baseline_context): + return + + portfolio_lang_freq = _portfolio_lang_freq_for_filtered_baseline(filtered_repos) + runtime_stats: dict[str, float] = {} + new_audits = _analyze_repos( + targeted_repos, + args=args, + client=client, + portfolio_lang_freq=portfolio_lang_freq, + custom_weights=custom_weights, + runtime_stats=runtime_stats, + ) + if not new_audits: + return + + # Load existing audits from the latest report so we can merge into them + existing_audits = existing_report_data.get("audits", []) if existing_report_data else [] + if existing_report_path: + print_info( + f"Merging into {existing_report_path.name} ({len(existing_audits)} existing repos)" + ) + + # Replace any existing audit entries for the re-analyzed repos + new_names = {audit.metadata.name for audit in new_audits} + kept_audits = [ + _audit_from_dict(audit_data) + for audit_data in existing_audits + if audit_data["metadata"]["name"] not in new_names + ] + # new_audits first so they appear at the top of the report + merged_audits = list(new_audits) + kept_audits + total_repos = ( + existing_report_data.get("total_repos", len(filtered_repos)) + if existing_report_data + else len(filtered_repos) + ) + + report = AuditReport.from_audits( + args.username, + merged_audits, + run_errors, + total_repos, + scoring_profile=scoring_profile_name, + run_mode="targeted", + portfolio_baseline_size=len(filtered_repos), + baseline_signature=baseline_context["baseline_signature"], + baseline_context=baseline_context, + ) + report.watch_state = build_watch_state( + args, + scoring_profile=scoring_profile_name, + portfolio_baseline_size=len(filtered_repos), + run_mode="targeted", + watch_plan=watch_plan, + latest_trusted_baseline=latest_trusted_baseline, + full_refresh_interval_days=FULL_REFRESH_DAYS, + ) + report.preflight_summary = getattr(args, "_preflight_summary", {}) + report.runtime_breakdown = runtime_stats + _apply_requested_reconciliation(report, args, merged_audits) + + outputs = _write_report_outputs( + report, + args, + output_dir, + client=client, + cache=None, + diff_source=args.diff or existing_report_path, + ) + _print_output_summary( + f"Targeted audit: {len(new_audits)} new/updated + {len(kept_audits)} existing = {len(merged_audits)} total", + report, + outputs, + ) + +def _regenerate_outputs_from_latest_report( + args, + output_dir: Path, + *, + client: GitHubClient | None, + existing_report_path: Path, + existing_report_data: dict, + watch_state_override: dict | None = None, +) -> None: + report = _report_from_dict(existing_report_data) + if getattr(args, "_preflight_summary", {}): + report.preflight_summary = getattr(args, "_preflight_summary", {}) + if watch_state_override: + report.watch_state = watch_state_override + needs_fresh_json = bool(args.campaign) + outputs = _write_report_outputs( + report, + args, + output_dir, + client=client, + json_path=None if needs_fresh_json else existing_report_path, + write_json=needs_fresh_json, + archive=needs_fresh_json, + save_fingerprint_data=False, + ) + print( + f"\n✓ Regenerated outputs from latest audit for {report.username}\n" + f" Source report: {existing_report_path}\n" + f" Reports:\n" + f" {outputs['md_path']}\n" + f" {outputs['excel_path']}\n" + f" {outputs['pcc_path']}\n" + f" {outputs['raw_path']}\n" + f" {outputs['warehouse_path']}" + f"{outputs['badge_info']}" + f"{outputs['notion_info']}" + f"{outputs['readme_info']}" + f"{outputs['suggestions_info']}" + f"{outputs['html_info']}" + f"{outputs['review_pack_info']}", + ) + +def _run_incremental_audit( + args, + client: GitHubClient, + output_dir: Path, + *, + all_repos: list[RepoMetadata], + errors: list[dict], + custom_weights: dict[str, float] | None, + scoring_profile_name: str, + watch_plan=None, + latest_trusted_baseline: dict | None = None, +) -> None: + """Only re-audit repos whose pushed_at changed since last run.""" + from src.history import load_fingerprints + + existing_report_path, existing_report_data = _load_latest_report(output_dir) + if not existing_report_path or not existing_report_data: + print_warning("No previous audit report found. Run a full audit first.") + return + + fingerprints = load_fingerprints(output_dir / ".audit-fingerprints.json") + if not fingerprints: + print_warning("No fingerprints found. Run a full audit first.") + print_info(f"Usage: python -m src {args.username}") + return + + repos = _filter_repos(all_repos, skip_forks=args.skip_forks, skip_archived=args.skip_archived) + + # Compare current pushed_at timestamps against stored fingerprints + changed: list[str] = [] + new: list[str] = [] + for repo in repos: + prev = fingerprints.get(repo.name) + curr_pushed = repo.pushed_at.isoformat() if repo.pushed_at else None + if prev is None: + # Repo not seen before — add to audit queue + new.append(repo.name) + elif prev.get("pushed_at") != curr_pushed: + # pushed_at changed — new commits since last run + changed.append(repo.name) + + needs_audit = changed + new + unchanged = len(repos) - len(needs_audit) + print_info( + f"Incremental: {len(needs_audit)} need audit " + f"({len(changed)} changed, {len(new)} new), {unchanged} unchanged" + ) + + if not needs_audit: + effective_watch_plan = watch_plan or argparse.Namespace( + mode="incremental", + reason="manual-incremental-run", + full_refresh_due=False, + ) + print_info("No changes. Regenerating outputs from latest report.") + watch_state = build_watch_state( + args, + scoring_profile=scoring_profile_name, + portfolio_baseline_size=existing_report_data.get("portfolio_baseline_size", len(repos)), + run_mode="incremental", + watch_plan=effective_watch_plan, + latest_trusted_baseline=latest_trusted_baseline, + full_refresh_interval_days=FULL_REFRESH_DAYS, + ) + _regenerate_outputs_from_latest_report( + args, + output_dir, + client=client, + existing_report_path=existing_report_path, + existing_report_data=existing_report_data, + watch_state_override=watch_state, + ) + return + + args.repos = needs_audit + effective_watch_plan = watch_plan or argparse.Namespace( + mode="incremental", + reason="manual-incremental-run", + full_refresh_due=False, + ) + _run_targeted_audit( + args, + client, + output_dir, + all_repos=all_repos, + errors=errors, + custom_weights=custom_weights, + scoring_profile_name=scoring_profile_name, + existing_report_path=existing_report_path, + existing_report_data=existing_report_data, + watch_plan=effective_watch_plan, + latest_trusted_baseline=latest_trusted_baseline, + ) + +def _load_scoring_profile(profile_name: str | None) -> tuple[dict[str, float] | None, str]: + normalized = _normalize_profile_name(profile_name) + if not profile_name: + return None, normalized + + profile_path = Path(f"config/scoring-profiles/{profile_name}.json") + if profile_path.is_file(): + print_info(f"Using scoring profile: {profile_name}") + return json.loads(profile_path.read_text()), normalized + + print_warning(f"Scoring profile not found: {profile_path}") + return None, normalized + +def _print_dry_run_summary(repos: list[RepoMetadata]) -> None: + """Print a Rich table of repos that would be audited, then return.""" + from datetime import timezone + + try: + from rich.console import Console + from rich.table import Table + except ImportError: + print(f"[dry-run] {len(repos)} repos would be audited", file=sys.stderr) + for r in repos: + print(f" {r.name}", file=sys.stderr) + return + + console = Console(stderr=True) + table = Table(title=f"[dry-run] {len(repos)} repos would be audited", show_lines=False) + table.add_column("Name") + table.add_column("Language") + table.add_column("Size (KB)", justify="right") + table.add_column("Stars", justify="right") + table.add_column("Days Since Push", justify="right") + + now = datetime.now(timezone.utc) + total_kb = 0 + for r in repos: + days = "" + if r.pushed_at: + pushed = r.pushed_at + if pushed.tzinfo is None: + pushed = pushed.replace(tzinfo=timezone.utc) + days = str((now - pushed).days) + total_kb += r.size_kb or 0 + table.add_row( + r.name, + r.language or "", + str(r.size_kb or 0), + str(r.stars or 0), + days, + ) + + console.print(table) + est_mb = total_kb / 1024 + console.print(f"[dim]{len(repos)} repos would be audited, est {est_mb:.1f} MB[/dim]") + +def _maybe_run_reindex(report: "AuditReport", warehouse_path: Path, args: object) -> None: + """Run semantic reindex after audit. Skips gracefully if deps missing.""" + from src.semantic_index import SemanticIndex, _run_reindex + + embedder_name: str = getattr(args, "embedder", "voyage") + force: bool = getattr(args, "reindex_force", False) + + idx = SemanticIndex.from_embedder_name(warehouse_path, embedder_name) + if idx is None: + print_warning( + "Semantic reindex skipped — embedder unavailable. " + "Set VOYAGE_API_KEY or use --embedder local with [semantic] extra installed." + ) + return + + summary = _run_reindex(idx, report.audits, force=force) + print_info( + f"Semantic index: {summary['embedded']} embedded, " + f"{summary['skipped']} skipped, " + f"{summary['total']} total " + f"({summary['duration_s']:.2f}s)" + ) diff --git a/src/app/security_modes.py b/src/app/security_modes.py new file mode 100644 index 0000000..add3e01 --- /dev/null +++ b/src/app/security_modes.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import datetime +import json +from pathlib import Path +from typing import Any + +from src.cli_output import print_info +from src.portfolio_security_gate import ( + build_security_gate_report, + render_security_gate_markdown, +) +from src.portfolio_truth_types import TRUTH_LATEST_FILENAME +from src.security_burndown import build_security_burndown, render_burndown_markdown + + +def run_security_burndown_mode(args: Any) -> None: + """Dispatch for `audit security-burndown `.""" + output_dir = Path(args.output_dir) + username = args.username + ghas_files = sorted( + output_dir.glob(f"ghas-alerts-{username}-*.json"), + key=lambda p: p.stat().st_mtime, + ) + if not ghas_files: + print_info( + f"No ghas-alerts-{username}-*.json found in {output_dir}. " + "Run `audit report --ghas-alerts` first." + ) + raise SystemExit(1) + ghas_path = ghas_files[-1] + try: + with ghas_path.open() as fh: + ghas_data = json.load(fh) + except Exception as exc: # noqa: BLE001 + print_info(f"Could not read {ghas_path}: {exc}") + raise SystemExit(1) + if not isinstance(ghas_data, dict): + print_info(f"{ghas_path} is not a name-keyed object — cannot build burndown.") + raise SystemExit(1) + has_details = any( + isinstance(entry.get("dependabot_details"), list) + for entry in ghas_data.values() + if isinstance(entry, dict) + ) + if not has_details: + print_info( + f"Warning: {ghas_path.name} contains counts only — no per-alert detail.\n" + "Re-run `audit report --ghas-alerts` to capture detail, " + "then retry security-burndown." + ) + raise SystemExit(0) + report = build_security_burndown(ghas_data) + markdown = render_burndown_markdown(report) + print(markdown) + today = datetime.date.today().isoformat() + out_path = output_dir / f"security-burndown-{username}-{today}.md" + out_path.write_text(markdown, encoding="utf-8") + print_info(f"Burndown written to {out_path}") + json_path = output_dir / f"security-burndown-{username}-{today}.json" + json_path.write_text(json.dumps(report.to_dict(), indent=2), encoding="utf-8") + print_info(f"Burndown JSON written to {json_path}") + + +def run_security_gate_mode(args: Any) -> None: + """Dispatch for `audit security-gate`.""" + truth_path = Path(args.output_dir) / TRUTH_LATEST_FILENAME + if not truth_path.exists(): + print_info( + f"{TRUTH_LATEST_FILENAME} not found in {truth_path.parent}. " + "Run `audit report --portfolio-truth --portfolio-truth-include-security` first." + ) + raise SystemExit(1) + try: + with truth_path.open(encoding="utf-8") as fh: + portfolio_truth = json.load(fh) + except Exception as exc: # noqa: BLE001 + print_info(f"Could not read {truth_path}: {exc}") + raise SystemExit(1) + if not isinstance(portfolio_truth, dict): + print_info(f"{truth_path} is not a portfolio-truth object.") + raise SystemExit(1) + report = build_security_gate_report( + portfolio_truth, + max_age_hours=getattr(args, "max_age_hours", None), + ) + if getattr(args, "json", False): + print(json.dumps(report.to_dict(), indent=2)) + else: + print(render_security_gate_markdown(report)) + if not report.passed: + raise SystemExit(1) diff --git a/src/app/semantic_search.py b/src/app/semantic_search.py new file mode 100644 index 0000000..0d48c28 --- /dev/null +++ b/src/app/semantic_search.py @@ -0,0 +1,41 @@ +"""Standalone semantic-search command flow.""" + +from __future__ import annotations + +from pathlib import Path + +from src.cli_output import print_info, print_warning + + +def run_semantic_search_mode(args: object, query: str) -> None: + """Run a standalone semantic search against the existing warehouse index.""" + from src.semantic_index import SemanticIndex, _run_search + from src.warehouse import WAREHOUSE_FILENAME + + output_dir = Path(getattr(args, "output_dir", "output")) + warehouse_path = output_dir / WAREHOUSE_FILENAME + if not warehouse_path.exists(): + print_warning( + f"Warehouse not found at {warehouse_path}. " + "Run an audit with --reindex first to build the semantic index." + ) + return + + embedder_name: str = getattr(args, "embedder", "voyage") + idx = SemanticIndex.from_embedder_name(warehouse_path, embedder_name) + if idx is None: + print_warning( + "Semantic search unavailable — embedder not configured. " + "Set VOYAGE_API_KEY or use --embedder local." + ) + return + + results = _run_search(idx, query, k=5) + if not results: + print_info("No results found in semantic index. Run --reindex first.") + return + + print_info(f'Semantic search: "{query}"\n') + for i, result in enumerate(results, 1): + print_info(f" {i}. {result.repo_name} (distance={result.score:.4f})") + print_info(f" {result.snippet}") diff --git a/src/app/serve_mode.py b/src/app/serve_mode.py new file mode 100644 index 0000000..8432b6a --- /dev/null +++ b/src/app/serve_mode.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import sys +from pathlib import Path + + +def run_serve_mode(args: object) -> None: + """Launch the local FastAPI + HTMX web UI (requires [serve] extra).""" + try: + from src.serve.app import run_serve + except ImportError: + sys.exit("audit serve requires the [serve] extra.\nInstall with: pip install -e '.[serve]'") + output_dir = Path(getattr(args, "output_dir", "output")) + run_serve( + port=getattr(args, "port", 8080), + host=getattr(args, "host", "127.0.0.1"), + output_dir=output_dir, + ) diff --git a/src/cache.py b/src/cache.py index 7e96500..05d2c34 100644 --- a/src/cache.py +++ b/src/cache.py @@ -3,10 +3,45 @@ import hashlib import json import time +from urllib.parse import parse_qsl, urlparse from pathlib import Path +from typing import Any CACHE_DIR = Path("output/.cache") CACHE_TTL = 3600 # 1 hour +_SENSITIVE_FIELD_NAMES = frozenset( + { + "access_token", + "api_key", + "apikey", + "authorization", + "client_secret", + "credential", + "password", + "private_key", + "github_token", + "secret", + "token", + } +) + + +def contains_sensitive_data(value: Any) -> bool: + """Return whether JSON-compatible data contains a credential field.""" + if isinstance(value, dict): + return any( + str(key).lower() in _SENSITIVE_FIELD_NAMES or contains_sensitive_data(item) + for key, item in value.items() + ) + if isinstance(value, list): + return any(contains_sensitive_data(item) for item in value) + if isinstance(value, tuple): + return any(contains_sensitive_data(item) for item in value) + return False + + +def _url_has_sensitive_query(url: str) -> bool: + return any(name.lower() in _SENSITIVE_FIELD_NAMES for name, _value in parse_qsl(urlparse(url).query)) class ResponseCache: @@ -50,6 +85,8 @@ def put( response: object, ) -> None: """Store response data with current timestamp.""" + if _url_has_sensitive_query(url) or contains_sensitive_data(params) or contains_sensitive_data(response): + return path = self._path(url, params) entry = { "url": url, @@ -58,7 +95,7 @@ def put( "cached_at": time.time(), } try: - path.write_text(json.dumps(entry)) + path.write_text(json.dumps(entry)) # lgtm [py/clear-text-storage-sensitive-data] redacted above except OSError: pass # Cache write failure is non-fatal diff --git a/src/cli.py b/src/cli.py index fb61cc2..2c00a28 100644 --- a/src/cli.py +++ b/src/cli.py @@ -14,44 +14,49 @@ from __future__ import annotations import argparse -import json import os import re import subprocess import sys import warnings -from collections import Counter -from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path -from time import perf_counter - -from src.analyzers import run_all_analyzers -from src.baseline_context import ( - build_baseline_context_from_args, - build_watch_state, - compare_baseline_context, - extract_baseline_context, - format_mismatch_value, - normalize_scoring_profile, -) -from src.cache import ResponseCache + from src.cli_mode_validation import validate_cli_mode_args -from src.cli_output import create_progress, print_info, print_status, print_warning -from src.cloner import clone_workspace -from src.github_client import GitHubClient -from src.models import AnalyzerResult, AuditReport, RepoAudit, RepoMetadata -from src.portfolio_truth_types import TRUTH_LATEST_FILENAME, truth_latest_path -from src.recurring_review import FULL_REFRESH_DAYS -from src.report_enrichment import build_run_change_counts, build_run_change_summary -from src.reporter import ( - write_json_report, - write_markdown_report, - write_pcc_export, - write_raw_metadata, +from src.cli_output import print_info +from src.app.run_audit import ( + _run_main_audit_cycle, + _run_watch_mode, +) +from src.app.auto_apply import run_auto_apply_approved_mode +from src.app.automation_proposals import run_automation_proposals_mode +from src.app.initiatives import ( + run_close_initiative_mode, + run_list_initiatives_mode, + run_set_initiative_mode, +) +from src.app.initiative_suggestions import ( + _run_accept_suggestion_mode, + _run_dismiss_suggestion_mode, + _run_dismissal_history_mode, + _run_expire_dismissals_mode, + _run_list_dismissed_mode, + _run_suggest_initiatives_mode, + _run_undo_dismiss_mode, ) -from src.scorer import score_repo -from src.terminology import ACTION_SYNC_CANONICAL_LABELS +from src.app.campaign_workflow import ( + _run_campaign_from_ledger_mode, + _run_draft_readmes_mode, + _run_plan_campaign_mode, +) +from src.app.portfolio_analysis import ( + _run_context_triage_mode, + _run_tier_gaps_export_mode, + _run_tier_recalibration_report_mode, +) +from src.app.improvement_application import _run_apply_improvements_mode +from src.app.semantic_search import run_semantic_search_mode + # Emitted at most once per process when legacy flat invocation is used. _LEGACY_WARNING_EVENTS: set[str] = set() @@ -91,8 +96,6 @@ audit --campaign security-review --writeback-target all --github-projects""" -def _date_str(dt: datetime) -> str: - return dt.strftime("%Y-%m-%d") def _utcnow() -> datetime: @@ -1592,5583 +1595,255 @@ def build_subcommand_parser() -> argparse.ArgumentParser: # ── Repo filtering and selection helpers ───────────────────────────── -def _filter_repos( - repos: list[RepoMetadata], - *, - skip_forks: bool = False, - skip_archived: bool = False, -) -> list[RepoMetadata]: - """Apply exclusion filters to the repo list.""" - filtered = repos - if skip_forks: - filtered = [r for r in filtered if not r.fork] - if skip_archived: - filtered = [r for r in filtered if not r.archived] - return filtered - - -def _write_json( - username: str, - repos: list[RepoMetadata], - errors: list[dict], - total_fetched: int, - output_dir: Path, - audits: list[RepoAudit] | None = None, -) -> Path: - """Write audit results JSON and return the file path.""" - output_dir.mkdir(parents=True, exist_ok=True) - output_path = output_dir / "raw_metadata.json" - - if audits: - # Compute tier distribution - tier_dist: dict[str, int] = {} - for a in audits: - tier_dist[a.completeness_tier] = tier_dist.get(a.completeness_tier, 0) + 1 - avg_score = sum(a.overall_score for a in audits) / len(audits) if audits else 0.0 - - report = { - "username": username, - "generated_at": datetime.now(timezone.utc).isoformat(), - "total_repos": total_fetched, - "repos_audited": len(audits), - "average_score": round(avg_score, 3), - "tier_distribution": tier_dist, - "audits": [a.to_dict() for a in audits], - "errors": errors, - } - else: - report = { - "username": username, - "generated_at": datetime.now(timezone.utc).isoformat(), - "total_repos": total_fetched, - "repos_included": len(repos), - "repos": [r.to_dict() for r in repos], - "errors": errors, - } - - with open(output_path, "w") as f: - json.dump(report, f, indent=2) - - return output_path - - -def _print_verbose(audit: RepoAudit) -> None: - """Print per-dimension score breakdown for a repo.""" - print(f"\n {'─' * 50}", file=sys.stderr) - print( - f" {audit.metadata.name} " - f"score={audit.overall_score:.2f} " - f"tier={audit.completeness_tier}" - f"{' flags=' + ','.join(audit.flags) if audit.flags else ''}", - file=sys.stderr, - ) - for r in audit.analyzer_results: - bar = "█" * int(r.score * 10) + "░" * (10 - int(r.score * 10)) - print( - f" {r.dimension:<17} {bar} {r.score:.2f}", - file=sys.stderr, - ) - for finding in r.findings[:3]: - print(f" · {finding}", file=sys.stderr) - - -def _resolve_repo_names(repos_arg: list[str]) -> list[str]: - """Extract repo names from URLs or bare names.""" - names = [] - seen: set[str] = set() - for r in repos_arg: - r = r.strip().rstrip("/") - if "/" in r: - # URL like https://github.com/user/RepoName - name = r.split("/")[-1] - else: - name = r - if name and name not in seen: - names.append(name) - seen.add(name) - return names - - -def _normalize_profile_name(profile_name: str | None) -> str: - return normalize_scoring_profile(profile_name) - - -def _parse_iso_dt(value: str | None) -> datetime | None: - if not value: - return None - return datetime.fromisoformat(value.replace("Z", "+00:00")) - - -# ── JSON deserialization helpers ────────────────────────────────────── -def _audit_from_dict(data: dict) -> RepoAudit: - meta_data = data.get("metadata", {}) - metadata = RepoMetadata( - name=meta_data["name"], - full_name=meta_data["full_name"], - description=meta_data.get("description"), - language=meta_data.get("language"), - languages=meta_data.get("languages", {}), - private=meta_data["private"], - fork=meta_data["fork"], - archived=meta_data["archived"], - created_at=_parse_iso_dt(meta_data.get("created_at")), # type: ignore[arg-type] - updated_at=_parse_iso_dt(meta_data.get("updated_at")), # type: ignore[arg-type] - pushed_at=_parse_iso_dt(meta_data.get("pushed_at")), - default_branch=meta_data.get("default_branch", "main"), - stars=meta_data.get("stars", 0), - forks=meta_data.get("forks", 0), - open_issues=meta_data.get("open_issues", 0), - size_kb=meta_data.get("size_kb", 0), - html_url=meta_data.get("html_url", ""), - clone_url=meta_data.get("clone_url", ""), - topics=meta_data.get("topics", []), - ) - analyzer_results = [ - AnalyzerResult( - dimension=result["dimension"], - score=result["score"], - max_score=result["max_score"], - findings=result["findings"], - details=result.get("details", {}), - ) - for result in data.get("analyzer_results", []) - ] - return RepoAudit( - metadata=metadata, - analyzer_results=analyzer_results, - overall_score=data.get("overall_score", 0), - completeness_tier=data.get("completeness_tier", "abandoned"), - interest_score=data.get("interest_score", 0), - interest_tier=data.get("interest_tier", "mundane"), - grade=data.get("grade", "F"), - interest_grade=data.get("interest_grade", "F"), - badges=data.get("badges", []), - next_badges=data.get("next_badges", []), - flags=data.get("flags", []), - lenses=data.get("lenses", {}), - hotspots=data.get("hotspots", []), - action_candidates=data.get("action_candidates", []), - security_posture=data.get("security_posture", {}), - score_explanation=data.get("score_explanation", {}), - portfolio_catalog=data.get("portfolio_catalog", {}), - scorecard=data.get("scorecard", {}), - ossf_scorecard=data.get("ossf_scorecard", {}), - ) - - -def _report_from_dict(data: dict) -> AuditReport: - from src.registry_parser import RegistryReconciliation - - reconciliation = None - if data.get("reconciliation"): - reconciliation = RegistryReconciliation(**data["reconciliation"]) - - summary = data.get("summary", {}) - return AuditReport( - username=data["username"], - generated_at=_parse_iso_dt(data.get("generated_at")) or datetime.now(timezone.utc), - total_repos=data.get("total_repos", 0), - repos_audited=data.get("repos_audited", 0), - tier_distribution=data.get("tier_distribution", {}), - average_score=data.get("average_score", 0), - language_distribution=data.get("language_distribution", {}), - audits=[_audit_from_dict(audit) for audit in data.get("audits", [])], - errors=data.get("errors", []), - portfolio_grade=data.get("portfolio_grade", "F"), - portfolio_health_score=data.get("portfolio_health_score", 0), - tech_stack=data.get("tech_stack", {}), - best_work=data.get("best_work", []), - most_active=summary.get("most_active", []), - most_neglected=summary.get("most_neglected", []), - highest_scored=summary.get("highest_scored", []), - lowest_scored=summary.get("lowest_scored", []), - scoring_profile=data.get("scoring_profile", "default"), - run_mode=data.get("run_mode", "full"), - portfolio_baseline_size=data.get("portfolio_baseline_size", len(data.get("audits", []))), - baseline_signature=data.get("baseline_signature", ""), - baseline_context=data.get("baseline_context", {}), - schema_version=data.get("schema_version", "3.7"), - lenses=data.get("lenses", {}), - hotspots=data.get("hotspots", []), - implementation_hotspots=data.get("implementation_hotspots", []), - implementation_hotspots_summary=data.get("implementation_hotspots_summary", {}), - portfolio_outcomes_summary=data.get("portfolio_outcomes_summary", {}), - operator_effectiveness_summary=data.get("operator_effectiveness_summary", {}), - high_pressure_queue_history=data.get("high_pressure_queue_history", []), - campaign_readiness_summary=data.get("campaign_readiness_summary", {}), - action_sync_summary=data.get("action_sync_summary", {}), - next_action_sync_step=data.get("next_action_sync_step", ""), - action_sync_packets=data.get("action_sync_packets", []), - apply_readiness_summary=data.get("apply_readiness_summary", {}), - next_apply_candidate=data.get("next_apply_candidate", {}), - action_sync_outcomes=data.get("action_sync_outcomes", []), - campaign_outcomes_summary=data.get("campaign_outcomes_summary", {}), - next_monitoring_step=data.get("next_monitoring_step", {}), - action_sync_tuning=data.get("action_sync_tuning", []), - campaign_tuning_summary=data.get("campaign_tuning_summary", {}), - next_tuned_campaign=data.get("next_tuned_campaign", {}), - historical_portfolio_intelligence=data.get("historical_portfolio_intelligence", []), - intervention_ledger_summary=data.get("intervention_ledger_summary", {}), - next_historical_focus=data.get("next_historical_focus", {}), - action_sync_automation=data.get("action_sync_automation", []), - automation_guidance_summary=data.get("automation_guidance_summary", {}), - next_safe_automation_step=data.get("next_safe_automation_step", {}), - approval_ledger=data.get("approval_ledger", []), - approval_workflow_summary=data.get("approval_workflow_summary", {}), - next_approval_review=data.get("next_approval_review", {}), - security_posture=data.get("security_posture", {}), - security_governance_preview=data.get("security_governance_preview", []), - collections=data.get("collections", {}), - profiles=data.get("profiles", {}), - scenario_summary=data.get("scenario_summary", {}), - action_backlog=data.get("action_backlog", []), - campaign_summary=data.get("campaign_summary", {}), - writeback_preview=data.get("writeback_preview", {}), - writeback_results=data.get("writeback_results", {}), - action_runs=data.get("action_runs", []), - external_refs=data.get("external_refs", {}), - managed_state_drift=data.get("managed_state_drift", []), - rollback_preview=data.get("rollback_preview", {}), - campaign_history=data.get("campaign_history", []), - governance_preview=data.get("governance_preview", {}), - governance_approval=data.get("governance_approval", {}), - governance_results=data.get("governance_results", {}), - governance_history=data.get("governance_history", []), - governance_drift=data.get("governance_drift", []), - governance_summary=data.get("governance_summary", {}), - preflight_summary=data.get("preflight_summary", {}), - review_summary=data.get("review_summary", {}), - review_alerts=data.get("review_alerts", []), - material_changes=data.get("material_changes", []), - review_targets=data.get("review_targets", []), - review_history=data.get("review_history", []), - watch_state=data.get("watch_state", {}), - operator_summary=data.get("operator_summary", {}), - operator_queue=data.get("operator_queue", []), - portfolio_catalog_summary=data.get("portfolio_catalog_summary", {}), - operating_paths_summary=data.get("operating_paths_summary", {}), - intent_alignment_summary=data.get("intent_alignment_summary", {}), - scorecards_summary=data.get("scorecards_summary", {}), - scorecard_programs=data.get("scorecard_programs", {}), - reconciliation=reconciliation, - ) - - -def _apply_portfolio_catalog(report: AuditReport, args) -> AuditReport: - from src.portfolio_catalog import ( - DEFAULT_CATALOG_PATH, - build_catalog_line, - build_intent_alignment_summary, - build_portfolio_catalog_summary, - catalog_entry_for_repo, - evaluate_intent_alignment, - load_portfolio_catalog, - ) - from src.report_enrichment import build_operator_focus - - catalog_path = getattr(args, "catalog", None) or DEFAULT_CATALOG_PATH - catalog_data = load_portfolio_catalog(Path(catalog_path)) - queue_by_repo = { - str(item.get("repo") or item.get("repo_name") or "").strip(): item - for item in (report.operator_queue or []) - if str(item.get("repo") or item.get("repo_name") or "").strip() - } - for audit in report.audits: - metadata = audit.metadata.to_dict() - base_entry = catalog_entry_for_repo(metadata, catalog_data) - focus_source = queue_by_repo.get(audit.metadata.name, {}) - operator_focus = build_operator_focus(focus_source) - intent_alignment, intent_alignment_reason = evaluate_intent_alignment( - base_entry, - completeness_tier=audit.completeness_tier, - archived=audit.metadata.archived, - operator_focus=operator_focus, - ) - audit.portfolio_catalog = { - **base_entry, - "catalog_line": build_catalog_line(base_entry), - "intent_alignment": intent_alignment, - "intent_alignment_reason": intent_alignment_reason, - "intent_alignment_line": f"{intent_alignment}: {intent_alignment_reason}", - "operator_focus": operator_focus, - } - - audit_lookup = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} - for item in report.operator_queue: - repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() - catalog_entry = audit_lookup.get(repo_name, {}) - if catalog_entry: - item["portfolio_catalog"] = dict(catalog_entry) - item["catalog_line"] = catalog_entry.get("catalog_line", "") - item["intent_alignment"] = catalog_entry.get("intent_alignment", "missing-contract") - item["intent_alignment_reason"] = catalog_entry.get("intent_alignment_reason", "") - - report.portfolio_catalog_summary = build_portfolio_catalog_summary( - report.audits, - catalog_path=str(catalog_path), - ) - report.portfolio_catalog_summary["catalog_exists"] = catalog_data.get("exists", False) - report.portfolio_catalog_summary["errors"] = catalog_data.get("errors", []) - report.portfolio_catalog_summary["warnings"] = catalog_data.get("warnings", []) - report.intent_alignment_summary = build_intent_alignment_summary(report.audits) - return report - - -def _apply_scorecards(report: AuditReport, args) -> AuditReport: - from src.report_enrichment import build_maturity_gap_summary, build_scorecard_line - from src.portfolio_catalog import build_intent_alignment_summary, evaluate_intent_alignment - from src.scorecards import ( - DEFAULT_SCORECARDS_PATH, - evaluate_scorecards_for_report, - load_scorecards, - ) - - scorecards_path = getattr(args, "scorecards", None) or DEFAULT_SCORECARDS_PATH - scorecards_data = load_scorecards(Path(scorecards_path)) - repo_results, summary, programs = evaluate_scorecards_for_report(report, scorecards_data) - by_repo = {result.get("repo", ""): result for result in repo_results} - queue_by_repo = { - str(item.get("repo") or item.get("repo_name") or "").strip(): item - for item in (report.operator_queue or []) - if str(item.get("repo") or item.get("repo_name") or "").strip() - } - for audit in report.audits: - result = by_repo.get(audit.metadata.name, {}) - audit.scorecard = dict(result) - if audit.portfolio_catalog: - audit.portfolio_catalog["scorecard"] = dict(result) - operator_focus = audit.portfolio_catalog.get("operator_focus", "") - if not operator_focus: - from src.report_enrichment import build_operator_focus - - operator_focus = build_operator_focus(queue_by_repo.get(audit.metadata.name, {})) - intent_alignment, intent_alignment_reason = evaluate_intent_alignment( - audit.portfolio_catalog, - completeness_tier=audit.completeness_tier, - archived=audit.metadata.archived, - operator_focus=operator_focus, - ) - audit.portfolio_catalog.update( - { - "intent_alignment": intent_alignment, - "intent_alignment_reason": intent_alignment_reason, - "intent_alignment_line": f"{intent_alignment}: {intent_alignment_reason}", - "operator_focus": operator_focus, - } - ) - catalog_by_repo = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} - for item in report.operator_queue: - repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() - result = by_repo.get(repo_name, {}) - catalog_entry = catalog_by_repo.get(repo_name, {}) - if catalog_entry: - item["portfolio_catalog"] = dict(catalog_entry) - item["intent_alignment"] = catalog_entry.get("intent_alignment", "") - item["intent_alignment_reason"] = catalog_entry.get("intent_alignment_reason", "") - if result: - item["scorecard"] = dict(result) - item["scorecard_line"] = build_scorecard_line(item) - item["maturity_gap_summary"] = build_maturity_gap_summary(item) - report.scorecards_summary = summary - report.scorecard_programs = programs - report.intent_alignment_summary = build_intent_alignment_summary(report.audits) - return report - - -def _apply_operating_paths(report: AuditReport) -> AuditReport: - from src.portfolio_pathing import ( - build_operating_path_entry, - build_operating_path_line, - build_operating_paths_summary, - ) - - for audit in report.audits: - catalog_entry = dict(audit.portfolio_catalog or {}) - if not catalog_entry: - continue - path_entry = build_operating_path_entry( - catalog_entry, - intent_alignment=catalog_entry.get("intent_alignment", ""), - archived=audit.metadata.archived, - completeness_tier=audit.completeness_tier, - decision_quality_status=(report.operator_summary or {}) - .get("decision_quality_v1", {}) - .get( - "decision_quality_status", - "", - ), - ) - path_line = build_operating_path_line(path_entry) - audit.portfolio_catalog = { - **path_entry, - "operating_path_line": path_line, - "operator_focus": catalog_entry.get("operator_focus", ""), - } - if audit.scorecard: - audit.portfolio_catalog["scorecard"] = dict(audit.scorecard) - - audit_lookup = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} - for item in report.operator_queue: - repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() - catalog_entry = audit_lookup.get(repo_name, {}) - if not catalog_entry: - continue - item["portfolio_catalog"] = dict(catalog_entry) - item["operating_path"] = catalog_entry.get("operating_path", "") - item["path_override"] = catalog_entry.get("path_override", "") - item["path_confidence"] = catalog_entry.get("path_confidence", "") - item["path_rationale"] = catalog_entry.get("path_rationale", "") - item["operating_path_line"] = catalog_entry.get("operating_path_line", "") - - report.operating_paths_summary = build_operating_paths_summary(report.audits) - return report - - -def _load_latest_report(output_dir: Path) -> tuple[Path | None, dict | None]: - reports = sorted( - output_dir.glob("audit-report-*.json"), - key=lambda path: path.stat().st_mtime, - reverse=True, - ) - if not reports: - return None, None - latest = reports[0] - return latest, json.loads(latest.read_text()) - - -def _latest_control_center_paths( - output_dir: Path, username: str, generated_at: datetime -) -> tuple[Path, Path]: - stamp = _date_str(generated_at) - return ( - output_dir / f"operator-control-center-{username}-{stamp}.json", - output_dir / f"operator-control-center-{username}-{stamp}.md", - ) - - -def _latest_weekly_command_center_paths( - output_dir: Path, username: str, generated_at: datetime -) -> tuple[Path, Path]: - stamp = _date_str(generated_at) - return ( - output_dir / f"weekly-command-center-{username}-{stamp}.json", - output_dir / f"weekly-command-center-{username}-{stamp}.md", - ) - - -def _latest_approval_center_paths( - output_dir: Path, username: str, generated_at: datetime -) -> tuple[Path, Path]: - stamp = _date_str(generated_at) - return ( - output_dir / f"approval-center-{username}-{stamp}.json", - output_dir / f"approval-center-{username}-{stamp}.md", - ) - - -def _latest_approval_receipt_paths( - output_dir: Path, username: str, generated_at: datetime -) -> tuple[Path, Path]: - stamp = _date_str(generated_at) - return ( - output_dir / f"approval-receipt-{username}-{stamp}.json", - output_dir / f"approval-receipt-{username}-{stamp}.md", - ) - - -def _latest_followup_review_receipt_paths( - output_dir: Path, username: str, generated_at: datetime -) -> tuple[Path, Path]: - stamp = _date_str(generated_at) - return ( - output_dir / f"approval-followup-receipt-{username}-{stamp}.json", - output_dir / f"approval-followup-receipt-{username}-{stamp}.md", - ) - - -def _report_artifact_datetime(report_path: Path | None, fallback: datetime) -> datetime: - if report_path: - stem = report_path.stem - if len(stem) >= 10: - parsed = _parse_iso_dt(f"{stem[-10:]}T00:00:00+00:00") - if parsed: - return parsed - return fallback - - -def _refresh_latest_report_state( - output_dir: Path, - args, -) -> tuple[Path, dict, AuditReport]: - from src.diff import diff_reports - from src.governance_activation import build_governance_summary - from src.history import find_previous - from src.operator_control_center import normalize_review_state - - report_path, report_data = _load_latest_report(output_dir) - if not report_path or not report_data: - raise FileNotFoundError("No existing audit report found in output directory") - diff_dict = None - previous_path = find_previous(report_path.name) - if previous_path: - diff_dict = diff_reports( - previous_path, - report_path, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ).to_dict() - report = _report_from_dict(report_data) - report_data = normalize_review_state( - report.to_dict(), - output_dir=output_dir, - diff_data=diff_dict, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ) - report_data["latest_report_path"] = str(report_path) - report_data["governance_summary"] = build_governance_summary(report_data) - report = _report_from_dict(report_data) - report = _apply_portfolio_catalog(report, args) - report = _enrich_report_with_operator_state( - report, - output_dir=output_dir, - diff_dict=diff_dict, - triage_view=getattr(args, "triage_view", "all"), - portfolio_profile=args.portfolio_profile, - collection=args.collection, - ) - return report_path, diff_dict or {}, report - - -def _write_approval_center_artifacts( - report: AuditReport, - output_dir: Path, - *, - approval_view: str, -) -> tuple[Path, Path, dict]: - from src.approval_ledger import load_approval_ledger_bundle, render_approval_center_markdown - - report_data = report.to_dict() - bundle = load_approval_ledger_bundle( - output_dir, - report_data, - list(report.operator_queue or []), - approval_view=approval_view, - ) - report.approval_ledger = bundle["approval_ledger"] - report.approval_workflow_summary = bundle["approval_workflow_summary"] - report.next_approval_review = bundle["next_approval_review"] - report.operator_queue = bundle.get("operator_queue", report.operator_queue) - report.operator_summary = { - **report.operator_summary, - "approval_ledger": bundle["approval_ledger"], - "approval_workflow_summary": bundle["approval_workflow_summary"], - "next_approval_review": bundle["next_approval_review"], - "top_ready_for_review_approvals": bundle["top_ready_for_review_approvals"], - "top_needs_reapproval_approvals": bundle["top_needs_reapproval_approvals"], - "top_overdue_approval_followups": bundle["top_overdue_approval_followups"], - "top_due_soon_approval_followups": bundle["top_due_soon_approval_followups"], - "top_approved_manual_approvals": bundle["top_approved_manual_approvals"], - "top_blocked_approvals": bundle["top_blocked_approvals"], - } - generated_at = report.generated_at - username = report.username - json_path, md_path = _latest_approval_center_paths(output_dir, username, generated_at) - payload = { - "username": username, - "generated_at": generated_at.isoformat(), - "approval_view": approval_view, - "approval_workflow_summary": bundle["approval_workflow_summary"], - "next_approval_review": bundle["next_approval_review"], - "approval_ledger": bundle["approval_ledger"], - "top_ready_for_review_approvals": bundle["top_ready_for_review_approvals"], - "top_needs_reapproval_approvals": bundle["top_needs_reapproval_approvals"], - "top_overdue_approval_followups": bundle["top_overdue_approval_followups"], - "top_due_soon_approval_followups": bundle["top_due_soon_approval_followups"], - "top_approved_manual_approvals": bundle["top_approved_manual_approvals"], - "top_blocked_approvals": bundle["top_blocked_approvals"], - "operator_summary": report.operator_summary, - } - json_path.write_text(json.dumps(payload, indent=2)) - md_path.write_text(render_approval_center_markdown(payload)) - return json_path, md_path, payload - - -def _write_control_center_artifacts( - report_data: dict, - snapshot: dict, - output_dir: Path, - *, - username: str, - generated_at: datetime, - report_reference: str, - diff_dict: dict | None = None, -) -> tuple[Path, Path, Path, Path, dict]: - from src.operator_control_center import ( - control_center_artifact_payload, - render_control_center_markdown, - ) - from src.weekly_command_center import ( - build_weekly_command_center_digest, - load_latest_portfolio_truth, - write_weekly_command_center_artifacts, - ) - - _filter_control_center_snapshot_for_default_view(snapshot) - json_path, md_path = _latest_control_center_paths(output_dir, username, generated_at) - snapshot.setdefault("operator_summary", {})["control_center_reference"] = str(json_path) - portfolio_truth_path, portfolio_truth = load_latest_portfolio_truth(output_dir) - weekly_digest = build_weekly_command_center_digest( - report_data, - snapshot, - diff_data=diff_dict, - portfolio_truth=portfolio_truth, - portfolio_truth_reference=str(portfolio_truth_path) if portfolio_truth_path else "", - control_center_reference=str(json_path), - report_reference=report_reference, - generated_at=generated_at.isoformat(), - ) - weekly_json, weekly_md = write_weekly_command_center_artifacts( - output_dir, - username=username, - generated_at=generated_at, - digest=weekly_digest, - ) - payload = control_center_artifact_payload(report_data, snapshot) - payload["weekly_command_center_digest_v1"] = weekly_digest - payload["weekly_command_center_reference"] = { - "json_path": str(weekly_json), - "markdown_path": str(weekly_md), - } - json_path.write_text(json.dumps(payload, indent=2)) - md_path.write_text(render_control_center_markdown(snapshot, username, generated_at.isoformat())) - return json_path, md_path, weekly_json, weekly_md, payload - - -def _enrich_control_center_snapshot_from_report( - report_data: dict, - snapshot: dict, - args, -) -> dict: - from src.portfolio_catalog import ( - DEFAULT_CATALOG_PATH, - build_catalog_line, - catalog_entry_for_repo, - evaluate_intent_alignment, - load_portfolio_catalog, - ) - from src.report_enrichment import build_operator_focus - - report = _report_from_dict( - { - **report_data, - "operator_summary": snapshot.get("operator_summary", {}), - "operator_queue": snapshot.get("operator_queue", []), - } - ) - catalog_path = getattr(args, "catalog", None) or DEFAULT_CATALOG_PATH - catalog_data = load_portfolio_catalog(Path(catalog_path)) - queue_by_repo = { - str(item.get("repo") or item.get("repo_name") or "").strip(): item - for item in report.operator_queue - if str(item.get("repo") or item.get("repo_name") or "").strip() - } - for audit in report.audits: - if (audit.portfolio_catalog or {}).get("has_explicit_entry"): - continue - base_entry = catalog_entry_for_repo(audit.metadata.to_dict(), catalog_data) - if not base_entry.get("has_explicit_entry"): - continue - operator_focus = build_operator_focus(queue_by_repo.get(audit.metadata.name, {})) - intent_alignment, intent_alignment_reason = evaluate_intent_alignment( - base_entry, - completeness_tier=audit.completeness_tier, - archived=audit.metadata.archived, - operator_focus=operator_focus, - ) - audit.portfolio_catalog = { - **base_entry, - "catalog_line": build_catalog_line(base_entry), - "intent_alignment": intent_alignment, - "intent_alignment_reason": intent_alignment_reason, - "intent_alignment_line": f"{intent_alignment}: {intent_alignment_reason}", - "operator_focus": operator_focus, - } - if any(audit.portfolio_catalog for audit in report.audits): - audit_lookup = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} - for item in report.operator_queue: - repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() - catalog_entry = audit_lookup.get(repo_name, {}) - if catalog_entry: - item["portfolio_catalog"] = dict(catalog_entry) - item["catalog_line"] = catalog_entry.get("catalog_line", "") - item["intent_alignment"] = catalog_entry.get("intent_alignment", "missing-contract") - item["intent_alignment_reason"] = catalog_entry.get("intent_alignment_reason", "") - else: - report = _apply_portfolio_catalog(report, args) - report = _apply_scorecards(report, args) - report = _apply_operating_paths(report) - snapshot["operator_summary"] = report.operator_summary - snapshot["operator_queue"] = report.operator_queue - return snapshot - - -def _write_approval_receipt( - output_dir: Path, - username: str, - *, - generated_at: datetime, - receipt: dict, -) -> tuple[Path, Path]: - json_path, md_path = _latest_approval_receipt_paths(output_dir, username, generated_at) - json_path.write_text(json.dumps(receipt, indent=2)) - lines = [ - f"# Approval Receipt: {username}", - "", - f"- Generated: `{generated_at.isoformat()}`", - f"- Subject: {receipt.get('label', 'Approval')}", - f"- State: {receipt.get('approval_state', 'approved')}", - f"- Reviewer: {receipt.get('approved_by', '') or 'local-operator'}", - f"- Approved At: `{receipt.get('approved_at', '')}`", - f"- Note: {receipt.get('approval_note', '') or '—'}", - f"- Summary: {receipt.get('summary', 'Local approval captured.')}", - ] - if receipt.get("approval_command"): - lines.append(f"- Approval Command: `{receipt.get('approval_command')}`") - if receipt.get("manual_apply_command"): - lines.append(f"- Manual Apply Command: `{receipt.get('manual_apply_command')}`") - md_path.write_text("\n".join(lines) + "\n") - return json_path, md_path - - -def _write_followup_review_receipt( - output_dir: Path, - username: str, - *, - generated_at: datetime, - receipt: dict, -) -> tuple[Path, Path]: - json_path, md_path = _latest_followup_review_receipt_paths(output_dir, username, generated_at) - json_path.write_text(json.dumps(receipt, indent=2)) - lines = [ - f"# Approval Follow-Up Receipt: {username}", - "", - f"- Generated: `{generated_at.isoformat()}`", - f"- Subject: {receipt.get('label', 'Approval')}", - f"- State: {receipt.get('approval_state', 'approved')} / {receipt.get('follow_up_state', 'not-applicable')}", - f"- Reviewer: {receipt.get('reviewed_by', '') or 'local-operator'}", - f"- Reviewed At: `{receipt.get('reviewed_at', '')}`", - f"- Next Follow-Up Due: `{receipt.get('next_follow_up_due_at', '') or '—'}`", - f"- Note: {receipt.get('review_note', '') or '—'}", - f"- Summary: {receipt.get('summary', 'Local follow-up review captured.')}", - ] - if receipt.get("follow_up_command"): - lines.append(f"- Follow-Up Command: `{receipt.get('follow_up_command')}`") - if receipt.get("manual_apply_command"): - lines.append(f"- Manual Apply Command: `{receipt.get('manual_apply_command')}`") - md_path.write_text("\n".join(lines) + "\n") - return json_path, md_path - - -def _refresh_shared_artifacts_from_report( - report: AuditReport, - output_dir: Path, - args, - *, - diff_dict: dict | None = None, -) -> dict[str, Path]: - from src.excel_export import export_excel - from src.history import load_repo_score_history, load_trend_data - from src.review_pack import export_review_pack - from src.warehouse import write_warehouse_snapshot - from src.web_export import export_html_dashboard - - approval_json, approval_md, _payload = _write_approval_center_artifacts( - report, - output_dir, - approval_view=getattr(args, "approval_view", "all"), - ) - json_path = write_json_report(report, output_dir) - write_markdown_report(report, output_dir, diff_data=diff_dict) - write_pcc_export(report, output_dir) - write_raw_metadata(report, output_dir) - trend_data = load_trend_data() - score_history = load_repo_score_history() - export_excel( - json_path, - output_dir / f"audit-dashboard-{report.username}-{_date_str(report.generated_at)}.xlsx", - trend_data=trend_data, - diff_data=diff_dict, - score_history=score_history, - portfolio_profile=args.portfolio_profile, - collection=args.collection, - excel_mode=args.excel_mode, - truth_dir=output_dir, - ) - export_review_pack( - report.to_dict(), - output_dir, - diff_data=diff_dict, - portfolio_profile=args.portfolio_profile, - collection=args.collection, - ) - export_html_dashboard( - report.to_dict(), - output_dir, - trend_data, - score_history, - diff_data=diff_dict, - portfolio_profile=args.portfolio_profile, - collection=args.collection, - ) - artifact_generated_at = _report_artifact_datetime(json_path, report.generated_at) - snapshot = { - "operator_summary": report.operator_summary, - "operator_queue": report.operator_queue, - } - control_json, control_md, weekly_json, weekly_md, _control_payload = ( - _write_control_center_artifacts( - report.to_dict(), - snapshot, - output_dir, - username=report.username, - generated_at=artifact_generated_at, - report_reference=str(json_path), - diff_dict=diff_dict, - ) - ) - report.operator_summary["control_center_reference"] = str(control_json) - write_warehouse_snapshot(report, output_dir, json_path) - return { - "json_path": json_path, - "control_center_json": control_json, - "control_center_md": control_md, - "weekly_command_center_json": weekly_json, - "weekly_command_center_md": weekly_md, - "approval_center_json": approval_json, - "approval_center_md": approval_md, - } + + + + + + + + + + + + + + + + + + def _run_control_center_mode(args, parser) -> None: - from src.diff import diff_reports - from src.governance_activation import build_governance_summary - from src.history import find_previous - from src.operator_control_center import build_operator_snapshot, normalize_review_state - - output_dir = Path(args.output_dir) - report_path, report_data = _load_latest_report(output_dir) - if not report_path or not report_data: - parser.error("No existing audit report found in output directory") - - diff_dict = None - previous_path = find_previous(report_path.name) - if previous_path: - diff_dict = diff_reports( - previous_path, - report_path, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ).to_dict() - - report_data["latest_report_path"] = str(report_path) - normalized = normalize_review_state( - report_data, - output_dir=output_dir, - diff_data=diff_dict, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ) - normalized["governance_summary"] = build_governance_summary(normalized) - snapshot = build_operator_snapshot( - normalized, - output_dir=output_dir, - triage_view=args.triage_view, - ) - snapshot = _enrich_control_center_snapshot_from_report(normalized, snapshot, args) - artifact_generated_at = _report_artifact_datetime( - report_path, - _parse_iso_dt(normalized.get("generated_at")) or datetime.now(timezone.utc), - ) - json_artifact, md_artifact, weekly_json, weekly_md, payload = _write_control_center_artifacts( - normalized, - snapshot, - output_dir, - username=normalized.get("username", args.username), - generated_at=artifact_generated_at, - report_reference=str(report_path), - diff_dict=diff_dict, - ) - weekly_digest = payload.get("weekly_command_center_digest_v1", {}) - source_freshness = weekly_digest.get("source_freshness", {}) - if source_freshness.get("status") and source_freshness.get("status") != "current": - print_info(weekly_digest.get("headline") or "Refresh the audit report before acting.") - print_info( - source_freshness.get("summary") - or "Control-center source freshness could not be proven." - ) - print_info(weekly_digest.get("decision") or "Refresh the audit report, then rerun.") - else: - _print_control_center_summary(snapshot) - print_info(f"Control center JSON: {json_artifact}") - print_info(f"Control center Markdown: {md_artifact}") - print_info(f"Weekly command center JSON: {weekly_json}") - print_info(f"Weekly command center Markdown: {weekly_md}") - print_info(_control_center_next_step_hint()) + from src.app.control_center import run_control_center_mode + run_control_center_mode(args, parser) -def _run_approval_center_mode(args, parser) -> None: - report_output_dir = Path(args.output_dir) - try: - _report_path, _diff_dict, report = _refresh_latest_report_state(report_output_dir, args) - except FileNotFoundError: - parser.error("No existing audit report found in output directory") - approval_json, approval_md, payload = _write_approval_center_artifacts( - report, - report_output_dir, - approval_view=args.approval_view, - ) - print_info( - payload.get("approval_workflow_summary", {}).get( - "summary", "No current approval needs review yet." - ) - ) - print_info( - payload.get("next_approval_review", {}).get( - "summary", "Stay local for now; no current approval needs review." - ) - ) - print_info(f"Approval center JSON: {approval_json}") - print_info(f"Approval center Markdown: {approval_md}") - # ── Post-process: update suppression hints ──────────────────────────────── - _post_process_approval_center_prefs(payload, report_output_dir) -def _post_process_approval_center_prefs(payload: dict, output_dir: Path) -> None: - """Build rejection records from the approval ledger and update operator_prefs.json.""" - from src.operator_prefs import ( - load_rejection_events, - post_process_approval_session, - ) - try: - rejection_records = load_rejection_events(output_dir) - total, newly_added = post_process_approval_session( - rejection_records, - output_dir, - ) - print_info(f"Suppressions: {total} action type(s) suppressed ({newly_added} newly added).") - except Exception as exc: # noqa: BLE001 - import logging - logging.getLogger(__name__).warning( - "operator_prefs post-process failed (non-fatal): %s", exc - ) +def _run_approval_center_mode(args, parser) -> None: + from src.app.approval_center import run_approval_center_mode + run_approval_center_mode(args, parser) -def _run_approval_capture_mode(args, parser) -> None: - from src.approval_ledger import ( - build_approval_followup_record, - build_approval_record, - load_approval_ledger_bundle, - ) - from src.warehouse import save_approval_followup_event, save_approval_record - report_output_dir = Path(args.output_dir) - try: - _report_path, diff_dict, report = _refresh_latest_report_state(report_output_dir, args) - except FileNotFoundError: - parser.error("No existing audit report found in output directory") - bundle = load_approval_ledger_bundle( - report_output_dir, - report.to_dict(), - list(report.operator_queue or []), - approval_view="all", - ) - ledger = { - str(item.get("approval_id") or ""): item for item in bundle.get("approval_ledger", []) - } - if args.approve_governance or args.review_governance: - approval_id = f"governance:{args.governance_scope}" - else: - approval_id = f"campaign:{args.campaign}" - ledger_record = ledger.get(approval_id) - if not ledger_record: - parser.error("No matching approval subject is surfaced in the latest report.") - - if args.approve_governance or args.approve_packet: - if ledger_record.get("approval_state") == "blocked": - parser.error( - "That approval subject is blocked by non-approval prerequisites and cannot be approved yet." - ) - if ledger_record.get("approval_state") == "not-applicable": - parser.error("That approval subject is not part of the current approval workflow.") - approval_record = build_approval_record( - ledger_record, - reviewer=args.approval_reviewer, - note=args.approval_note or "", - ) - save_approval_record(report_output_dir, approval_record) - else: - if ledger_record.get("approval_state") in { - "ready-for-review", - "needs-reapproval", - "blocked", - "not-applicable", - }: - parser.error( - "That approval subject is not currently eligible for a recurring local follow-up review." - ) - if str(ledger_record.get("follow_up_command") or "").strip() == "": - parser.error( - "That approval subject does not currently expose a follow-up review command." - ) - followup_event = build_approval_followup_record( - ledger_record, - reviewer=args.approval_reviewer, - note=args.approval_note or "", - ) - save_approval_followup_event(report_output_dir, followup_event) - - _report_path, diff_dict, report = _refresh_latest_report_state(report_output_dir, args) - _refresh_shared_artifacts_from_report(report, report_output_dir, args, diff_dict=diff_dict) - approval_json, approval_md, _payload = _write_approval_center_artifacts( - report, - report_output_dir, - approval_view="all", - ) - updated_bundle = load_approval_ledger_bundle( - report_output_dir, - report.to_dict(), - list(report.operator_queue or []), - approval_view="all", - ) - updated_record = next( - ( - item - for item in updated_bundle.get("approval_ledger", []) - if item.get("approval_id") == approval_id - ), - ledger_record, - ) - if args.approve_governance or args.approve_packet: - receipt_payload = {**updated_record, **approval_record} - receipt_json, receipt_md = _write_approval_receipt( - report_output_dir, - report.username, - generated_at=_utcnow(), - receipt=receipt_payload, - ) - print_info(receipt_payload.get("summary", "Local approval captured.")) - print_info(f"Approval receipt JSON: {receipt_json}") - print_info(f"Approval receipt Markdown: {receipt_md}") - else: - receipt_payload = {**updated_record, **followup_event} - receipt_json, receipt_md = _write_followup_review_receipt( - report_output_dir, - report.username, - generated_at=_utcnow(), - receipt=receipt_payload, - ) - print_info(receipt_payload.get("summary", "Local follow-up review captured.")) - print_info(f"Approval follow-up receipt JSON: {receipt_json}") - print_info(f"Approval follow-up receipt Markdown: {receipt_md}") - print_info(f"Approval center JSON: {approval_json}") - print_info(f"Approval center Markdown: {approval_md}") -def _run_acknowledgment_capture_mode(args, parser) -> None: - from src.diff import diff_reports - from src.history import find_previous - from src.operator_acknowledgments import ( - build_acknowledgment_record, - find_matching_change, - find_sibling_changes, - load_acknowledgments, - save_acknowledgment, - ) - from src.recurring_review import MATERIALITY_THRESHOLDS, evaluate_material_changes - - if not args.acknowledge_target: - parser.error("--acknowledge-target is required for acknowledgment capture") - if not args.acknowledge_kind: - parser.error("--acknowledge-kind is required for acknowledgment capture") - if not (args.acknowledge_note or "").strip(): - parser.error("--acknowledge-note is required and must explain the acknowledgment") - - output_dir = Path(args.output_dir) - report_path, report_data = _load_latest_report(output_dir) - if not report_path or not report_data: - parser.error("No existing audit report found in output directory") - - diff_dict: dict | None = None - previous_path = find_previous(report_path.name) - if previous_path: - diff_dict = diff_reports( - previous_path, - report_path, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ).to_dict() - - material_changes = evaluate_material_changes( - report_data, - diff_data=diff_dict, - thresholds=MATERIALITY_THRESHOLDS["standard"], - ) - acknowledgments = load_acknowledgments(output_dir, args.username) - matched = find_matching_change( - repo_name=args.acknowledge_target, - change_kind=args.acknowledge_kind, - material_changes=material_changes, - acknowledgments=acknowledgments, - ) - if not matched: - parser.error( - f"No open '{args.acknowledge_kind}' change found for " - f"'{args.acknowledge_target}' in the latest report" - ) +def _run_approval_capture_mode(args, parser) -> None: + from src.app.approval_center import run_approval_capture_mode - reviewer = args.acknowledge_reviewer or args.approval_reviewer - record = build_acknowledgment_record(matched, reviewer=reviewer, note=args.acknowledge_note) - saved_path = save_acknowledgment(output_dir, args.username, record) + run_approval_capture_mode(args, parser) - print_info( - f"Acknowledged {args.acknowledge_kind} for {args.acknowledge_target} " - f"(change_key={record['change_key'][:12]}…, reviewer={reviewer})" - ) - for sibling in find_sibling_changes(matched, material_changes): - sibling_record = build_acknowledgment_record( - sibling, reviewer=reviewer, note=args.acknowledge_note - ) - save_acknowledgment(output_dir, args.username, sibling_record) - print_info( - f"Acknowledged sibling {sibling.get('change_type')} for " - f"{sibling.get('repo_name')} " - f"(change_key={sibling_record['change_key'][:12]}…)" - ) - print_info(f"Acknowledgment store: {saved_path}") - print_info("Run --control-center to confirm the item is filtered from the queue.") + +def _run_acknowledgment_capture_mode(args, parser) -> None: + from src.app.acknowledgments import run_acknowledgment_capture_mode + + run_acknowledgment_capture_mode(args, parser) def _run_doctor_mode(args, config_inspection) -> None: - from src.diagnostics import format_diagnostics_report, run_diagnostics, write_diagnostics_report + from src.app.doctor import run_doctor_mode - result = run_diagnostics(args, config_inspection=config_inspection, full=True) - output_dir = Path(args.output_dir) - artifact_path = write_diagnostics_report(result, output_dir, args.username) - print(format_diagnostics_report(result)) - print_info(f"Diagnostics artifact: {artifact_path}") - print_info(_doctor_next_step_hint(args.username)) - if result.blocking_errors: - raise SystemExit(1) + run_doctor_mode(args, config_inspection) def _run_generate_manifest_mode(args, parser) -> None: - from src.repo_improver import generate_manifest, write_manifest + from src.app.report_only import run_generate_manifest_mode - output_dir = Path(args.output_dir) - _report_path, report_data = _load_latest_report(output_dir) - if not report_data: - parser.error("No existing audit report found in output directory") - manifest = generate_manifest(report_data) - manifest_path = write_manifest(manifest, output_dir) - print_info(f"Improvement manifest: {manifest_path} ({len(manifest)} repos)") + run_generate_manifest_mode(args, parser) -def _run_campaign_from_ledger_mode(args) -> None: - """Dispatch for --campaign-from-ledger [--writeback-apply] [--dry-run]. - Loads approved campaign-plan packets from the ledger and executes each - action via the existing apply executor map. Dry-run mode prints what would - be executed without calling the GitHub API. - """ - from src.cache import ResponseCache - from src.github_client import GitHubClient - from src.plan_campaign import ( - dispatch_action, - load_approved_campaign_plans, - mark_campaign_applied, - record_campaign_apply_failure, - ) - output_dir = Path(args.output_dir) - dry_run = getattr(args, "dry_run", False) - username = getattr(args, "username", "") or "" - cache = None if args.no_cache else ResponseCache() - client = GitHubClient(token=args.token, cache=cache) - packets = load_approved_campaign_plans(output_dir) - if not packets: - print_info("campaign-from-ledger: 0 approved packets found — nothing to apply.") - return - verb = "preview" if dry_run else "apply" - print_info(f"campaign-from-ledger: {len(packets)} approved packet(s) to {verb}.") - - for packet in packets: - print_info(f" packet goal: {packet.goal[:80]!r} ({len(packet.actions)} actions)") - - action_results: list[tuple[bool, str]] = [] - for action in packet.actions: - # 7B.5 — only dispatch actions that have been explicitly approved; - # skip pending and rejected actions. - action_state = getattr(action, "state", "pending") or "pending" - if action_state != "approved": - skip_label = "rejected" if action_state == "rejected" else "pending" - print_info(f" [skip:{skip_label}] {action.action_type} {action.repo_name}") - action_results.append((True, f"skipped ({skip_label})")) - continue - - if dry_run: - # Dry-run: print preview, record as success for state purposes - msg = ( - f"would execute: {action.action_type} {action.repo_name}" - f" (target={action.target!r}, rationale={action.rationale[:60]!r})" - ) - print_info(f" [dry-run] {msg}") - action_results.append((True, msg)) - else: - ok, msg = dispatch_action( - action, - client=client, - owner=username, - dry_run=False, - ) - status = "ok" if ok else "FAIL" - print_info(f" [{status}] {action.action_type} {action.repo_name}: {msg}") - action_results.append((ok, msg)) - - if dry_run: - # Do not mutate ledger state on dry-run - continue - - # 7B.5 — only mark applied when every action is terminal (approved+applied or rejected). - # If any action is still pending, leave as approved-manual for the operator to revisit. - has_pending = any( - (getattr(a, "state", "pending") or "pending") == "pending" for a in packet.actions - ) - if has_pending: - print_info( - " packet kept approved-manual — some actions still pending per-action review" - ) - continue - - # Determine overall packet success: - # "applied" only when every supported action succeeded AND every - # unsupported/pending action is in the packet as pending_human_action. - # Mixed-result packets (a supported action failed) stay approved-manual - # with a failure event listing the failed actions. - supported_results = [ - (ok, msg) - for (ok, msg), action in zip(action_results, packet.actions) - if action.action_type - not in ("pending_human_action", "add_license", "add_codeowners", "enable_dependabot") - and (getattr(action, "state", "pending") or "pending") != "rejected" - ] - unsupported_results = [ - (ok, msg) - for (ok, msg), action in zip(action_results, packet.actions) - if action.action_type in ("add_license", "add_codeowners", "enable_dependabot") - ] - - # Unimplemented-handler actions are expected failures — don't penalise the packet - # as long as no genuinely-supported action failed. - failed_supported = [(ok, msg) for ok, msg in supported_results if not ok] - - if not failed_supported: - mark_campaign_applied(packet, output_dir) - print_info( - f" packet marked applied " - f"(supported={len(supported_results)}, skipped={len(unsupported_results)})" - ) - else: - error_summary = "; ".join(msg for _, msg in failed_supported) - record_campaign_apply_failure(packet, error_summary, output_dir) - print_info( - f" packet kept approved-manual — {len(failed_supported)} failure(s): {error_summary[:120]}" - ) - - -def _run_plan_campaign_mode(args) -> None: - """Dispatch for --plan-campaign: generate a goal-driven campaign plan packet.""" - from src.approval_ledger import default_approval_reviewer as _default_reviewer - from src.llm_cost import BudgetExceededError, CostTracker - from src.narrative import _resolve_provider - from src.operator_prefs import load_prefs, prefs_path - from src.plan_campaign import generate_plan, narrow_candidates, write_packet_to_ledger - from src.warehouse import WAREHOUSE_FILENAME - - output_dir = Path(args.output_dir) - goal: str = str(args.plan_campaign).strip() - max_repos: int = int(getattr(args, "max_repos", 50) or 50) - reviewer: str = getattr(args, "approval_reviewer", None) or _default_reviewer() - - # ── Load audit results from portfolio-truth-latest.json ─────────────────── - truth_path = truth_latest_path(output_dir) - if not truth_path.exists(): - print_info( - f"portfolio-truth-latest.json not found in {output_dir}. " - "Run `audit report --portfolio-truth` first to generate repo data. " - "--plan-campaign requires a truth snapshot to select candidates." - ) - return - try: - raw = json.loads(truth_path.read_text(encoding="utf-8")) - audit_results: list[dict] = list(raw.get("repos", raw.get("results", []))) - except (OSError, json.JSONDecodeError) as exc: - print_info(f"Error reading portfolio-truth-latest.json: {exc}") - return - # ── Semantic index (optional — fallback to alphabetical if unavailable) ──── - semantic_index = None - warehouse_path = output_dir / WAREHOUSE_FILENAME - if warehouse_path.exists(): - try: - from src.semantic_index import SemanticIndex - - semantic_index = SemanticIndex(output_dir) - except Exception as exc: # noqa: BLE001 - print_info( - f"Warning: could not load SemanticIndex: {exc} — using alphabetical fallback." - ) - - # ── LLM provider ────────────────────────────────────────────────────────── - provider_result = _resolve_provider( - getattr(args, "narrative_provider", None), - getattr(args, "narrative_model", None), - getattr(args, "token", None), - ) - if provider_result is None: - print_info( - "No LLM provider available for --plan-campaign. " - "Set ANTHROPIC_API_KEY or GITHUB_TOKEN, or pass --narrative-provider." - ) - return - provider, model = provider_result - # ── Cost tracker ────────────────────────────────────────────────────────── - budget_usd = getattr(args, "max_llm_spend", None) - cost_tracker: CostTracker = CostTracker(budget_usd=budget_usd, output_path=output_dir) - # ── Operator prefs ──────────────────────────────────────────────────────── - pref_file = prefs_path(output_dir) - prefs = load_prefs(pref_file) - # ── Narrow candidates ───────────────────────────────────────────────────── - candidates = narrow_candidates( - audit_results, - goal=goal, - semantic_index=semantic_index, - max_repos=max_repos, - ) - if not candidates: - print_info("No candidate repos found. Check that portfolio-truth-latest.json has data.") - return - # ── Generate plan ───────────────────────────────────────────────────────── - import sys - try: - packet = generate_plan( - candidates, - goal=goal, - provider=provider, - model=model, - cost_tracker=cost_tracker, - prefs=prefs, - ) - except BudgetExceededError as exc: - print(f"\nERROR: LLM budget exceeded during campaign planning: {exc}", file=sys.stderr) - return - # ── Persist packet to ledger ────────────────────────────────────────────── - record_id = write_packet_to_ledger(packet, output_dir=output_dir, reviewer=reviewer) - cost_tracker.write_telemetry() - pending_count = sum(1 for a in packet.actions if a.action_type == "pending_human_action") - print_info( - f"Goal: {goal}. " - f"Considered {packet.candidate_count}. " - f"Qualified {packet.qualified_count}. " - f"{pending_count} pending human review. " - f"LLM cost: ${packet.llm_cost_usd:.4f}. " - f"Packet ID: {record_id}." - ) -def _run_draft_readmes_mode(args) -> None: - """Dispatch for --draft-readmes: generate LLM-authored README draft packets.""" - import sys - from src.approval_ledger import default_approval_reviewer as _default_reviewer - from src.draft_readmes import ( - build_context, - generate_draft, - qualify_repos, - write_packets_to_ledger, - ) - from src.llm_cost import BudgetExceededError, CostTracker - from src.narrative import _resolve_provider - from src.operator_prefs import ( - is_suppressed, - load_prefs, - post_process_approval_session, - prefs_path, - ) - output_dir = Path(args.output_dir) - opt_in_repos: list[str] = list(getattr(args, "draft_readmes_repos", None) or []) - all_qualifying: bool = bool(getattr(args, "draft_readmes_all", False)) - reviewer: str = getattr(args, "approval_reviewer", None) or _default_reviewer() - if not opt_in_repos and not all_qualifying: - print_info( - "--draft-readmes requires --draft-readmes-all or at least one --draft-readmes-repo. " - "No repos selected." - ) - return - # ── Load audit results (portfolio-truth-latest.json or warehouse) ───────── - audit_results: list[dict] = [] - truth_path = truth_latest_path(output_dir) - if truth_path.exists(): - try: - raw = json.loads(truth_path.read_text(encoding="utf-8")) - audit_results = list(raw.get("repos", raw.get("results", []))) - except (OSError, json.JSONDecodeError) as exc: - print_info(f"Warning: could not read portfolio-truth-latest.json: {exc}") - else: - print_info( - f"portfolio-truth-latest.json not found in {output_dir}. " - "Run `audit report --portfolio-truth` first to populate repo data. " - "Proceeding with empty repo list — only explicit --draft-readmes-repo repos will be drafted." - ) - # ── Qualify repos ────────────────────────────────────────────────────────── - repo_names = qualify_repos( - audit_results, opt_in_repos=opt_in_repos, all_qualifying=all_qualifying - ) - if not repo_names: - print_info("No repos qualify for --draft-readmes with current flags.") - return - # Build a name → dict lookup for fast access - repo_by_name: dict[str, dict] = { - str(r.get("repo_name") or r.get("name") or ""): r for r in audit_results - } - # Repos requested via --draft-readmes-repo may not exist in audit_results — create stubs - for name in repo_names: - if name not in repo_by_name: - repo_by_name[name] = {"repo_name": name, "name": name} - - # ── Semantic index (optional — proceed without neighbors if unavailable) ──── - semantic_index = None - warehouse_path = output_dir / "portfolio-warehouse.db" - if warehouse_path.exists(): - try: - from src.semantic_index import SemanticIndex - - semantic_index = SemanticIndex(output_dir) - except Exception as exc: # noqa: BLE001 - print_info( - f"Warning: could not load SemanticIndex: {exc} — proceeding without neighbors." - ) - - # ── LLM provider ────────────────────────────────────────────────────────── - provider_result = _resolve_provider( - getattr(args, "narrative_provider", None), - getattr(args, "narrative_model", None), - getattr(args, "token", None), - ) - if provider_result is None: - print_info( - "No LLM provider available for --draft-readmes. " - "Set ANTHROPIC_API_KEY or GITHUB_TOKEN, or pass --narrative-provider." - ) - return - provider, model = provider_result - - # ── Cost tracker ────────────────────────────────────────────────────────── - cost_tracker: CostTracker | None = None - budget_usd = getattr(args, "max_llm_spend", None) - if budget_usd is not None or True: # always track telemetry - cost_tracker = CostTracker(budget_usd=budget_usd, output_path=output_dir) - - # ── Operator prefs ──────────────────────────────────────────────────────── - pref_file = prefs_path(output_dir) - prefs = load_prefs(pref_file) - - # ── Main loop ───────────────────────────────────────────────────────────── - packets = [] - skipped_suppressed = 0 - skipped_budget = 0 - errors = 0 - - for repo_name in repo_names: - # 5.3 — suppression check - if is_suppressed(prefs, action_type="draft-readme", target_context=repo_name): - print_info(f" skip {repo_name}: suppressed by operator prefs") - skipped_suppressed += 1 - continue - - repo = repo_by_name[repo_name] - context = build_context(repo, semantic_index=semantic_index) - - try: - packet = generate_draft( - repo, context=context, provider=provider, model=model, cost_tracker=cost_tracker - ) - packets.append(packet) - print_info(f" drafted {repo_name} ({packet.diff_summary})") - except BudgetExceededError as exc: - print(f"\nERROR: LLM budget exceeded at {repo_name}: {exc}", file=sys.stderr) - skipped_budget = len(repo_names) - len(packets) - skipped_suppressed - 1 - break - except Exception as exc: # noqa: BLE001 - print_info(f" error drafting {repo_name}: {exc}") - errors += 1 - - # ── Persist packets ──────────────────────────────────────────────────────── - if packets: - write_packets_to_ledger(packets, output_dir, reviewer) - - # ── Refresh suppressions from rejection history ──────────────────────────── - # We pass an empty list here — newly-generated drafts have no decision yet, - # so detect_suppressions would find zero consecutive rejections. The real - # suppression update happens when the operator rejects via approval_request_reject. - # Calling post_process_approval_session with [] is a no-op but keeps the prefs - # file consistent and auto-prunes stale hints if any exist. - if pref_file.parent.exists(): - try: - post_process_approval_session([], output_dir) - except Exception as exc: # noqa: BLE001 - print_info(f"Warning: could not refresh suppression hints: {exc}") - - if cost_tracker is not None: - cost_tracker.write_telemetry() - - total_cost = cost_tracker.total_usd() if cost_tracker is not None else 0.0 - print_info( - f"Drafted {len(packets)} packet(s) for {len(packets)} repo(s). " - f"{skipped_suppressed} skipped (prefs). " - f"{skipped_budget} skipped (budget). " - f"{errors} error(s). " - f"LLM cost: ${total_cost:.4f}." - ) - - -def _run_set_initiative_mode(args) -> None: - """Validate and persist a tier-upgrade initiative for a repo.""" - import sys - from datetime import date - - from src.initiatives import ( - Initiative, - initiatives_path, - operator_identity, - upsert_initiative, - ) - from src.maturity_tiers import TIER_DEFINITIONS, compute_tier - - repo_name: str = args.set_initiative - target_tier: int | None = getattr(args, "target_tier", None) - deadline_str: str | None = getattr(args, "deadline", None) - output_dir = Path(args.output_dir) - - # Validate required co-flags - if target_tier is None: - print_warning("--target-tier is required with --set-initiative (choices: 2, 3, 4)") - sys.exit(2) - if deadline_str is None: - print_warning("--deadline YYYY-MM-DD is required with --set-initiative") - sys.exit(2) - - # Validate deadline format and future-ness - try: - deadline_date = date.fromisoformat(deadline_str) - except ValueError: - print_warning(f"--deadline must be YYYY-MM-DD, got: {deadline_str!r}") - sys.exit(2) - if deadline_date < date.today(): - print_warning(f"--deadline {deadline_str} is in the past. Provide a future date.") - sys.exit(2) - - # Load portfolio-truth to validate repo and check current tier - import json as _json - - pt_candidates = sorted(output_dir.glob(TRUTH_LATEST_FILENAME)) - if not pt_candidates: - pt_candidates = sorted(output_dir.glob("portfolio-truth-*.json")) - if not pt_candidates: - print_warning( - f"Portfolio truth not found in {output_dir}. " - "Run `audit report --portfolio-truth` first." - ) - sys.exit(2) - pt_path = truth_latest_path(output_dir) - if not pt_path.exists(): - pt_path = pt_candidates[-1] - try: - pt_data = _json.loads(pt_path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - print_warning(f"Could not read portfolio truth: {exc}") - sys.exit(2) - - projects: list[dict] = pt_data.get("projects", []) - repo_dict: dict | None = None - for proj in projects: - name = proj.get("identity", {}).get("display_name", "") - if name.lower() == repo_name.lower(): - repo_dict = proj - break - - if repo_dict is None: - print_warning( - f"Repo {repo_name!r} not found in portfolio truth. " - "Run `audit report --portfolio-truth` first." - ) - sys.exit(2) - - current_tier = compute_tier(repo_dict) - if target_tier <= current_tier: - tier_name_target = TIER_DEFINITIONS[target_tier].name - tier_name_current = TIER_DEFINITIONS[current_tier].name if current_tier > 0 else "Untracked" - print_warning( - f"Target tier {target_tier} ({tier_name_target}) is not greater than " - f"current tier {current_tier} ({tier_name_current}) for {repo_name!r}." - ) - sys.exit(2) - - from datetime import datetime as _dt - from datetime import timezone as _tz - - initiative = Initiative( - repo_name=repo_name, - target_tier=target_tier, - deadline=deadline_str, - set_at=_dt.now(tz=_tz.utc).isoformat(), - set_by=operator_identity(), - ) - upsert_initiative(initiatives_path(output_dir), initiative) - tier_label = TIER_DEFINITIONS[target_tier].name - print_info(f"Initiative set: {repo_name} → Tier {target_tier} ({tier_label}) by {deadline_str}") - - -def _run_list_initiatives_mode(args) -> None: - """Print a status table for all initiatives.""" - import json as _json - - from src.initiatives import derive_status, initiatives_path, load_initiatives - from src.maturity_tiers import TIER_DEFINITIONS, compute_tier, tier_name - - output_dir = Path(args.output_dir) - path = initiatives_path(output_dir) - initiatives = load_initiatives(path) - - # Load portfolio-truth for current-tier lookup (best-effort) - projects_by_name: dict[str, dict] = {} - pt_path = truth_latest_path(output_dir) - if pt_path.exists(): - try: - pt_data = _json.loads(pt_path.read_text(encoding="utf-8")) - for proj in pt_data.get("projects", []): - name = proj.get("identity", {}).get("display_name", "") - if name: - projects_by_name[name.lower()] = proj - except (OSError, ValueError): - # Initiative listing can proceed without portfolio-truth tier context. - pass - - open_initiatives = [i for i in initiatives if i.closed_at is None] - closed_initiatives = [i for i in initiatives if i.closed_at is not None] - - print_info("Initiative Tracker") - print_info("══════════════════") - - if not open_initiatives: - print_info("No open initiatives.") - else: - header = f"{'REPO':<30} {'TARGET':<12} {'CURRENT':<12} {'DEADLINE':<12} {'STATUS'}" - print_info(header) - print_info("-" * len(header)) - for initiative in open_initiatives: - repo_dict = projects_by_name.get(initiative.repo_name.lower(), {}) - current = compute_tier(repo_dict) if repo_dict else 0 - status = derive_status(initiative, repo_dict) - target_label = ( - f"{TIER_DEFINITIONS[initiative.target_tier].name}({initiative.target_tier})" - if initiative.target_tier in TIER_DEFINITIONS - else str(initiative.target_tier) - ) - current_label = f"{tier_name(current)}({current})" if current > 0 else "Untracked" - status_detail = status - if status == "at-risk": - from datetime import date - - try: - days_left = (date.fromisoformat(initiative.deadline) - date.today()).days - status_detail = f"at-risk (deadline ≤ {days_left}d)" - except ValueError: - # Malformed deadlines keep the generic at-risk label. - pass - elif status == "on-track": - status_detail = "on-track" - row = ( - f"{initiative.repo_name:<30} " - f"{target_label:<12} " - f"{current_label:<12} " - f"{initiative.deadline:<12} " - f"{status_detail}" - ) - print_info(row) - - if closed_initiatives: - print_info(f"\nClosed: {len(closed_initiatives)}") - - -def _run_close_initiative_mode(args) -> None: - """Close the open initiative for a repo.""" - import sys - - from src.initiatives import close_initiative, initiatives_path - - repo_name: str = args.close_initiative - output_dir = Path(args.output_dir) - closed = close_initiative(initiatives_path(output_dir), repo_name, reason="met") - if closed is None: - print_warning(f"No open initiative found for {repo_name!r}.") - sys.exit(2) - print_info( - f"Initiative closed: {repo_name} → Tier {closed.target_tier} " - f"(reason: {closed.closed_reason}, closed_at: {closed.closed_at})" - ) - - -def _run_suggest_initiatives_mode(args) -> None: - """LLM-rank repos closest to qualifying for their next maturity tier (Arc G S8.4).""" - from pathlib import Path as _Path - - from src.llm_cost import BudgetExceededError - from src.maturity_tiers import tier_name - from src.suggest_initiatives import generate_suggestions - - truth_path = truth_latest_path(_Path(args.output_dir)) - if not truth_path.exists(): - print_warning( - "portfolio-truth-latest.json not found. " - "Run `audit triage USERNAME --portfolio-truth` first." - ) - return - truth = json.loads(truth_path.read_text()) - projects = truth.get("projects", []) - # 0 is the const sentinel meaning "use per-repo next tier" - target = args.suggest_initiatives if args.suggest_initiatives else None - budget = args.llm_budget if args.llm_budget is not None else 0.10 - try: - suggestions, cost = generate_suggestions(projects, target_tier=target, budget_usd=budget) - except BudgetExceededError as exc: - print(f"\nERROR: LLM budget exceeded: {exc}", file=sys.stderr) - return - if not suggestions: - print_info("No suggestions: no repos are close to qualifying for the next tier.") - return - print_info(f"Suggested Initiatives ({len(suggestions)} candidates, ${cost:.4f} spent)") - print() - for s in suggestions: - print( - f" {s.repo_name:<30} {tier_name(s.current_tier)} → {tier_name(s.target_tier):<10} " - f"[{s.estimated_effort}]" - ) - print(f" Missing: {', '.join(s.missing_requirements)}") - print(f" Rationale: {s.rationale}") - print() -def _run_accept_suggestion_mode(args) -> None: - """Accept a suggestion: convert it into a tier-upgrade initiative (Arc G S9.1).""" - import sys - from src.suggest_initiatives import accept_suggestion - output_dir = Path(args.output_dir) - truth_path = truth_latest_path(output_dir) - if not truth_path.exists(): - print_warning( - "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." - ) - return - try: - truth = json.loads(truth_path.read_text()) - except (OSError, json.JSONDecodeError) as exc: - print_warning(f"Failed to read portfolio-truth: {exc}") - return - projects = truth.get("projects", []) - try: - initiative = accept_suggestion( - repo_name=args.accept_suggestion, - projects=projects, - output_dir=output_dir, - deadline=getattr(args, "deadline", None), - target_tier=getattr(args, "target_tier", None), - ) - except ValueError as exc: - print_warning(str(exc)) - sys.exit(2) - print_info( - f"Initiative accepted: {initiative.repo_name} → " - f"Tier {initiative.target_tier} by {initiative.deadline}" - ) -def _run_dismiss_suggestion_mode(args) -> None: - """Dismiss a repo from future LLM-suggested initiatives (Arc G S11.4).""" - import sys - from pathlib import Path - from src.suggest_initiatives import dismiss_suggestion_record, dismissed_path - output_dir = Path(args.output_dir) - try: - entry = dismiss_suggestion_record( - dismissed_path(output_dir), - repo_name=args.dismiss_suggestion, - reason=getattr(args, "reason", "") or "", - expires_days=getattr(args, "dismiss_expires_days", None), - ) - except ValueError as exc: - print_warning(str(exc)) - sys.exit(2) - expiry_note = f" (expires {entry.expires_at})" if entry.expires_at else "" - print_info( - f"✗ Dismissed: {entry.repo_name}" - + (f" — {entry.reason}" if entry.reason else "") - + expiry_note - ) -def _run_undo_dismiss_mode(args) -> None: - """Restore a dismissed repo to the suggestion pool (Arc G S11.4).""" - from pathlib import Path - from src.suggest_initiatives import dismissed_path, undo_dismiss - output_dir = Path(args.output_dir) - removed = undo_dismiss(dismissed_path(output_dir), args.undo_dismiss) - if removed: - print_info(f"✓ Restored: {args.undo_dismiss}") - else: - print_warning(f"{args.undo_dismiss} was not dismissed; nothing to undo") +# ── Core analysis pipeline ──────────────────────────────────────────── -def _run_list_dismissed_mode(args) -> None: - """List all currently dismissed suggestion repos (Arc G S11.4).""" - from pathlib import Path - from src.suggest_initiatives import dismissed_path, load_dismissed - output_dir = Path(args.output_dir) - items = load_dismissed(dismissed_path(output_dir)) - if not items: - print_info("No dismissed suggestions.") - return - print_info(f"Dismissed Suggestions ({len(items)})") - for d in items: - reason = f" — {d.reason}" if d.reason else "" - print(f" {d.repo_name:<30} dismissed {d.dismissed_at[:10]} by {d.dismissed_by}{reason}") +def _run_portfolio_truth_mode(args) -> None: + from src.app.portfolio_truth import run_portfolio_truth_mode -def _run_expire_dismissals_mode(args) -> None: - """Remove dismissals whose expiry date has passed (Arc G S12.1).""" - from pathlib import Path + run_portfolio_truth_mode(args) - from src.suggest_initiatives import dismissed_path, expire_dismissals - output_dir = Path(args.output_dir) - expired = expire_dismissals(dismissed_path(output_dir)) - if not expired: - print_info("No dismissals to expire.") - return - print_info(f"Expired {len(expired)} dismissal(s):") - for d in expired: - print(f" {d.repo_name:<30} (was set to expire {d.expires_at})") +def _run_portfolio_context_recovery_mode(args) -> None: + from src.app.portfolio_truth import run_portfolio_context_recovery_mode + run_portfolio_context_recovery_mode(args) -def _run_dismissal_history_mode(args) -> None: - """Show audit trail of dismissal events (Arc G S12.1).""" - from pathlib import Path - from src.suggest_initiatives import dismissed_path, load_dismissal_events - output_dir = Path(args.output_dir) - events = load_dismissal_events(dismissed_path(output_dir)) - if not events: - print_info("No dismissal history.") - return - print_info(f"Dismissal History ({len(events)} event(s))") - for e in events: - reason = f" — {e.reason}" if e.reason else "" - print(f" {e.occurred_at[:19]} {e.event_type:<10} {e.repo_name:<30} by {e.actor}{reason}") -def _run_tier_gaps_export_mode(args) -> None: - """Dump per-repo tier-gap data as JSON or markdown (Arc G S12.4).""" - from datetime import datetime, timezone - from pathlib import Path - from src.maturity_tiers import compute_tier, tier_gap, tier_name - output_dir = Path(args.output_dir) - truth_path = truth_latest_path(output_dir) - if not truth_path.exists(): - print_warning( - "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." - ) - return - try: - truth = json.loads(truth_path.read_text()) - except (OSError, json.JSONDecodeError) as exc: - print_warning(f"Failed to read portfolio-truth: {exc}") - sys.exit(2) - - projects = truth.get("projects", []) - target_override = getattr(args, "tier_gaps_target", None) - if target_override is not None and target_override not in (2, 3, 4): - print_warning(f"Invalid --tier-gaps-target {target_override}; must be 2, 3, or 4.") - sys.exit(2) - - gaps: list[dict] = [] - for project in projects: - name = (project.get("identity") or {}).get("display_name") or "" - if not name: - continue - current = compute_tier(project) - if current == 0 or current == 4: - continue # no-git or already-Platinum: no next tier - target = target_override if target_override is not None else (current + 1) - if target <= current: - continue # operator's override is below or equal to current - gap = tier_gap(project, target) - gaps.append( - { - "repo_name": name, - "current_tier": current, - "current_tier_name": tier_name(current), - "target_tier": target, - "target_tier_name": tier_name(target), - "missing_requirements": list(gap.missing_requirements), - "requirement_sources": list(gap.requirement_sources), - } - ) - fmt = getattr(args, "format", "json") - if fmt == "markdown": - _print_tier_gaps_markdown(gaps) - else: - envelope = { - "version": 1, - "generated_at": datetime.now(timezone.utc).isoformat(), - "gaps": gaps, - } - print(json.dumps(envelope, indent=2)) - - -def _print_tier_gaps_markdown(gaps: list[dict]) -> None: - """Human-readable tier-gap table (Arc G S12.4).""" - if not gaps: - print_info("No tier gaps to report (all repos either at Platinum or no git).") - return - print_info(f"Tier Gaps ({len(gaps)} repo(s))") - print() - print("| REPO | CURRENT → TARGET | MISSING | SOURCE |") - print("|------|------------------|---------|--------|") - for g in gaps: - missing = ", ".join(g["missing_requirements"]) if g["missing_requirements"] else "—" - sources = ", ".join(g["requirement_sources"]) if g["requirement_sources"] else "—" - print( - f"| {g['repo_name']} | {g['current_tier_name']} → {g['target_tier_name']} | {missing} | {sources} |" - ) -def _run_apply_improvements_mode(args, parser) -> None: - from src.repo_improver import ( - apply_metadata_updates, - apply_readme_updates, - generate_execution_report, - load_improvements, - ) - improvements_file = getattr(args, "improvements_file", None) - apply_readmes = getattr(args, "apply_readmes", False) - apply_metadata = getattr(args, "apply_metadata", False) - # --apply-metadata always needs a file; --apply-readmes can read from ledger instead. - if apply_metadata and not improvements_file: - parser.error("--apply-metadata requires --improvements-file") - if not apply_readmes and not apply_metadata: - parser.error("--apply-metadata / --apply-readmes requires --improvements-file") +# ── Report output orchestration ─────────────────────────────────────── - cache = None if args.no_cache else ResponseCache() - client = GitHubClient(token=args.token, cache=cache) - output_dir = Path(args.output_dir) - dry_run = getattr(args, "dry_run", False) - # Load file-based updates (may be empty if no file supplied) - file_updates: list[dict] = [] - if improvements_file: - file_updates = list(load_improvements(improvements_file).values()) - all_results: list[dict] = [] - if apply_metadata: - results = apply_metadata_updates(client, args.username, file_updates, dry_run=dry_run) - all_results.extend(results) - ok_count = sum( - 1 for r in results for a in r.get("actions", []) if a.get("ok") or a.get("dry_run") - ) - print_info(f"Metadata updates: {ok_count} actions {'previewed' if dry_run else 'applied'}") - - if apply_readmes: - # Build the merged update list: - # 1) file-based packets (if --improvements-file provided) - # 2) approved ledger packets (if any, de-duplicated by repo name) - readme_updates: list[dict] = list(file_updates) - ledger_packets_by_repo: dict[str, object] = {} - - from src.draft_readmes import ( - assemble_readme_from_approved_sections, - load_approved_drafts, - load_approved_sectioned_packets, - mark_draft_applied, - mark_section_packet_applied, - record_draft_apply_failure, - ) - # ── Path A: per-section sub-records (Sprint 8.5) ───────────────────── - sectioned_packets = load_approved_sectioned_packets(output_dir) - sectioned_updates_by_repo: dict[str, tuple[str, str]] = {} # repo → (packet_id, readme) - for pid, sections in sectioned_packets.items(): - repo_name_sec: str = str((sections[0].get("repo_name") or "") if sections else "") - if not repo_name_sec: - continue - assembled = assemble_readme_from_approved_sections(sections) - if assembled is None: - print_info(f"sectioned packet {pid} has no approved sections; skipping") - continue - pending = [s for s in sections if s.get("state", "pending") == "pending"] - if pending: - print_info(f"sectioned packet {pid} has {len(pending)} pending sections; skipping") - continue - sectioned_updates_by_repo[repo_name_sec] = (pid, assembled) - - for repo_name_sec, (pid, assembled_readme) in sectioned_updates_by_repo.items(): - file_names = {(u.get("name") or u.get("repo", "").split("/")[-1]) for u in file_updates} - if repo_name_sec not in file_names: - readme_updates.append({"name": repo_name_sec, "readme": assembled_readme}) - if dry_run: - char_count = len(assembled_readme) - print_info( - f" [dry-run] would push sectioned README to {repo_name_sec}: " - f"{char_count} chars" - ) - - # ── Path B: legacy whole-packet records ─────────────────────────────── - ledger_packets = load_approved_drafts(output_dir, getattr(args, "username", None)) - for pkt in ledger_packets: - # Convert DraftReadmePacket → shape expected by apply_readme_updates - # apply_readme_updates expects: {name: str, readme: str} - # De-duplicate: file-based takes precedence (already present in readme_updates). - file_names = {(u.get("name") or u.get("repo", "").split("/")[-1]) for u in file_updates} - if pkt.repo_name not in file_names: - readme_updates.append({"name": pkt.repo_name, "readme": pkt.proposed_readme}) - ledger_packets_by_repo[pkt.repo_name] = pkt - - if not readme_updates: - print_info("README updates: 0 repos to apply (no file and no approved ledger packets).") - else: - if dry_run: - # Print per-repo preview lines for ledger-sourced packets so the operator - # can see what would be pushed. File-based packets are also covered because - # apply_readme_updates returns {"dry_run": True} records when dry_run=True. - for pkt_repo, _pkt in ledger_packets_by_repo.items(): - upd = next( - ( - u - for u in readme_updates - if (u.get("name") or u.get("repo", "").split("/")[-1]) == pkt_repo - ), - None, - ) - if upd is not None: - char_count = len(upd.get("readme", "")) - print_info( - f" [dry-run] would push README to {pkt_repo}: {char_count} chars" - ) - - results = apply_readme_updates(client, args.username, readme_updates, dry_run=dry_run) - all_results.extend(results) - - # State transitions for ledger-sourced packets (live apply only) - if not dry_run: - for result in results: - repo_name = result.get("repo", "") - # Path A: sectioned packets - if repo_name in sectioned_updates_by_repo: - pid, _assembled = sectioned_updates_by_repo[repo_name] - if result.get("ok"): - mark_section_packet_applied(pid, output_dir) - # Path B: legacy whole-packet records - elif repo_name in ledger_packets_by_repo: - pkt = ledger_packets_by_repo[repo_name] - if result.get("ok"): - mark_draft_applied(output_dir, pkt, apply_result=result) # type: ignore[arg-type] - else: - error_msg = str(result.get("error") or "unknown error") - record_draft_apply_failure(output_dir, pkt, error=error_msg) # type: ignore[arg-type] - - ok_count = sum(1 for r in results if r.get("ok") or r.get("dry_run")) - verb = "previewed" if dry_run else "pushed" - print_info( - f"README updates: {ok_count} repos {verb}" - + ( - f" ({len(ledger_packets_by_repo)} from ledger)" - if ledger_packets_by_repo - else "" - ) - ) - - report_path = generate_execution_report(all_results, output_dir) - print_info(f"Execution report: {report_path}") - - -def _run_main_audit_cycle(args, config_inspection) -> None: - from src.diagnostics import format_preflight_summary, run_diagnostics, should_block_run - - if args.preflight_mode != "off": - preflight = run_diagnostics(args, config_inspection=config_inspection, full=False) - setattr(args, "_preflight_summary", preflight.to_preflight_summary()) - print_info(format_preflight_summary(preflight)) - if preflight.status != "ok": - for check in [item for item in preflight.checks if item.status != "ok"][:5]: - print_warning(f"{check.summary} ({check.category})") - if should_block_run(preflight, args.preflight_mode): - raise SystemExit(1) - - custom_weights, scoring_profile_name = _load_scoring_profile(args.scoring_profile) - - if not args.token: - print_warning( - "No token provided. Only public repos will be fetched.\n" - " Set GITHUB_TOKEN or pass --token for private repo access." - ) - cache = None if args.no_cache else ResponseCache() - client = GitHubClient(token=args.token, cache=cache) - output_dir = Path(args.output_dir) +# ── Partial run modes ───────────────────────────────────────────────── - all_repos, errors = _fetch_repo_metadata(args, client) - total_fetched = len(all_repos) - repos = _filter_repos( - all_repos, - skip_forks=args.skip_forks, - skip_archived=args.skip_archived, - ) - _print_filter_summary(all_repos, repos, args) - if getattr(args, "dry_run", False): - _print_dry_run_summary(repos) - return - if args.repos: - _run_targeted_audit( - args, - client, - output_dir, - all_repos=all_repos, - errors=errors, - custom_weights=custom_weights, - scoring_profile_name=scoring_profile_name, - watch_plan=getattr(args, "_watch_plan", None), - latest_trusted_baseline=getattr(args, "_latest_trusted_watch_baseline", None), - ) - return - if args.incremental: - _run_incremental_audit( - args, - client, - output_dir, - all_repos=all_repos, - errors=errors, - custom_weights=custom_weights, - scoring_profile_name=scoring_profile_name, - watch_plan=getattr(args, "_watch_plan", None), - latest_trusted_baseline=getattr(args, "_latest_trusted_watch_baseline", None), - ) - return - resumed_names: set[str] = set() - resumed_audits: list[RepoAudit] = [] - if getattr(args, "resume", False): - from src.progress import load_progress - - saved = load_progress(output_dir) - if saved: - completed_dicts, _run_meta = saved - for audit_dict in completed_dicts: - try: - resumed_audits.append(_audit_from_dict(audit_dict)) - resumed_names.add(audit_dict.get("metadata", {}).get("name", "")) - except Exception: - # Skip corrupt resume entries and continue with the rest. - pass - if resumed_audits: - print_info(f"Resumed {len(resumed_audits)} previously completed repo(s)") - repos = [r for r in repos if r.name not in resumed_names] - - runtime_stats: dict[str, float] = {} - audits = _analyze_repos( - repos, - args=args, - client=client, - portfolio_lang_freq=_portfolio_lang_freq_for_filtered_baseline(repos), - custom_weights=custom_weights, - runtime_stats=runtime_stats, - ) - all_audits = resumed_audits + audits - - if all_audits: - audits = all_audits - baseline_context = build_baseline_context_from_args( - args, - scoring_profile=scoring_profile_name, - portfolio_baseline_size=len(repos), - ) - report = AuditReport.from_audits( - args.username, - audits, - errors, - total_fetched, - scoring_profile=scoring_profile_name, - run_mode="full", - portfolio_baseline_size=len(repos), - baseline_signature=baseline_context["baseline_signature"], - baseline_context=baseline_context, - ) - report.watch_state = build_watch_state( - args, - scoring_profile=scoring_profile_name, - portfolio_baseline_size=len(repos), - run_mode="full", - watch_plan=getattr(args, "_watch_plan", None), - latest_trusted_baseline=getattr(args, "_latest_trusted_watch_baseline", None), - full_refresh_interval_days=FULL_REFRESH_DAYS, - ) - report.preflight_summary = getattr(args, "_preflight_summary", {}) - report.runtime_breakdown = runtime_stats - _apply_requested_reconciliation(report, args, audits) - outputs = _write_report_outputs(report, args, output_dir, client=client, cache=cache) - _print_output_summary( - f"Audited {report.repos_audited} repos for {report.username}", report, outputs - ) - if getattr(args, "create_issues", False): - from src.issue_creator import create_audit_issues - from src.quick_wins import find_quick_wins - - quick_wins = find_quick_wins(audits) - issue_result = create_audit_issues( - quick_wins, - args.username, - client, - dry_run=getattr(args, "dry_run", False), - ) - print_info( - f"Issues: {len(issue_result['created'])} created, " - f"{len(issue_result['skipped'])} skipped (already exist)" - ) - - if getattr(args, "summary", False) and outputs.get("json_path"): - from src.diff import diff_reports, print_diff_summary - from src.history import find_previous - - prev_path = find_previous(outputs["json_path"].name) - if prev_path: - diff = diff_reports( - prev_path, - outputs["json_path"], - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ) - print_diff_summary(diff) +# ── Scoring profile loader ───────────────────────────────────────────── - return - raw_path = _write_json( - args.username, - repos, - errors, - total_fetched, - output_dir, - ) - print( - f"\n✓ Fetched {total_fetched} repos for {args.username}\n" - f" Included: {len(repos)} | Errors: {len(errors)}\n" - f" Output: {raw_path}", - ) +# ── Dry-run preview ─────────────────────────────────────────────────── -def _run_watch_mode(args, config_inspection) -> None: - from src.recurring_review import choose_watch_plan - from src.watch import run_watch_loop +# ── Semantic index helpers (Arc F S3.1) ─────────────────────────────── - def _run_watch_once() -> None: - watch_plan = choose_watch_plan( - Path(args.output_dir), - args, - scoring_profile=normalize_scoring_profile(args.scoring_profile), - ) - print_info(f"Watch decision: {watch_plan.mode} ({watch_plan.reason})") - original_incremental = args.incremental - original_repos = args.repos - setattr(args, "_watch_plan", watch_plan) - setattr(args, "_latest_trusted_watch_baseline", watch_plan.latest_trusted_baseline) - try: - args.incremental = watch_plan.mode == "incremental" - args.repos = None - _run_main_audit_cycle(args, config_inspection) - finally: - args.incremental = original_incremental - args.repos = original_repos - run_watch_loop(_run_watch_once, interval=args.watch_interval) -def _doctor_next_step_hint(username: str) -> str: - return ( - f"Next step: run `audit {username} --html` for the standard workbook, then " - f"`audit {username} --control-center` for read-only weekly triage." - ) +# ── Serve mode ─────────────────────────────────────────────────────────────── +def _run_serve_mode(args: object) -> None: + from src.app.serve_mode import run_serve_mode + run_serve_mode(args) -def _control_center_next_step_hint() -> str: - return ( - "Reading order: workbook Dashboard -> Run Changes -> Review Queue -> Repo Detail. " - "Move into Action Sync only when the local weekly story is already settled." - ) +# ── Subcommand inference for legacy flat invocation ─────────────────── +def _infer_subcommand_from_flags(args: argparse.Namespace) -> str: + """Return the effective subcommand name for a legacy flat invocation.""" + # triage signals + triage_flags = ( + "control_center", + "approval_center", + "triage_view", + "approve_governance", + "approve_packet", + "review_governance", + "review_packet", + "auto_apply_approved", + "reset_prefs", + "acknowledge_target", + "acknowledge_kind", + "semantic_search", + "ask", + "set_initiative", + "initiatives", + "close_initiative", + ) + for flag in triage_flags: + val = getattr(args, flag, None) + if val and val not in (False, "all", None, ""): + return "triage" + if getattr(args, "approval_center", False) or getattr(args, "control_center", False): + return "triage" -def _normal_audit_next_step_hint(username: str) -> str: - return ( - f"Next step: open the standard workbook first, then run `audit {username} --control-center` " - "for the read-only operator queue." + # report signals + report_flags = ( + "portfolio_truth", + "portfolio_context_recovery", + "apply_context_recovery", + "generate_manifest", + "apply_metadata", + "apply_readmes", + "campaign_from_ledger", + "draft_readmes", + "upload_badges", + "notion_sync", + "tier_gaps", + "tier_recalibration_report", + "context_triage", + "propose_automation", + "list_proposals", + "execute_proposals", ) + for flag in report_flags: + if getattr(args, flag, False): + return "report" + if getattr(args, "campaign", None): + return "report" + if getattr(args, "writeback_target", None): + return "report" + if getattr(args, "approve_proposal", None) or getattr(args, "reject_proposal", None): + return "report" + + return "run" + + +_KNOWN_SUBCOMMANDS: frozenset[str] = frozenset( + {"run", "triage", "report", "serve", "security-burndown", "security-gate"} +) -def _print_control_center_summary(snapshot: dict) -> None: - summary = snapshot.get("operator_summary", {}) - queue = snapshot.get("operator_queue", []) - recent_changes = snapshot.get("operator_recent_changes", []) - print( - f"\nOperator Control Center\n {summary.get('headline', 'No operator triage items are currently surfaced.')}" - ) - if summary.get("report_reference"): - print(f" Latest report: {summary['report_reference']}") - if summary.get("source_run_id"): - print(f" Source run: {summary['source_run_id']}") - if summary.get("next_recommended_run_mode"): - print( - " Next recommended run: " - f"{summary.get('next_recommended_run_mode', 'unknown')}" - f" ({summary.get('watch_decision_summary', 'No watch decision summary available.')})" - ) - if summary.get("watch_strategy"): - print(f" Watch strategy: {summary['watch_strategy']}") - if summary.get("what_changed"): - print(f" What changed: {summary['what_changed']}") - if summary.get("why_it_matters"): - print(f" Why it matters: {summary['why_it_matters']}") - if summary.get("what_to_do_next"): - print(f" What to do next: {summary['what_to_do_next']}") - if summary.get("trend_summary"): - print(f" Trend: {summary['trend_summary']}") - if summary.get("accountability_summary"): - print(f" Accountability: {summary['accountability_summary']}") - primary_target = summary.get("primary_target") or {} - if primary_target: - repo = f"{primary_target.get('repo')}: " if primary_target.get("repo") else "" - print(f" Primary target: {repo}{primary_target.get('title', 'Operator target')}") - if summary.get("primary_target_reason"): - print(f" Why this is the top target: {summary['primary_target_reason']}") - if summary.get("primary_target_done_criteria"): - print(f" What counts as done: {summary['primary_target_done_criteria']}") - if summary.get("closure_guidance"): - print(f" Closure guidance: {summary['closure_guidance']}") - if summary.get("primary_target_last_intervention"): - intervention = summary.get("primary_target_last_intervention") or {} - when = (intervention.get("recorded_at") or "")[:10] - event_type = intervention.get("event_type", "recorded") - outcome = intervention.get("outcome", event_type) - print(f" What we tried: {when} {event_type} ({outcome})".strip()) - if summary.get("primary_target_resolution_evidence"): - print(f" Resolution evidence: {summary['primary_target_resolution_evidence']}") - if summary.get("primary_target_confidence_label"): - print( - " Primary target confidence: " - f"{summary.get('primary_target_confidence_label', 'low')} " - f"({summary.get('primary_target_confidence_score', 0.0):.2f})" - ) - if summary.get("primary_target_confidence_reasons"): - print( - " Confidence reasons: " - + ", ".join(summary.get("primary_target_confidence_reasons") or []) - ) - if summary.get("next_action_confidence_label"): - print( - " Next action confidence: " - f"{summary.get('next_action_confidence_label', 'low')} " - f"({summary.get('next_action_confidence_score', 0.0):.2f})" - ) - if summary.get("primary_target_trust_policy"): - print( - " Trust policy: " - f"{summary.get('primary_target_trust_policy', 'monitor')} " - f"({summary.get('primary_target_trust_policy_reason', 'No trust-policy reason is recorded yet.')})" - ) - if summary.get("adaptive_confidence_summary"): - print(f" Why this confidence is actionable: {summary['adaptive_confidence_summary']}") - if summary.get("primary_target_exception_status") not in {None, "", "none"}: - print( - " Trust policy exception: " - f"{summary.get('primary_target_exception_status', 'none')} " - f"({summary.get('primary_target_exception_reason', 'No trust-policy exception reason is recorded yet.')})" - ) - if summary.get("primary_target_exception_pattern_status") not in {None, "", "none"}: - print( - " Exception pattern learning: " - f"{summary.get('primary_target_exception_pattern_status', 'none')} " - f"({summary.get('primary_target_exception_pattern_reason', 'No exception-pattern reason is recorded yet.')})" - ) - if summary.get("primary_target_trust_recovery_status") not in {None, "", "none"}: - print( - " Trust recovery: " - f"{summary.get('primary_target_trust_recovery_status', 'none')} " - f"({summary.get('primary_target_trust_recovery_reason', 'No trust-recovery reason is recorded yet.')})" - ) - if summary.get("primary_target_recovery_confidence_label"): - print( - " Recovery confidence: " - f"{summary.get('primary_target_recovery_confidence_label', 'low')} " - f"({summary.get('primary_target_recovery_confidence_score', 0.0):.2f})" - ) - if summary.get("recovery_confidence_summary"): - print(f" Recovery confidence summary: {summary['recovery_confidence_summary']}") - if summary.get("primary_target_exception_retirement_status") not in {None, "", "none"}: - print( - " Exception retirement: " - f"{summary.get('primary_target_exception_retirement_status', 'none')} " - f"({summary.get('primary_target_exception_retirement_reason', 'No exception-retirement reason is recorded yet.')})" - ) - if summary.get("primary_target_policy_debt_status") not in {None, "", "none"}: - print( - " Policy debt cleanup: " - f"{summary.get('primary_target_policy_debt_status', 'none')} " - f"({summary.get('primary_target_policy_debt_reason', 'No policy-debt reason is recorded yet.')})" - ) - if summary.get("primary_target_class_normalization_status") not in {None, "", "none"}: - print( - " Class-level trust normalization: " - f"{summary.get('primary_target_class_normalization_status', 'none')} " - f"({summary.get('primary_target_class_normalization_reason', 'No class-normalization reason is recorded yet.')})" - ) - if summary.get("primary_target_class_memory_freshness_status"): - print( - " Class memory freshness: " - f"{summary.get('primary_target_class_memory_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_class_memory_freshness_reason', 'No class-memory freshness reason is recorded yet.')})" - ) - if summary.get("primary_target_class_decay_status") is not None: - print( - " Trust decay controls: " - f"{summary.get('primary_target_class_decay_status', 'none')} " - f"({summary.get('primary_target_class_decay_reason', 'No class-decay reason is recorded yet.')})" - ) - if summary.get("primary_target_transition_closure_confidence_label"): - print( - " Transition closure confidence: " - f"{summary.get('primary_target_transition_closure_confidence_label', 'low')} " - f"({summary.get('primary_target_transition_closure_confidence_score', 0.0):.2f}; " - f"{summary.get('primary_target_transition_closure_likely_outcome', 'none')})" - ) - if summary.get("transition_closure_confidence_summary"): - print(f" Transition closure summary: {summary['transition_closure_confidence_summary']}") - if summary.get("primary_target_class_pending_debt_status") not in {None, "", "none"}: - print( - " Class pending debt audit: " - f"{summary.get('primary_target_class_pending_debt_status', 'none')} " - f"({summary.get('primary_target_class_pending_debt_reason', 'No class pending-debt reason is recorded yet.')})" - ) - if summary.get("class_pending_debt_summary"): - print(f" Class pending debt summary: {summary['class_pending_debt_summary']}") - if summary.get("class_pending_resolution_summary"): - print(f" Class pending resolution summary: {summary['class_pending_resolution_summary']}") - if summary.get("primary_target_pending_debt_freshness_status"): - print( - " Pending debt freshness: " - f"{summary.get('primary_target_pending_debt_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_pending_debt_freshness_reason', 'No pending-debt freshness reason is recorded yet.')})" - ) - if summary.get("pending_debt_freshness_summary"): - print(f" Pending debt freshness summary: {summary['pending_debt_freshness_summary']}") - if summary.get("pending_debt_decay_summary"): - print(f" Pending debt decay summary: {summary['pending_debt_decay_summary']}") - if summary.get("primary_target_closure_forecast_reweight_direction"): - print( - " Closure forecast reweighting: " - f"{summary.get('primary_target_closure_forecast_reweight_direction', 'neutral')} " - f"({summary.get('primary_target_closure_forecast_reweight_score', 0.0):.2f})" - ) - if summary.get("closure_forecast_reweighting_summary"): - print( - f" Closure forecast reweighting summary: {summary['closure_forecast_reweighting_summary']}" - ) - if summary.get("primary_target_closure_forecast_momentum_status"): - print( - " Closure forecast momentum: " - f"{summary.get('primary_target_closure_forecast_momentum_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_momentum_score', 0.0):.2f})" - ) - if summary.get("closure_forecast_momentum_summary"): - print( - f" Closure forecast momentum summary: {summary['closure_forecast_momentum_summary']}" - ) - if summary.get("primary_target_closure_forecast_freshness_status"): - print( - " Closure forecast freshness: " - f"{summary.get('primary_target_closure_forecast_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_freshness_reason', 'No closure-forecast freshness reason is recorded yet.')})" - ) - if summary.get("closure_forecast_freshness_summary"): - print( - f" Closure forecast freshness summary: {summary['closure_forecast_freshness_summary']}" - ) - if summary.get("primary_target_closure_forecast_stability_status"): - print( - " Closure forecast hysteresis: " - f"{summary.get('primary_target_closure_forecast_stability_status', 'watch')} " - f"({summary.get('primary_target_closure_forecast_hysteresis_status', 'none')}: " - f"{summary.get('primary_target_closure_forecast_hysteresis_reason', 'No closure-forecast hysteresis reason is recorded yet.')})" - ) - if summary.get("closure_forecast_hysteresis_summary"): - print( - f" Closure forecast hysteresis summary: {summary['closure_forecast_hysteresis_summary']}" - ) - if summary.get("primary_target_closure_forecast_decay_status") not in {None, "", "none"}: - print( - " Hysteresis decay controls: " - f"{summary.get('primary_target_closure_forecast_decay_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_decay_reason', 'No closure-forecast decay reason is recorded yet.')})" - ) - if summary.get("closure_forecast_decay_summary"): - print(f" Closure forecast decay summary: {summary['closure_forecast_decay_summary']}") - if summary.get("primary_target_closure_forecast_refresh_recovery_status") not in { - None, - "", - "none", - }: - print( - " Closure forecast refresh recovery: " - f"{summary.get('primary_target_closure_forecast_refresh_recovery_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_refresh_recovery_score', 0.0):.2f})" - ) - if summary.get("closure_forecast_refresh_recovery_summary"): - print( - f" Closure forecast refresh recovery summary: {summary['closure_forecast_refresh_recovery_summary']}" - ) - if summary.get("primary_target_closure_forecast_reacquisition_status") not in { - None, - "", - "none", - }: - print( - " Reacquisition controls: " - f"{summary.get('primary_target_closure_forecast_reacquisition_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reacquisition_reason', 'No closure-forecast reacquisition reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reacquisition_summary"): - print( - f" Closure forecast reacquisition summary: {summary['closure_forecast_reacquisition_summary']}" - ) - if summary.get("primary_target_closure_forecast_reacquisition_persistence_status") not in { - None, - "", - "none", - }: - print( - " Reacquisition persistence: " - f"{summary.get('primary_target_closure_forecast_reacquisition_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reacquisition_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reacquisition_age_runs', 0)} run(s))" - ) - if summary.get("closure_forecast_reacquisition_persistence_summary"): - print( - f" Reacquisition persistence summary: {summary['closure_forecast_reacquisition_persistence_summary']}" - ) - if summary.get("primary_target_closure_forecast_recovery_churn_status") not in { - None, - "", - "none", - }: - print( - " Recovery churn controls: " - f"{summary.get('primary_target_closure_forecast_recovery_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_recovery_churn_reason', 'No recovery-churn reason is recorded yet.')})" - ) - if summary.get("closure_forecast_recovery_churn_summary"): - print(f" Recovery churn summary: {summary['closure_forecast_recovery_churn_summary']}") - if summary.get("primary_target_closure_forecast_reacquisition_freshness_status") not in { - None, - "", - "insufficient-data", - }: - print( - " Reacquisition freshness: " - f"{summary.get('primary_target_closure_forecast_reacquisition_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_reacquisition_freshness_reason', 'No reacquisition-freshness reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reacquisition_freshness_summary"): - print( - f" Reacquisition freshness summary: {summary['closure_forecast_reacquisition_freshness_summary']}" - ) - if summary.get("primary_target_closure_forecast_persistence_reset_status") not in { - None, - "", - "none", - }: - print( - " Persistence reset controls: " - f"{summary.get('primary_target_closure_forecast_persistence_reset_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_persistence_reset_reason', 'No persistence-reset reason is recorded yet.')})" - ) - if summary.get("closure_forecast_persistence_reset_summary"): - print( - f" Persistence reset summary: {summary['closure_forecast_persistence_reset_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_refresh_recovery_status") not in { - None, - "", - "none", - }: - print( - " Reset refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_refresh_recovery_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_refresh_recovery_score', 0.0):.2f})" - ) - if summary.get("closure_forecast_reset_refresh_recovery_summary"): - print( - f" Reset refresh recovery summary: {summary['closure_forecast_reset_refresh_recovery_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_reason', 'No reset re-entry reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_summary"): - print(f" Reset re-entry summary: {summary['closure_forecast_reset_reentry_summary']}") - if summary.get("primary_target_closure_forecast_reset_reentry_persistence_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry persistence: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reset_reentry_age_runs', 0)} run(s))" - ) - if summary.get("closure_forecast_reset_reentry_persistence_summary"): - print( - " Reset re-entry persistence summary: " - f"{summary['closure_forecast_reset_reentry_persistence_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_churn_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry churn controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_churn_reason', 'No reset re-entry churn reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_churn_summary"): - print( - " Reset re-entry churn summary: " - f"{summary['closure_forecast_reset_reentry_churn_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_freshness_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry freshness: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_freshness_reason', 'No reset re-entry freshness reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_freshness_summary"): - print( - " Reset re-entry freshness summary: " - f"{summary['closure_forecast_reset_reentry_freshness_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_reset_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry reset controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_reset_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_reset_reason', 'No reset re-entry reset reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_reset_summary"): - print( - " Reset re-entry reset summary: " - f"{summary['closure_forecast_reset_reentry_reset_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_refresh_recovery_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_refresh_recovery_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_refresh_recovery_score', 0.0):.2f})" - ) - if summary.get("closure_forecast_reset_reentry_refresh_recovery_summary"): - print( - " Reset re-entry refresh recovery summary: " - f"{summary['closure_forecast_reset_reentry_refresh_recovery_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry rebuild controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reason', 'No reset re-entry rebuild reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_summary"): - print( - " Reset re-entry rebuild summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_freshness_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild freshness: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_freshness_reason', 'No reset re-entry rebuild freshness reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_freshness_summary"): - print( - " Reset re-entry rebuild freshness summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_freshness_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_reset_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry rebuild reset controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reset_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reset_reason', 'No reset re-entry rebuild reset reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reset_summary"): - print( - " Reset re-entry rebuild reset summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reset_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_score', 0.0):.2f})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_refresh_recovery_summary"): - print( - " Reset re-entry rebuild refresh recovery summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_refresh_recovery_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_reentry_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry rebuild re-entry controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_reason', 'No reset re-entry rebuild re-entry reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_summary"): - print( - " Reset re-entry rebuild re-entry summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_persistence_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry persistence: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_age_runs', 0)} run(s))" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_summary"): - print( - " Reset re-entry rebuild re-entry persistence summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_persistence_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry churn controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_reason', 'No reset re-entry rebuild re-entry churn reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_churn_summary"): - print( - " Reset re-entry rebuild re-entry churn summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_churn_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_freshness_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry freshness: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_freshness_reason', 'No reset re-entry rebuild re-entry freshness reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_freshness_summary"): - print( - " Reset re-entry rebuild re-entry freshness summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_freshness_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_reset_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry reset controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_reset_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_reset_reason', 'No reset re-entry rebuild re-entry reset reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_reset_summary"): - print( - " Reset re-entry rebuild re-entry reset summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_reset_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status', 'none')} " - f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary', 'No reset re-entry rebuild re-entry refresh recovery summary is recorded yet.')})" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reason', 'No reset re-entry rebuild re-entry restore reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_summary"): - print( - " Reset re-entry rebuild re-entry restore summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status" - ) not in {None, "", "insufficient-data"}: - print( - " Reset re-entry rebuild re-entry restore freshness: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_reason', 'No reset re-entry rebuild re-entry restore freshness reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_summary"): - print( - " Reset re-entry rebuild re-entry restore freshness summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore reset controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reset_reason', 'No reset re-entry rebuild re-entry restore reset reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reset_summary"): - print( - " Reset re-entry rebuild re-entry restore reset summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_reset_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status', 'none')} " - f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_summary', 'No reset re-entry rebuild re-entry restore refresh recovery summary is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_summary" - ): - print( - " Reset re-entry rebuild re-entry restore refresh recovery summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-restore controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason', 'No reset re-entry rebuild re-entry restore re-restore reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_summary"): - print( - " Reset re-entry rebuild re-entry restore re-restore summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-restore persistence: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_age_runs', 0)} run(s))" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-restore persistence summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-restore churn controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_reason', 'No reset re-entry rebuild re-entry restore re-restore churn reason is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-restore churn summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status" - ) not in {None, "", "insufficient-data"}: - print( - " Reset re-entry rebuild re-entry restore re-restore freshness: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status', 'insufficient-data')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_reason', 'No reset re-entry rebuild re-entry restore re-restore freshness reason is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-restore freshness summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-restore reset controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_reason', 'No reset re-entry rebuild re-entry restore re-restore reset reason is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-restore reset summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-restore refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status', 'none')} " - f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_summary', 'No reset re-entry rebuild re-entry restore re-restore refresh recovery summary is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-restore refresh recovery summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-restore controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason', 'No reset re-entry rebuild re-entry restore re-re-restore reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_summary"): - print( - " Reset re-entry rebuild re-entry restore re-re-restore summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-restore persistence: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs', 0)} run(s))" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-re-restore persistence summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-restore churn controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason', 'No reset re-entry rebuild re-entry restore re-re-restore churn reason is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-re-restore churn summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-restore refresh recovery: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status', 'none')} " - f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary', 'No reset re-entry rebuild re-entry restore re-re-restore refresh recovery summary is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-re-restore refresh recovery summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-re-restore controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_reason', 'No reset re-entry rebuild re-entry restore re-re-re-restore reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary"): - print( - " Reset re-entry rebuild re-entry restore re-re-re-restore summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-re-restore persistence: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs', 0)} run(s))" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-re-re-restore persistence summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild re-entry restore re-re-re-restore churn controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason', 'No reset re-entry rebuild re-entry restore re-re-re-restore churn reason is recorded yet.')})" - ) - if summary.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary" - ): - print( - " Reset re-entry rebuild re-entry restore re-re-re-restore churn summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary']}" - ) - if summary.get( - "primary_target_closure_forecast_reset_reentry_rebuild_persistence_status" - ) not in {None, "", "none"}: - print( - " Reset re-entry rebuild persistence: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_persistence_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_persistence_score', 0.0):.2f}; " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_age_runs', 0)} run(s))" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_persistence_summary"): - print( - " Reset re-entry rebuild persistence summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_persistence_summary']}" - ) - if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_churn_status") not in { - None, - "", - "none", - }: - print( - " Reset re-entry rebuild churn controls: " - f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_churn_status', 'none')} " - f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_churn_reason', 'No reset re-entry rebuild churn reason is recorded yet.')})" - ) - if summary.get("closure_forecast_reset_reentry_rebuild_churn_summary"): - print( - " Reset re-entry rebuild churn summary: " - f"{summary['closure_forecast_reset_reentry_rebuild_churn_summary']}" - ) - if summary.get("recommendation_drift_status"): - print( - " Recommendation drift: " - f"{summary.get('recommendation_drift_status', 'stable')} " - f"({summary.get('recommendation_drift_summary', 'No recommendation-drift summary is recorded yet.')})" - ) - if summary.get("exception_pattern_summary"): - print(f" Exception pattern summary: {summary['exception_pattern_summary']}") - if summary.get("exception_retirement_summary"): - print(f" Exception retirement summary: {summary['exception_retirement_summary']}") - if summary.get("policy_debt_summary"): - print(f" Policy debt summary: {summary['policy_debt_summary']}") - if summary.get("trust_normalization_summary"): - print(f" Trust normalization summary: {summary['trust_normalization_summary']}") - if summary.get("class_memory_summary"): - print(f" Class memory summary: {summary['class_memory_summary']}") - if summary.get("class_decay_summary"): - print(f" Class decay summary: {summary['class_decay_summary']}") - if summary.get("recommendation_quality_summary"): - print(f" Recommendation quality: {summary['recommendation_quality_summary']}") - if summary.get("confidence_validation_status"): - print( - " Confidence validation: " - f"{summary.get('confidence_validation_status', 'insufficient-data')} " - f"({summary.get('confidence_calibration_summary', 'No confidence-calibration summary is recorded yet.')})" - ) - if summary.get("recent_validation_outcomes"): - recent_bits = [] - for item in (summary.get("recent_validation_outcomes") or [])[:3]: - recent_bits.append( - f"{item.get('target_label', 'Operator target')} " - f"[{item.get('confidence_label', 'low')}] -> {str(item.get('outcome', 'unresolved')).replace('_', ' ')}" - ) - print(" Recent confidence outcomes: " + "; ".join(recent_bits)) - if summary.get("follow_through_summary"): - print(f" Follow-through: {summary['follow_through_summary']}") - lane_labels = [ - ("blocked", "Blocked"), - ("urgent", "Needs Attention Now"), - ("ready", "Ready for Manual Action"), - ("deferred", "Safe to Defer"), - ] - for lane, label in lane_labels: - lane_items = [item for item in queue if item.get("lane") == lane] - items = [item for item in lane_items if _should_print_control_center_item(item)] - if not items: - continue - print(f"\n{label}") - for item in items[:8]: - repo = f"{item['repo']}: " if item.get("repo") else "" - print(f" - {repo}{item.get('title', 'Triage item')}") - print(f" {item.get('summary', '')}") - print(f" Why: {item.get('lane_reason', item.get('lane_label', ''))}") - print(f" Next: {item.get('recommended_action', '')}") - if item.get("catalog_line"): - print(f" Catalog: {item.get('catalog_line')}") - if item.get("intent_alignment"): - print( - " Intent alignment: " - f"{item.get('intent_alignment')} ({item.get('intent_alignment_reason', 'No alignment reason is recorded yet.')})" - ) - omitted_count = len(lane_items) - len(items) - if omitted_count > 0: - print(f" ({omitted_count} experiment/manual-only item(s) hidden from default view.)") - if recent_changes: - print("\nRecently Changed") - for item in recent_changes[:5]: - subject = ( - item.get("repo") or item.get("repo_full_name") or item.get("item_id") or "portfolio" - ) - print( - f" - {item.get('generated_at', '')[:10]} {subject}: {item.get('summary', item.get('kind', 'change'))}" - ) - - -def _should_print_control_center_item(item: dict) -> bool: - catalog = item.get("portfolio_catalog") or {} - lifecycle = str(catalog.get("lifecycle_state") or "").strip().lower() - intended = str(catalog.get("intended_disposition") or "").strip().lower() - program = str(catalog.get("maturity_program") or "").strip().lower() - operating_path = str(item.get("operating_path") or catalog.get("operating_path") or "").strip().lower() - if lifecycle in {"archived", "archive"}: - return False - if intended == "archive" or program == "archive" or operating_path == "archive": - return False - if lifecycle in {"experiment", "experimental"}: - return False - if intended == "experiment" or program == "experiment" or operating_path == "experiment": - return False - return True - - -def _filter_control_center_snapshot_for_default_view(snapshot: dict) -> dict: - queue = snapshot.get("operator_queue") - if not isinstance(queue, list): - return snapshot - snapshot["operator_queue"] = [ - item - for item in queue - if isinstance(item, dict) and _should_print_control_center_item(item) - ] - return snapshot - - -def _fetch_repo_metadata(args, client: GitHubClient) -> tuple[list[RepoMetadata], list[dict]]: - if args.graphql and args.token: - from src.graphql_client import bulk_fetch_repos - - print_info("Using GraphQL bulk fetch...") - raw_repos = bulk_fetch_repos(args.username, args.token) - all_repos: list[RepoMetadata] = [] - errors: list[dict] = [] - for repo_data in raw_repos: - try: - langs = repo_data.pop("_languages", {}) - repo_data.pop("_releases", None) - meta = RepoMetadata.from_api_response(repo_data, languages=langs) - all_repos.append(meta) - except Exception as exc: - errors.append({"repo": repo_data.get("full_name", "?"), "error": str(exc)}) - print_info(f"GraphQL: {len(all_repos)} repos fetched") - return all_repos, errors - - return client.get_repo_metadata(args.username) - - -def _print_filter_summary(all_repos: list[RepoMetadata], repos: list[RepoMetadata], args) -> None: - forks_excluded = sum(1 for r in all_repos if r.fork) if args.skip_forks else 0 - archived_excluded = sum(1 for r in all_repos if r.archived) if args.skip_archived else 0 - skipped = len(all_repos) - len(repos) - if skipped: - parts = [] - if forks_excluded: - parts.append(f"{forks_excluded} forks") - if archived_excluded: - parts.append(f"{archived_excluded} archived") - print_info(f"Filtered out {skipped} repos ({', '.join(parts) or 'forks/archived'})") - - -def _compute_portfolio_lang_freq(repos: list[RepoMetadata]) -> dict[str, float]: - lang_counts = Counter(repo.language for repo in repos if repo.language) - return {lang: count / len(repos) for lang, count in lang_counts.items()} if repos else {} - - -def _portfolio_lang_freq_for_filtered_baseline(repos: list[RepoMetadata]) -> dict[str, float]: - """Compute novelty baseline from the full filtered portfolio, never only the rerun subset.""" - return _compute_portfolio_lang_freq(repos) - - -def _analysis_worker_count(args) -> int: - """Return the bounded repo-analysis worker count for this run.""" - raw_value = getattr(args, "analysis_workers", None) - if raw_value is None: - raw_value = os.environ.get("GITHUB_REPO_AUDITOR_ANALYSIS_WORKERS") - - if raw_value in {None, ""}: - return DEFAULT_ANALYSIS_WORKERS - - try: - requested = int(raw_value) - except (TypeError, ValueError): - print_warning("Invalid analysis worker count; using the reliable single-worker default.") - return DEFAULT_ANALYSIS_WORKERS - - if requested < 1: - print_warning( - "Analysis worker count must be at least 1; using the reliable single-worker default." - ) - return DEFAULT_ANALYSIS_WORKERS - - if requested > MAX_ANALYSIS_WORKERS: - print_warning( - f"Analysis worker count capped at {MAX_ANALYSIS_WORKERS} to avoid GitHub API stalls." - ) - return MAX_ANALYSIS_WORKERS - - return requested - - -def _use_analysis_progress(workers: int) -> bool: - """Use rich progress only when it can render visibly for the operator.""" - return workers > 1 and sys.stderr.isatty() - - -def _use_analyzer_cache(args, workers: int) -> bool: - """Use the SQLite analyzer cache only for single-worker analysis.""" - return not getattr(args, "no_analyzer_cache", False) and workers == 1 - - -def _select_target_repos( - target_names: list[str], repos: list[RepoMetadata] -) -> tuple[list[RepoMetadata], list[str]]: - exact = {repo.name: repo for repo in repos} - lower = {repo.name.lower(): repo for repo in repos} - selected: list[RepoMetadata] = [] - missing: list[str] = [] - - for name in target_names: - repo = exact.get(name) or lower.get(name.lower()) - if repo: - selected.append(repo) - else: - missing.append(name) - - return selected, missing - - -# ── Core analysis pipeline ──────────────────────────────────────────── -def _analyze_repos( - repos: list[RepoMetadata], - *, - args, - client: GitHubClient, - portfolio_lang_freq: dict[str, float], - custom_weights: dict[str, float] | None, - runtime_stats: dict | None = None, -) -> list[RepoAudit]: - from src.analyzers import load_custom_analyzers - - if args.skip_clone: - print_warning("Audit modes that score repos do not support --skip-clone.") - return [] - - extra_analyzers = [] - if getattr(args, "analyzers_dir", None): - extra_analyzers = load_custom_analyzers(Path(args.analyzers_dir)) - if extra_analyzers: - print_info( - f"Loaded {len(extra_analyzers)} custom analyzer(s) from {args.analyzers_dir}" - ) - - audits: list[RepoAudit] = [] - requested_workers = _analysis_worker_count(args) - - # Open a warehouse connection for the analyzer result cache unless disabled. - _warehouse_conn = None - if not _use_analyzer_cache(args, requested_workers): - if requested_workers > 1 and not getattr(args, "no_analyzer_cache", False): - print_warning( - "Analyzer result cache disabled for parallel analysis; " - "rerun with one analysis worker to use the SQLite cache." - ) - else: - import sqlite3 as _sqlite3 - - from src.warehouse import WAREHOUSE_FILENAME - from src.warehouse import _ensure_schema as _warehouse_ensure_schema - - _output_dir = Path(getattr(args, "output_dir", "output")) - _db_path = _output_dir / WAREHOUSE_FILENAME - try: - _output_dir.mkdir(parents=True, exist_ok=True) - _warehouse_conn = _sqlite3.connect(str(_db_path)) - _warehouse_ensure_schema(_warehouse_conn) - except Exception as _cache_err: - print_warning(f"Could not open warehouse for analyzer cache: {_cache_err}") - _warehouse_conn = None - - def _analyze_one(repo_meta: RepoMetadata, repo_path: Path) -> RepoAudit: - worker_client = GitHubClient(token=client.token, cache=client.cache) - _commit_sha = repo_meta.pushed_at.isoformat() if repo_meta.pushed_at else "" - results = run_all_analyzers( - repo_path, - repo_meta, - worker_client, - extra_analyzers=extra_analyzers, - conn=_warehouse_conn, - commit_sha=_commit_sha, - sbom_source=getattr(args, "sbom_source", "lockfile"), - ) - return score_repo( - repo_meta, - results, - repo_path=repo_path, - portfolio_lang_freq=portfolio_lang_freq, - custom_weights=custom_weights, - github_client=worker_client, - scorecard_enabled=args.scorecard, - security_offline=args.security_offline, - ) - - # ── Optional async enrichment prefetch ─────────────────────────────────── - _fetch_mode: str = getattr(args, "fetch_mode", "sync") - if _fetch_mode == "async" and repos: - from src.github_client_async import fetch_enrichment_sync as _async_prefetch - - _fetch_workers: int = max(1, getattr(args, "fetch_workers", 10)) - print_info( - f"Pre-fetching enrichment for {len(repos)} repos " - f"(async, concurrency={_fetch_workers})..." - ) - _prefetch_start = perf_counter() - try: - _repo_pairs = [(r.full_name.split("/")[0], r.name) for r in repos if "/" in r.full_name] - _async_prefetch( - _repo_pairs, - token=client.token, - max_concurrency=_fetch_workers, - cache=client.cache, - ) - _prefetch_elapsed = perf_counter() - _prefetch_start - print_info(f"Async enrichment prefetch complete in {_prefetch_elapsed:.1f}s.") - if runtime_stats is not None: - runtime_stats["async_prefetch_seconds"] = round(_prefetch_elapsed, 3) - except Exception as _prefetch_err: - print_warning( - f"Async enrichment prefetch failed ({_prefetch_err!r}); " - "falling back to per-repo sync fetch." - ) - - _reconcile_diverged: bool = False - clone_start = perf_counter() - with clone_workspace( - repos, - token=args.token, - on_progress=lambda i, t, n: None, - on_error=lambda n, m: print_warning(f"Failed to clone {n}"), - ) as cloned: - clone_seconds = perf_counter() - clone_start - if runtime_stats is not None: - runtime_stats["clone_fetch_seconds"] = round(clone_seconds, 3) - print_info(f"Cloned {len(cloned)}/{len(repos)} repos. Analyzing...") - analyzable = [ - (index, repo_meta, cloned.get(repo_meta.name)) for index, repo_meta in enumerate(repos) - ] - analyzable = [ - (index, repo_meta, repo_path) for index, repo_meta, repo_path in analyzable if repo_path - ] - workers = min(requested_workers, max(1, len(analyzable))) - if workers == 1: - print_info("Analyzing with 1 worker for reliable full-audit progress.") - else: - print_info(f"Analyzing with {workers} workers.") - progress = create_progress() if _use_analysis_progress(workers) else None - analyze_start = perf_counter() - if progress: - with progress: - task = progress.add_task("Analyzing", total=len(repos)) - completed: dict[int, RepoAudit] = {} - skipped = len(repos) - len(analyzable) - for _ in range(skipped): - progress.advance(task) - if workers == 1: - for index, repo_meta, repo_path in analyzable: - progress.update(task, description=f"Analyzing {repo_meta.name}") - completed[index] = _analyze_one(repo_meta, repo_path) - if args.verbose: - _print_verbose(completed[index]) - progress.advance(task) - else: - with ThreadPoolExecutor(max_workers=workers) as executor: - futures = { - executor.submit(_analyze_one, repo_meta, repo_path): ( - index, - repo_meta.name, - ) - for index, repo_meta, repo_path in analyzable - } - for future in as_completed(futures): - index, repo_name = futures[future] - progress.update(task, description=f"Analyzing {repo_name}") - completed[index] = future.result() - if args.verbose: - _print_verbose(completed[index]) - progress.advance(task) - audits.extend(completed[index] for index in sorted(completed)) - else: - completed: dict[int, RepoAudit] = {} - if workers == 1: - for index, repo_meta, repo_path in analyzable: - print( - f" [{index + 1}/{len(repos)}] Analyzing {repo_meta.name}...", - file=sys.stderr, - ) - completed[index] = _analyze_one(repo_meta, repo_path) - if args.verbose: - _print_verbose(completed[index]) - else: - with ThreadPoolExecutor(max_workers=workers) as executor: - futures = { - executor.submit(_analyze_one, repo_meta, repo_path): (index, repo_meta.name) - for index, repo_meta, repo_path in analyzable - } - finished = 0 - for future in as_completed(futures): - index, repo_name = futures[future] - finished += 1 - print( - f" [{finished}/{len(analyzable)}] Analyzing {repo_name}...", - file=sys.stderr, - ) - completed[index] = future.result() - if args.verbose: - _print_verbose(completed[index]) - audits.extend(completed[index] for index in sorted(completed)) - if runtime_stats is not None: - runtime_stats["analyzer_seconds"] = round(perf_counter() - analyze_start, 3) - - # ── Cache reconcile gate ────────────────────────────────────────────── - _do_reconcile: bool = getattr(args, "reconcile_cache", False) - if _do_reconcile and _warehouse_conn is not None and audits: - from src.analyzer_cache import reconcile as _cache_reconcile - from src.analyzers import run_all_analyzers as _run_all - - _repo_path_map: dict[str, object] = { - repo_meta.name: cloned.get(repo_meta.name) for repo_meta in repos - } - _repo_meta_map: dict[str, object] = {repo_meta.name: repo_meta for repo_meta in repos} - _sha_map: dict[str, str] = { - repo_meta.name: (repo_meta.pushed_at.isoformat() if repo_meta.pushed_at else "") - for repo_meta in repos - } - - def _fresh_run(repo_path, meta, conn=None): - return _run_all( - repo_path, - meta, - conn=None, - commit_sha="", - sbom_source=getattr(args, "sbom_source", "lockfile"), - ) - - _reconcile_report = _cache_reconcile( - _repo_path_map, - _repo_meta_map, - _warehouse_conn, - _fresh_run, - commit_sha_map=_sha_map, - ) - _checked = _reconcile_report["checked"] - _matched = _reconcile_report["matched"] - _divergent = _reconcile_report["divergent"] - print_info( - f"Cache reconcile: {_matched}/{_checked} matched, {len(_divergent)} divergent" - ) - if _divergent: - _reconcile_diverged = True - for _entry in _divergent: - print_warning( - f" DIVERGE {_entry['repo']} {_entry['analyzer']}: {_entry['diff_summary']}" - ) - _output_dir_r = Path(getattr(args, "output_dir", "output")) - _output_dir_r.mkdir(parents=True, exist_ok=True) - import datetime as _dt - import json as _json - - _stamp = _dt.date.today().isoformat() - _report_path = _output_dir_r / f"cache-reconcile-{args.username}-{_stamp}.json" - try: - _report_path.write_text( - _json.dumps(_reconcile_report, indent=2), encoding="utf-8" - ) - print_warning(f" Full divergence report: {_report_path}") - except Exception as _write_err: - print_warning(f"Could not write reconcile report: {_write_err}") - - print_info("Clones cleaned up") - if _warehouse_conn is not None: - try: - _warehouse_conn.close() - except Exception: - # Warehouse close failures are non-actionable during final cleanup. - pass - if _reconcile_diverged: - sys.exit(1) - return audits - - -def _apply_requested_reconciliation(report: AuditReport, args, audits: list[RepoAudit]) -> None: - if args.registry: - from src.registry_parser import parse_registry, reconcile, sync_new_repos - - registry = parse_registry(args.registry) - report.reconciliation = reconcile(registry, audits) - print_info( - f"Registry: {report.reconciliation.registry_total} projects, " - f"{len(report.reconciliation.matched)} matched" - ) - if args.sync_registry and report.reconciliation.on_github_not_registry: - added = sync_new_repos( - args.registry, - report.reconciliation.on_github_not_registry, - audits, - ) - if added: - print_info( - f"Synced {len(added)} repos to registry: {', '.join(added[:5])}" - + (f"... (+{len(added) - 5})" if len(added) > 5 else "") - ) - return - - if args.notion_registry: - from src.notion_registry import load_notion_registry - from src.registry_parser import reconcile - - notion_projects = load_notion_registry(Path("config")) - if notion_projects: - report.reconciliation = reconcile(notion_projects, audits) - print_info( - f"Notion registry: {len(notion_projects)} projects, " - f"{len(report.reconciliation.matched)} matched" - ) - - -def _run_auto_apply_approved_mode(args, output_dir: Path) -> None: - """Apply approved campaign packets for repos that pass the automation trust bar.""" - from src.approval_ledger import load_approval_ledger_bundle - from src.auto_apply import ( - build_trust_bar_index, - filter_safe_actions, - filter_trusted_repo_actions, - get_approved_manual_campaigns, - summarize_trust_bar, - ) - from src.github_client import GitHubClient - from src.ops_writeback import ( - apply_github_writeback, - build_campaign_bundle, - summarize_writeback_results, - ) - from src.warehouse import load_latest_campaign_state - - cache = None if getattr(args, "no_cache", False) else None - client: GitHubClient | None = ( - GitHubClient(token=args.token, cache=cache) if getattr(args, "token", None) else None - ) - - try: - _report_path, _diff_dict, report = _refresh_latest_report_state(output_dir, args) - except FileNotFoundError: - print_info("No existing audit report found in output directory. Run a normal audit first.") - return - - truth_path = truth_latest_path(output_dir) - if not truth_path.exists(): - print_info("No portfolio truth snapshot found. Run --portfolio-truth first.") - return - - truth_snapshot = json.loads(truth_path.read_text()) - decision_quality_status = ( - (report.operator_summary or {}) - .get("decision_quality_v1", {}) - .get("decision_quality_status", "") - ) - trust_bar_index = build_trust_bar_index(truth_snapshot, decision_quality_status) - trust_bar_summary = summarize_trust_bar(truth_snapshot, decision_quality_status) - print_info( - "Automation trust bar: " - f"{trust_bar_summary['automation_eligible_count']} opted-in repos; " - f"{trust_bar_summary['baseline_eligible_count']} baseline opted-in repos; " - f"{trust_bar_summary['trusted_repo_count']} repos pass the full trust bar " - f"(decision quality: {trust_bar_summary['decision_quality_status']})." - ) - if trust_bar_summary["automation_eligible_repos"]: - print_info( - "Automation-eligible repos: " - + ", ".join(trust_bar_summary["automation_eligible_repos"]) - ) - - bundle = load_approval_ledger_bundle( - output_dir, - report.to_dict(), - list(report.operator_queue or []), - approval_view="all", - ) - approved_campaigns = get_approved_manual_campaigns(bundle) - - if not approved_campaigns: - print_info("No approved-manual campaign packets found.") - return - - total_applied = 0 - total_skipped = 0 - for record in approved_campaigns: - campaign_type = str(record.get("subject_key") or "") - if not campaign_type: - continue - _campaign_summary, actions = build_campaign_bundle( - report.to_dict(), - campaign_type=campaign_type, - portfolio_profile=getattr(args, "portfolio_profile", None), - collection_name=getattr(args, "collection", None), - max_actions=None, - writeback_target="github", - ) - safe_actions = filter_safe_actions(actions) - trusted_actions = filter_trusted_repo_actions(safe_actions, trust_bar_index) - - if not trusted_actions: - skipped_repos = {str(a.get("repo") or "") for a in actions} - { - str(a.get("repo") or "") for a in trusted_actions - } - print_info( - f"Campaign {campaign_type!r}: 0 eligible actions " - f"(skipped repos: {', '.join(sorted(skipped_repos)) or 'none'})" - ) - total_skipped += len(actions) - continue - - if getattr(args, "dry_run", False): - print_info( - f"Campaign {campaign_type!r}: {len(trusted_actions)} eligible actions " - "but dry-run mode is enabled; no GitHub writes were attempted." - ) - continue - - if client is None: - print_info( - f"Campaign {campaign_type!r}: {len(trusted_actions)} eligible actions " - "but no GitHub client available (dry run)." - ) - continue - - previous_state = load_latest_campaign_state(output_dir, campaign_type) - github_results, _refs, _drift, _closure = apply_github_writeback( - client, - trusted_actions, - previous_state=previous_state, - sync_mode=str(record.get("sync_mode") or "reconcile"), - campaign_summary=_campaign_summary, - github_projects_config=None, - operator_context={}, - ) - summary = summarize_writeback_results(github_results, "github", apply=True) - applied_count = int(summary.get("applied_count", 0)) - total_applied += applied_count - print_info( - f"Campaign {campaign_type!r}: applied {applied_count} / {len(trusted_actions)} actions." - ) - - print_info(f"Auto-apply complete: {total_applied} applied, {total_skipped} skipped.") - - -def _load_release_count_by_name(*, output_dir: Path, username: str) -> dict[str, int] | None: - """Load release_count per project name from the latest audit report JSON. - - Returns a dict mapping display_name -> release_count, or None if no audit - report is found (warning is logged). - """ - import logging - - _log = logging.getLogger(__name__) - - audit_files = sorted( - output_dir.glob(f"audit-report-{username}-*.json"), - key=lambda p: p.stat().st_mtime, - ) - if not audit_files: - _log.warning( - "--portfolio-truth-include-release-count requires a prior audit run; " - "no audit-report-%s-*.json found in %s — skipping release_count overlay", - username, - output_dir, - ) - return None - - audit_path = audit_files[-1] - try: - with audit_path.open() as fh: - data = json.load(fh) - except Exception as exc: # noqa: BLE001 - _log.warning( - "--portfolio-truth-include-release-count: could not read %s: %s — skipping", - audit_path, - exc, - ) - return None - - result: dict[str, int] = {} - for audit in data.get("audits") or []: - name = (audit.get("metadata") or {}).get("name") - if not name: - continue - for ar in audit.get("analyzer_results") or []: - if ar.get("dimension") == "activity": - rc = (ar.get("details") or {}).get("release_count") - if isinstance(rc, int): - result[name] = rc - break - return result - - -def _latest_audit_report_path(*, output_dir: Path, username: str) -> Path | None: - audit_files = sorted( - output_dir.glob(f"audit-report-{username}-*.json"), - key=lambda p: p.stat().st_mtime, - ) - return audit_files[-1] if audit_files else None - - -def _repo_status_entries_from_metadata( - repo_metadata: list[dict], *, source: str -) -> dict[str, dict]: - result: dict[str, dict] = {} - for metadata in repo_metadata: - name = str(metadata.get("name") or "").strip() - full_name = str(metadata.get("full_name") or "").strip() - archived = metadata.get("archived") - if not name or not isinstance(archived, bool): - continue - entry = {"archived": archived, "full_name": full_name, "source": source} - result[name] = entry - repo_name = full_name.rsplit("/", 1)[-1] if full_name else "" - if repo_name: - result.setdefault(repo_name, entry) - return result - - -def _load_live_repo_status_by_name( - *, - username: str, - token: str | None, - cache: ResponseCache | None, -) -> dict[str, dict] | None: - """Fetch current GitHub repo archived flags using the existing REST client.""" - import logging - - _log = logging.getLogger(__name__) - try: - repos = GitHubClient(token=token, cache=cache).list_repos(username) - except Exception as exc: # noqa: BLE001 - _log.warning( - "--portfolio-truth: could not fetch live GitHub repo status for %s: %s — " - "falling back to latest audit report metadata", - username, - exc, - ) - return None - return _repo_status_entries_from_metadata(repos, source="github_api") - - -def _load_repo_status_from_audit_by_name( - *, output_dir: Path, username: str -) -> dict[str, dict] | None: - """Load GitHub repo status metadata from the latest audit report JSON.""" - import logging - - _log = logging.getLogger(__name__) - audit_path = _latest_audit_report_path(output_dir=output_dir, username=username) - if audit_path is None: - return None - - try: - with audit_path.open() as fh: - data = json.load(fh) - except Exception as exc: # noqa: BLE001 - _log.warning( - "--portfolio-truth: could not read repo status overlay from %s: %s — skipping", - audit_path, - exc, - ) - return None - - repo_metadata: list[dict] = [] - for audit in data.get("audits") or []: - metadata = audit.get("metadata") or {} - if isinstance(metadata, dict): - repo_metadata.append(metadata) - return _repo_status_entries_from_metadata(repo_metadata, source="audit_report") - - -def _load_security_alerts_by_name(*, output_dir: Path, username: str) -> dict[str, dict] | None: - """Load per-repo GHAS alert counts from the latest output/ghas-alerts--*.json. - - The file is already keyed by display name in the shape SecurityFields expects - ({name: {"dependabot": {...}, "code_scanning": {...}, "secret_scanning": {...}}}), - so the overlay needs no transformation. Returns None (with a warning) if no GHAS - report is found — the security overlay is then skipped, leaving counts at zero. - """ - import logging - - _log = logging.getLogger(__name__) - - ghas_files = sorted( - output_dir.glob(f"ghas-alerts-{username}-*.json"), - key=lambda p: p.stat().st_mtime, - ) - if not ghas_files: - _log.warning( - "--portfolio-truth-include-security requires a prior `audit report --ghas-alerts` " - "run; no ghas-alerts-%s-*.json found in %s — skipping security overlay", - username, - output_dir, - ) - return None - - ghas_path = ghas_files[-1] - try: - with ghas_path.open() as fh: - data = json.load(fh) - except Exception as exc: # noqa: BLE001 - _log.warning( - "--portfolio-truth-include-security: could not read %s: %s — skipping", - ghas_path, - exc, - ) - return None - - if not isinstance(data, dict): - _log.warning( - "--portfolio-truth-include-security: %s is not a name-keyed object — skipping", - ghas_path, - ) - return None - return {name: entry for name, entry in data.items() if isinstance(entry, dict)} - - -WAREHOUSE_REPORT_STALE_DAYS = 7 - - -def _warn_if_warehouse_report_stale(output_dir: Path, username: str) -> None: - """Warn when the legacy warehouse report is missing or stale (F2). - - Notion OS's external-signal-sync reads ``audit-report--*.json`` (the - 3.7 warehouse report), but ``--portfolio-truth`` mode does NOT regenerate it — - the truth pipeline scans the workspace and never runs the GitHub audit that - produces warehouse data. Per the F2 "keep both artifacts live" decision, surface - the gap at generation time so the operator runs ``audit report `` to - keep Notion's Repo Auditor signal fresh. Complements the cross-system-smoke C2 - check, which catches the same drift at smoke time. - """ - from datetime import date - - report_path = _latest_audit_report_path(output_dir=output_dir, username=username) - if report_path is None: - print_warning( - f"No audit-report-{username}-*.json in {output_dir}: Notion's Repo Auditor " - f"signal reads that warehouse report and this --portfolio-truth run did not " - f"create one. Run `audit report {username}` to generate it (F2)." - ) - return - match = re.search(r"(\d{4}-\d{2}-\d{2})", report_path.name) - if not match: - return - try: - report_date = date.fromisoformat(match.group(1)) - except ValueError: - return - age = (date.today() - report_date).days - if age > WAREHOUSE_REPORT_STALE_DAYS: - print_warning( - f"Newest warehouse report {report_path.name} is {age}d old: Notion's Repo " - f"Auditor signal reads it and is now stale. Run `audit report {username}` to " - f"refresh the warehouse report (F2 — both artifacts kept live by decision)." - ) - - -def _run_portfolio_truth_mode(args) -> None: - from src.portfolio_truth_publish import PortfolioTruthPublishError, publish_portfolio_truth - - output_dir = Path(args.output_dir) - workspace_root = Path(args.workspace_root) - registry_output = ( - Path(args.registry_output) - if args.registry_output - else workspace_root / "project-registry.md" - ) - portfolio_report_output = ( - Path(args.portfolio_report_output) - if args.portfolio_report_output - else workspace_root / "PORTFOLIO-AUDIT-REPORT.md" - ) - legacy_registry_path = Path(args.registry) if args.registry else registry_output - - release_count_by_name: dict[str, int] | None = None - if getattr(args, "portfolio_truth_include_release_count", False): - release_count_by_name = _load_release_count_by_name( - output_dir=output_dir, - username=args.username, - ) - - security_alerts_by_name: dict[str, dict] | None = None - if getattr(args, "portfolio_truth_include_security", False): - security_alerts_by_name = _load_security_alerts_by_name( - output_dir=output_dir, - username=args.username, - ) - repo_status_by_name = _load_live_repo_status_by_name( - username=args.username, - token=getattr(args, "token", None), - cache=None if getattr(args, "no_cache", False) else ResponseCache(), - ) - if repo_status_by_name is None: - repo_status_by_name = _load_repo_status_from_audit_by_name( - output_dir=output_dir, - username=args.username, - ) - - try: - result = publish_portfolio_truth( - workspace_root=workspace_root, - output_dir=output_dir, - registry_output=registry_output, - portfolio_report_output=portfolio_report_output, - catalog_path=Path(args.catalog) if args.catalog else None, - legacy_registry_path=legacy_registry_path, - include_notion=True, - allow_empty_notion=getattr(args, "portfolio_truth_allow_empty_notion", False), - release_count_by_name=release_count_by_name, - security_alerts_by_name=security_alerts_by_name, - repo_status_by_name=repo_status_by_name, - ) - except PortfolioTruthPublishError as exc: - raise SystemExit(str(exc)) from exc - print_info(f"Portfolio truth snapshot: {result.latest_path}") - print_info(f"Portfolio truth history snapshot: {result.snapshot_path}") - print_info(f"Project registry compatibility output: {result.registry_output}") - print_info(f"Portfolio audit compatibility output: {result.portfolio_report_output}") - print_info( - f"Portfolio truth generated for {result.project_count} projects " - f"(registry {'updated' if result.registry_changed else 'unchanged'}, " - f"report {'updated' if result.report_changed else 'unchanged'})" - ) - _warn_if_warehouse_report_stale(output_dir, args.username) - - -def _run_portfolio_context_recovery_mode(args) -> None: - from src.portfolio_context_recovery import ( - apply_context_recovery_plan, - build_context_recovery_plan, - write_context_recovery_plan_artifacts, - ) - from src.portfolio_truth_publish import publish_portfolio_truth - from src.portfolio_truth_reconcile import build_portfolio_truth_snapshot - - output_dir = Path(args.output_dir) - workspace_root = Path(args.workspace_root) - registry_output = ( - Path(args.registry_output) - if args.registry_output - else workspace_root / "project-registry.md" - ) - portfolio_report_output = ( - Path(args.portfolio_report_output) - if args.portfolio_report_output - else workspace_root / "PORTFOLIO-AUDIT-REPORT.md" - ) - legacy_registry_path = Path(args.registry) if args.registry else registry_output - catalog_path = Path(args.catalog) if args.catalog else None - - build_result = build_portfolio_truth_snapshot( - workspace_root=workspace_root, - catalog_path=catalog_path, - legacy_registry_path=legacy_registry_path, - include_notion=True, - ) - plan = build_context_recovery_plan( - build_result.snapshot, - workspace_root=workspace_root, - allow_dirty=bool(getattr(args, "allow_dirty_worktree", False)), - ) - plan_json, plan_markdown = write_context_recovery_plan_artifacts(plan, output_dir=output_dir) - print_info(f"Context recovery plan JSON: {plan_json}") - print_info(f"Context recovery plan Markdown: {plan_markdown}") - eligible_count = sum(1 for project in plan.projects if project.status == "eligible") - skipped_count = sum(1 for project in plan.projects if project.status == "skipped") - excluded_count = sum(1 for project in plan.projects if project.status == "excluded") - print_info( - f"Frozen context-recovery cohort: {plan.target_project_count} targets " - f"({eligible_count} eligible, {skipped_count} skipped, {excluded_count} excluded)" - ) - - if not args.apply_context_recovery: - return - - apply_result = apply_context_recovery_plan( - build_result.snapshot, - plan, - workspace_root=workspace_root, - catalog_path=catalog_path, - limit=args.context_recovery_limit, - ) - if apply_result.failed_projects: - raise SystemExit("Context recovery failed for: " + ", ".join(apply_result.failed_projects)) - - truth_result = publish_portfolio_truth( - workspace_root=workspace_root, - output_dir=output_dir, - registry_output=registry_output, - portfolio_report_output=portfolio_report_output, - catalog_path=catalog_path, - legacy_registry_path=legacy_registry_path, - include_notion=True, - ) - print_info( - f"Applied context recovery to {len(apply_result.updated_projects)} projects " - f"(skipped/excluded {len(apply_result.skipped_projects)})." - ) - print_info(f"Portfolio truth snapshot: {truth_result.latest_path}") - print_info(f"Project registry compatibility output: {truth_result.registry_output}") - print_info(f"Portfolio audit compatibility output: {truth_result.portfolio_report_output}") - - -def _run_automation_proposals_mode(args) -> None: - """Triage the durable bounded-automation proposal queue (Arc D phase 3b). - - Handles --propose-automation / --list-proposals / --approve-proposal / - --reject-proposal / --execute-proposals. The approval gate and every git/gh - safety rail live in the executor + proposal layers; this is thin dispatch. - """ - from datetime import datetime, timezone - - from src.automation_proposals import ( - ACTION_CATALOG_SEED, - ACTION_CONTEXT_PR, - ProposalApprovalError, - ProposalNotFoundError, - approve_proposal, - build_automation_proposals, - load_proposals, - reject_proposal, - save_proposals, - ) - from src.portfolio_automation import select_automation_candidates - - output_dir = Path(args.output_dir) - proposals_path = output_dir / "pending-proposals.json" - now = datetime.now(timezone.utc).isoformat() - - if getattr(args, "approve_proposal", None) or getattr(args, "reject_proposal", None): - try: - proposals = load_proposals(proposals_path) - if getattr(args, "approve_proposal", None): - updated = approve_proposal( - proposals, - args.approve_proposal, - approved_by="local-operator", - approved_at=now, - ) - label = f"Approved proposal {args.approve_proposal!r}." - else: - updated = reject_proposal(proposals, args.reject_proposal, rejected_at=now) - label = f"Rejected proposal {args.reject_proposal!r}." - except (ProposalNotFoundError, ProposalApprovalError, ValueError) as exc: - print_warning(str(exc)) - return - save_proposals(proposals_path, updated) - print_info(label) - return - - if getattr(args, "list_proposals", False): - proposals = load_proposals(proposals_path) - if not proposals: - print_info("No bounded-automation proposals in the queue.") - return - print_info(f"Bounded-automation proposal queue ({len(proposals)} total):") - for proposal in proposals: - print_info(f" {proposal.status}: {proposal.proposal_id} — {proposal.description}") - return - - if getattr(args, "propose_automation", False): - from src.weekly_command_center import load_latest_portfolio_truth - - _truth_path, truth = load_latest_portfolio_truth(output_dir) - if not truth: - print_warning("No portfolio truth snapshot found. Run --portfolio-truth first.") - return - try: - _report_path, _diff, report = _refresh_latest_report_state(output_dir, args) - decision_quality_status = ( - (report.operator_summary or {}) - .get("decision_quality_v1", {}) - .get("decision_quality_status", "") - ) - except FileNotFoundError: - decision_quality_status = "" - candidates = select_automation_candidates( - truth, decision_quality_status=decision_quality_status - ) - existing = load_proposals(proposals_path) - merged = build_automation_proposals( - candidates, action_type=ACTION_CONTEXT_PR, created_at=now, existing=existing - ) - merged = build_automation_proposals( - candidates, action_type=ACTION_CATALOG_SEED, created_at=now, existing=merged - ) - save_proposals(proposals_path, merged) - print_info( - f"Proposal queue: {len(merged)} total ({len(merged) - len(existing)} new) " - f"from {len(candidates)} eligible candidate(s)." - ) - return - - if getattr(args, "execute_proposals", False): - from src.automation_proposals import executable_proposals - from src.automation_workflow import execute_approved_proposals - from src.portfolio_truth_reconcile import build_portfolio_truth_snapshot - - # Building a fresh portfolio snapshot scans the whole workspace (+ Notion); - # skip that entirely when nothing is approved to execute. - if not executable_proposals(load_proposals(proposals_path)): - print_info("No approved bounded-automation proposals to execute.") - return - - workspace_root = Path(getattr(args, "workspace_root", None) or DEFAULT_PORTFOLIO_WORKSPACE) - catalog_path = ( - Path(args.catalog) - if getattr(args, "catalog", None) - else Path("config/portfolio-catalog.yaml") - ) - registry_output = ( - Path(args.registry_output) - if getattr(args, "registry_output", None) - else workspace_root / "project-registry.md" - ) - legacy_registry_path = ( - Path(args.registry) if getattr(args, "registry", None) else registry_output - ) - build_result = build_portfolio_truth_snapshot( - workspace_root=workspace_root, - catalog_path=catalog_path if catalog_path.exists() else None, - legacy_registry_path=legacy_registry_path, - include_notion=True, - ) - apply = bool(getattr(args, "apply", False)) - results = execute_approved_proposals( - proposals_path=proposals_path, - snapshot=build_result.snapshot, - workspace_root=workspace_root, - catalog_path=catalog_path, - executed_at=now, - dry_run=not apply, - ) - if not results: - print_info("No approved bounded-automation proposals to execute.") - return - for result in results: - print_info(f" {result.outcome}: {result.proposal_id} — {result.detail}") - mode = "apply" if apply else "dry-run" - print_info(f"Execute proposals ({mode}): {len(results)} approved proposal(s) processed.") - return - - -def _run_tier_recalibration_report_mode(args) -> None: - """Generate tier distribution report and flag bunching (Arc H A4).""" - from datetime import date, datetime, timezone - - from src.tier_recalibration import tier_distribution_report - - output_dir = Path(args.output_dir) - truth_path = truth_latest_path(output_dir) - if not truth_path.exists(): - print_warning( - "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." - ) - return - - try: - truth = json.loads(truth_path.read_text()) - except (OSError, json.JSONDecodeError) as exc: - print_warning(f"Failed to read portfolio-truth: {exc}") - sys.exit(2) - - projects = truth.get("projects", []) - report = tier_distribution_report(projects) - out_path = output_dir / f"tier-recalibration-{date.today()}.json" - envelope = { - "version": 1, - "generated_at": datetime.now(timezone.utc).isoformat(), - **report, - } - out_path.write_text(json.dumps(envelope, indent=2)) - print_info(f"Tier recalibration report written to {out_path}") - if report["bunching_detected"]: - print_warning( - "Bunching detected: at least one tier holds >60% of repos. " - "Consider adjusting tier thresholds." - ) - else: - print_info("No bunching detected — tier distribution looks healthy.") - - -def _run_context_triage_mode(args) -> None: - """Run context quality triage across the portfolio (Arc H B1).""" - from datetime import date, datetime, timezone - - from src.catalog_validator import validate_catalog - from src.portfolio_context_triage import run_triage - - output_dir = Path(args.output_dir) - truth_path = truth_latest_path(output_dir) - if not truth_path.exists(): - print_warning( - "portfolio-truth-latest.json not found. Run `audit run --portfolio-truth` first." - ) - return - - try: - truth = json.loads(truth_path.read_text()) - except (OSError, json.JSONDecodeError) as exc: - print_warning(f"Failed to read portfolio-truth: {exc}") - sys.exit(2) - - projects = truth.get("projects", []) - catalog_path = ( - Path(args.catalog) - if getattr(args, "catalog", None) - else Path("config/portfolio-catalog.yaml") - ) - repo_keys: list[str] = [] - for project in projects: - identity = project.get("identity") or {} - project_key = identity.get("project_key") or "" - name = identity.get("display_name") or project.get("name", "") - repo_keys.extend(key for key in (project_key, name) if key) - catalog_scores = ( - validate_catalog(catalog_path, sorted(set(repo_keys))) if catalog_path.exists() else {} - ) - - enriched: list[dict] = [] - for project in projects: - identity = project.get("identity") or {} - name = identity.get("display_name") or project.get("name", "") - project_key = identity.get("project_key") or name - row = dict(project) - row["catalog_completeness"] = max( - catalog_scores.get(project_key, 0.0), - catalog_scores.get(name, 0.0), - ) - enriched.append(row) - - entries = run_triage(enriched) - out = [e.to_dict() for e in entries] - out_path = output_dir / f"context-triage-{date.today()}.json" - envelope = { - "version": 1, - "generated_at": datetime.now(timezone.utc).isoformat(), - "total_flagged": len(out), - "triage": out, - } - out_path.write_text(json.dumps(envelope, indent=2)) - print_info(f"Context triage written to {out_path} — {len(out)} repos flagged") - - -def _apply_governance_view_filter(report: AuditReport, governance_view: str) -> None: - if not isinstance(report.governance_preview, dict): - report.governance_preview = {} - report.governance_preview["selected_view"] = governance_view - if governance_view == "all": - return - - preview_actions = ( - report.governance_preview.get("actions", []) - if isinstance(report.governance_preview, dict) - else [] - ) - result_rows = ( - report.governance_results.get("results", []) - if isinstance(report.governance_results, dict) - else [] - ) - drift_rows = report.governance_drift if isinstance(report.governance_drift, list) else [] - - if governance_view == "ready": - filtered_preview = [item for item in preview_actions if item.get("applyable")] - report.governance_preview = { - **report.governance_preview, - "actions": filtered_preview, - "applyable_count": len(filtered_preview), - "action_count": len(filtered_preview), - } - return - - if governance_view == "drifted": - report.governance_drift = drift_rows - report.governance_results = { - **report.governance_results, - "results": [item for item in result_rows if item.get("status") == "drifted"], - } - return - - if governance_view == "approved": - if not report.governance_approval: - report.governance_preview = {**report.governance_preview, "actions": []} - report.governance_results = {**report.governance_results, "results": []} - return - - if governance_view == "applied": - report.governance_results = { - **report.governance_results, - "results": [item for item in result_rows if item.get("status") == "applied"], - } - - -def _apply_ops_writeback( - report: AuditReport, args, client: GitHubClient | None, output_dir: Path -) -> None: - if not args.campaign: - return - - github_projects_config = None - operator_context: dict[str, dict] = {} - if getattr(args, "github_projects", False): - from src.github_projects import load_github_projects_config, operator_context_by_repo - from src.operator_control_center import build_operator_snapshot, normalize_review_state - - github_projects_config = load_github_projects_config( - Path(args.github_projects_config) - if getattr(args, "github_projects_config", None) - else None - ) - normalized = normalize_review_state( - report.to_dict(), - output_dir=output_dir, - diff_data=None, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ) - operator_snapshot = build_operator_snapshot( - normalized, - output_dir=output_dir, - triage_view="all", - ) - operator_context = operator_context_by_repo(operator_snapshot.get("operator_queue", [])) - - from src.notion_sync import sync_campaign_actions - from src.ops_writeback import ( - apply_github_writeback, - build_action_runs, - build_campaign_bundle, - build_campaign_run, - build_rollback_preview, - build_writeback_preview, - summarize_writeback_results, - ) - from src.warehouse import load_campaign_history, load_latest_campaign_state - - previous_state = load_latest_campaign_state(output_dir, args.campaign) - campaign_summary, actions = build_campaign_bundle( - report.to_dict(), - campaign_type=args.campaign, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - max_actions=args.max_actions, - writeback_target=args.writeback_target, - ) - campaign_summary["sync_mode"] = args.campaign_sync_mode - report.campaign_summary = campaign_summary - report.writeback_preview = build_writeback_preview( - campaign_summary, - actions, - writeback_target=args.writeback_target, - apply=args.writeback_apply, - previous_state=previous_state, - sync_mode=args.campaign_sync_mode, - github_projects_config=github_projects_config, - operator_context=operator_context, - ) - - results: list[dict] = [] - external_refs: dict[str, dict] = {} - managed_state_drift: list[dict] = [] - if args.writeback_apply and args.writeback_target: - if args.writeback_target in {"github", "all"} and client is not None: - github_results, github_refs, github_drift, _github_closure_events = ( - apply_github_writeback( - client, - actions, - previous_state=previous_state, - sync_mode=args.campaign_sync_mode, - campaign_summary=campaign_summary, - github_projects_config=github_projects_config, - operator_context=operator_context, - ) - ) - results.extend(github_results) - external_refs.update(github_refs) - managed_state_drift.extend(github_drift) - if args.writeback_target in {"notion", "all"}: - notion_results, notion_refs, notion_drift = sync_campaign_actions( - actions, - campaign_summary, - config_dir=Path("config"), - apply=True, - previous_state=previous_state, - sync_mode=args.campaign_sync_mode, - ) - results.extend(notion_results) - external_refs.update(notion_refs) - managed_state_drift.extend(notion_drift) - - report.writeback_results = summarize_writeback_results( - results, - args.writeback_target, - args.writeback_apply, - ) - report.writeback_results["campaign_run"] = build_campaign_run( - campaign_summary, - actions, - writeback_target=args.writeback_target, - apply=args.writeback_apply, - sync_mode=args.campaign_sync_mode, - ) - report.action_runs = build_action_runs( - actions, - results, - args.writeback_target, - args.writeback_apply, - previous_state=previous_state, - sync_mode=args.campaign_sync_mode, - ) - report.external_refs = external_refs - report.managed_state_drift = managed_state_drift - report.rollback_preview = build_rollback_preview(results) - historical_entries = load_campaign_history(output_dir, args.campaign, limit=20) - report.campaign_history = report.action_runs + historical_entries[:20] - - -def _enrich_report_with_operator_state( - report: AuditReport, - *, - output_dir: Path, - diff_dict: dict | None, - triage_view: str, - portfolio_profile: str, - collection: str | None, -) -> AuditReport: - from src.governance_activation import build_governance_summary - from src.operator_control_center import build_operator_snapshot, normalize_review_state - - normalized = normalize_review_state( - report.to_dict(), - output_dir=output_dir, - diff_data=diff_dict, - portfolio_profile=portfolio_profile, - collection_name=collection, - ) - normalized["governance_summary"] = build_governance_summary(normalized) - snapshot = build_operator_snapshot( - normalized, - output_dir=output_dir, - triage_view=triage_view, - ) - report.governance_summary = normalized.get("governance_summary", {}) - report.review_summary = normalized.get("review_summary", {}) - report.review_alerts = normalized.get("review_alerts", []) - report.material_changes = normalized.get("material_changes", []) - report.review_targets = normalized.get("review_targets", []) - report.review_history = normalized.get("review_history", []) - report.watch_state = normalized.get("watch_state", {}) - report.operator_summary = snapshot.get("operator_summary", {}) - report.operator_queue = snapshot.get("operator_queue", []) - report.portfolio_outcomes_summary = snapshot.get("portfolio_outcomes_summary", {}) - report.operator_effectiveness_summary = snapshot.get("operator_effectiveness_summary", {}) - report.high_pressure_queue_history = snapshot.get("high_pressure_queue_history", []) - report.campaign_readiness_summary = snapshot.get("campaign_readiness_summary", {}) - report.action_sync_summary = snapshot.get("action_sync_summary", {}) - report.next_action_sync_step = snapshot.get("next_action_sync_step", "") - report.action_sync_packets = snapshot.get("action_sync_packets", []) - report.apply_readiness_summary = snapshot.get("apply_readiness_summary", {}) - report.next_apply_candidate = snapshot.get("next_apply_candidate", {}) - report.action_sync_outcomes = snapshot.get("action_sync_outcomes", []) - report.campaign_outcomes_summary = snapshot.get("campaign_outcomes_summary", {}) - report.next_monitoring_step = snapshot.get("next_monitoring_step", {}) - report.action_sync_tuning = snapshot.get("action_sync_tuning", []) - report.campaign_tuning_summary = snapshot.get("campaign_tuning_summary", {}) - report.next_tuned_campaign = snapshot.get("next_tuned_campaign", {}) - report.historical_portfolio_intelligence = snapshot.get("historical_portfolio_intelligence", []) - report.intervention_ledger_summary = snapshot.get("intervention_ledger_summary", {}) - report.next_historical_focus = snapshot.get("next_historical_focus", {}) - report.action_sync_automation = snapshot.get("action_sync_automation", []) - report.automation_guidance_summary = snapshot.get("automation_guidance_summary", {}) - report.next_safe_automation_step = snapshot.get("next_safe_automation_step", {}) - report.approval_ledger = snapshot.get("approval_ledger", []) - report.approval_workflow_summary = snapshot.get("approval_workflow_summary", {}) - report.next_approval_review = snapshot.get("next_approval_review", {}) - return report - - -# ── Report output orchestration ─────────────────────────────────────── -def _write_report_outputs( - report: AuditReport, - args, - output_dir: Path, - *, - client: GitHubClient | None = None, - cache: ResponseCache | None = None, - json_path: Path | None = None, - write_json: bool = True, - archive: bool = True, - save_fingerprint_data: bool = True, - diff_source: Path | None = None, -) -> dict[str, object]: - from src.diff import diff_reports, format_diff_markdown - from src.excel_export import export_excel - from src.history import ( - archive_report, - find_previous, - load_repo_score_history, - load_trend_data, - save_fingerprints, - ) - from src.warehouse import write_warehouse_snapshot - - output_start = perf_counter() - _apply_ops_writeback(report, args, client, output_dir) - _apply_governance_view_filter(report, args.governance_view) - if write_json: - json_path = write_json_report(report, output_dir) - elif json_path is None: - raise ValueError("json_path is required when write_json is False") - - if diff_source is None and write_json: - diff_source = find_previous(json_path.name) - - diff_dict = None - if diff_source: - diff = diff_reports( - diff_source, - json_path, - portfolio_profile=args.portfolio_profile, - collection_name=args.collection, - ) - diff_dict = diff.to_dict() - diff_md_path = ( - output_dir / f"audit-diff-{report.username}-{_date_str(report.generated_at)}.md" - ) - diff_md_path.write_text(format_diff_markdown(diff)) - diff_json_path = ( - output_dir / f"audit-diff-{report.username}-{_date_str(report.generated_at)}.json" - ) - diff_json_path.write_text(json.dumps(diff_dict, indent=2)) - print_info( - f"Diff: {len(diff.tier_changes)} tier changes, " - f"{len([c for c in diff.score_changes if abs(c['delta']) > 0.05])} significant score changes" - ) - - report = _apply_portfolio_catalog(report, args) - report = _enrich_report_with_operator_state( - report, - output_dir=output_dir, - diff_dict=diff_dict, - triage_view=getattr(args, "triage_view", "all"), - portfolio_profile=args.portfolio_profile, - collection=args.collection, - ) - report = _apply_portfolio_catalog(report, args) - report = _apply_scorecards(report, args) - report = _apply_operating_paths(report) - report.run_change_summary = build_run_change_summary(diff_dict) - report.run_change_counts = build_run_change_counts(diff_dict) - report_data = report.to_dict() - if write_json: - json_path = write_json_report(report, output_dir) - - trend_data = load_trend_data() - score_history = load_repo_score_history() - workbook_start = perf_counter() - excel_path = export_excel( - json_path, - output_dir / f"audit-dashboard-{report.username}-{_date_str(report.generated_at)}.xlsx", - trend_data=trend_data, - diff_data=diff_dict, - score_history=score_history, - portfolio_profile=args.portfolio_profile, - collection=args.collection, - excel_mode=args.excel_mode, - truth_dir=output_dir, - ) - report.runtime_breakdown["workbook_build_seconds"] = round(perf_counter() - workbook_start, 3) - md_path = write_markdown_report(report, output_dir, diff_data=diff_dict) - pcc_path = write_pcc_export(report, output_dir) - raw_path = write_raw_metadata(report, output_dir) - warehouse_path = write_warehouse_snapshot(report, output_dir, json_path) - - # ── Semantic reindex (Arc F S3.1) ────────────────────────────────── - if getattr(args, "reindex", False) or getattr(args, "reindex_force", False): - _maybe_run_reindex(report, warehouse_path, args) - - if archive and write_json: - archive_report(json_path) - if save_fingerprint_data: - save_fingerprints(report_data["audits"], output_dir / ".audit-fingerprints.json") - report.runtime_breakdown["report_output_seconds"] = round(perf_counter() - output_start, 3) - - badge_info = "" - if args.badges: - from src.badge_export import _write_badges_markdown, export_badges, upload_badge_gist - - badge_result = export_badges(report_data, output_dir) - badge_info = ( - f"\n {badge_result['badges_md']} ({badge_result['files_written']} badge files)" - ) - if args.upload_badges: - gist_urls = upload_badge_gist(output_dir / "badges", report.username) - if gist_urls: - _write_badges_markdown(report_data, output_dir / "badges", gist_urls) - - notion_info = "" - if args.notion: - from src.notion_client import get_notion_token, load_notion_config - from src.notion_export import _load_project_map, export_notion_events - from src.notion_sync import ( - check_recommendation_followup, - create_audit_action_requests, - create_audit_history_entry, - create_recommendation_run, - patch_project_completeness_cards, - patch_weekly_review, - sync_notion_events, - ) - - notion_result = export_notion_events(report_data, output_dir) - notion_info = ( - f"\n {notion_result['events_path']} " - f"({notion_result['event_count']} events, {len(notion_result['unmapped'])} unmapped)" - ) - if args.notion_sync: - sync_notion_events(notion_result["events_path"], Path("config")) - sync_token = get_notion_token() - sync_config = load_notion_config(Path("config")) - if sync_token and sync_config: - from src.notion_dashboard import create_notion_dashboard - from src.quick_wins import find_quick_wins - - quick_wins = find_quick_wins(report.audits) - project_map = _load_project_map(Path("config")) - create_recommendation_run(report_data, quick_wins, sync_token, sync_config) - create_audit_action_requests( - report_data.get("audits", []), - project_map, - sync_token, - sync_config, - ) - patch_weekly_review(report_data, diff_dict, quick_wins, sync_token, sync_config) - create_audit_history_entry(report_data, sync_token, sync_config) - patch_project_completeness_cards( - report_data.get("audits", []), - project_map, - sync_token, - sync_config, - ) - check_recommendation_followup(report_data, sync_token, sync_config) - create_notion_dashboard(report_data, sync_token, sync_config) - - readme_info = "" - if args.portfolio_readme: - from src.portfolio_readme import export_portfolio_readme - - readme_result = export_portfolio_readme(report_data, output_dir) - readme_info = f"\n {readme_result['readme_path']}" - - suggestions_info = "" - if args.readme_suggestions: - from src.readme_suggestions import generate_readme_suggestions - - sug_result = generate_readme_suggestions(report_data, output_dir) - suggestions_info = f"\n {sug_result['suggestions_path']} ({sug_result['total_suggestions']} suggestions)" - - html_info = "" - if args.html: - from src.web_export import export_html_dashboard - - html_result = export_html_dashboard( - report_data, - output_dir, - trend_data, - score_history, - diff_data=diff_dict, - portfolio_profile=args.portfolio_profile, - collection=args.collection, - ) - html_info = f"\n {html_result['html_path']}" - - pdf_info = "" - if args.pdf: - from src.pdf_export import export_pdf_report - - pdf_path = export_pdf_report(report_data, output_dir) - if pdf_path: - pdf_info = f"\n {pdf_path}" - - review_pack_info = "" - if args.review_pack: - from src.review_pack import export_review_pack - - review_pack_result = export_review_pack( - report_data, - output_dir, - diff_data=diff_dict, - portfolio_profile=args.portfolio_profile, - collection=args.collection, - ) - review_pack_info = f"\n {review_pack_result['review_pack_path']}" - - if args.auto_archive: - from src.archive_candidates import export_archive_report, find_archive_candidates - - candidates = find_archive_candidates(score_history) - if candidates: - archive_result = export_archive_report(candidates, report.username, output_dir) - print_info( - f"Archive candidates: {archive_result['count']} repos → {archive_result['report_path']}" - ) - - if getattr(args, "vuln_check", False): - from src.vuln_check import check_vulnerabilities, format_vuln_summary - - vulns = check_vulnerabilities(report_data.get("audits", []), cache=cache) - print_info(format_vuln_summary(vulns)) - if vulns: - vuln_path = ( - output_dir / f"vuln-report-{report.username}-{_date_str(report.generated_at)}.json" - ) - vuln_path.write_text(json.dumps(vulns, indent=2, default=str)) - print_info(f"Vulnerability report: {vuln_path}") - - if getattr(args, "ghas_alerts", False) or getattr(args, "vuln_check", False): - from src.ghas_alert_details import fetch_dependabot_details - from src.ghas_alerts import fetch_ghas_alerts, format_ghas_summary - - ghas_token: str | None = getattr(args, "token", None) or None - ghas_data = fetch_ghas_alerts( - report_data.get("audits", []), - token=ghas_token, - cache=cache, - ) - # Enrich each repo entry with per-alert detail for security-burndown. - # fetch_dependabot_details paginates the same endpoint as fetch_ghas_alerts - # but lives in a separate module to keep ghas_alerts.py byte-identical to - # main (editing it triggers ruff-format reflows that CodeQL flags). - dep_details = fetch_dependabot_details( - report_data.get("audits", []), - token=ghas_token, - cache=cache, - ) - for repo_name in ghas_data: - ghas_data[repo_name]["dependabot_details"] = dep_details.get(repo_name, []) - print_info(format_ghas_summary(ghas_data)) - if ghas_data: - ghas_path = ( - output_dir / f"ghas-alerts-{report.username}-{_date_str(report.generated_at)}.json" - ) - ghas_path.write_text(json.dumps(ghas_data, indent=2, default=str)) - print_info(f"GHAS alerts report: {ghas_path}") - - if getattr(args, "ossf_scorecard", False): - from src.ossf_scorecard import fetch_ossf_scorecards, format_ossf_summary - - ossf_data = fetch_ossf_scorecards( - report_data.get("audits", []), - cache=cache, - ) - # Wire per-repo data into audit JSON - ossf_by_repo: dict[str, dict] = {} - for full_name, scorecard in ossf_data.items(): - ossf_by_repo[full_name] = scorecard - for audit in report.audits: - fn = audit.metadata.full_name - if fn in ossf_by_repo: - audit.ossf_scorecard = ossf_by_repo[fn] - # Re-serialize after mutation - report_data = report.to_dict() - - print_info(format_ossf_summary(ossf_data)) - ossf_path = ( - output_dir / f"ossf-scorecard-{report.username}-{_date_str(report.generated_at)}.json" - ) - ossf_path.write_text(json.dumps(ossf_data, indent=2, default=str)) - print_info(f"OSSF Scorecard report: {ossf_path}") - - # ── LLM cost tracking ──────────────────────────────────────────────────── - _uses_llm = args.narrative or getattr(args, "briefing", False) - _cost_tracker = None - if _uses_llm: - from src.llm_cost import BudgetExceededError, CostTracker - - _cost_tracker = CostTracker( - budget_usd=getattr(args, "max_llm_spend", None), - output_path=output_dir, - ) - - if args.narrative: - from src.narrative import generate_narrative - - try: - generate_narrative( - report_data, - output_dir, - provider_name=args.narrative_provider, - model=args.narrative_model, - github_token=args.token, - cost_tracker=_cost_tracker, - ) - except BudgetExceededError as exc: - print(f"\nERROR: {exc}", file=sys.stderr) - if _cost_tracker is not None: - _cost_tracker.write_telemetry() - sys.exit(1) - - if getattr(args, "briefing", False): - from src.briefing import generate_briefing - - try: - generate_briefing( - report_data, - output_dir, - provider_name=args.narrative_provider, - model=args.narrative_model, - github_token=args.token, - write_voice=getattr(args, "briefing_voice", False), - cost_tracker=_cost_tracker, - include_suggestions=getattr(args, "include_suggestions", False), - ) - except BudgetExceededError as exc: - print(f"\nERROR: {exc}", file=sys.stderr) - if _cost_tracker is not None: - _cost_tracker.write_telemetry() - sys.exit(1) - - if _cost_tracker is not None: - _cost_tracker.write_telemetry() - - cache_info = "" - if cache: - cache_info = f"\n Cache: {cache.hits} hits, {cache.misses} misses" - - return { - "json_path": json_path, - "md_path": md_path, - "excel_path": excel_path, - "pcc_path": pcc_path, - "raw_path": raw_path, - "warehouse_path": warehouse_path, - "badge_info": badge_info, - "notion_info": notion_info, - "readme_info": readme_info, - "suggestions_info": suggestions_info, - "html_info": html_info, - "pdf_info": pdf_info, - "review_pack_info": review_pack_info, - "cache_info": cache_info, - } - - -def _ensure_partial_run_baseline_compatible( - existing_report_data: dict | None, current_context: dict -) -> bool: - if not existing_report_data: - return True - - existing_context = extract_baseline_context(existing_report_data) - if not existing_context: - print_warning( - "Latest report does not include baseline context.\n" - " Run a full audit first so targeted and incremental reruns have a trustworthy baseline." - ) - return False - - mismatches = compare_baseline_context(current_context, existing_context) - if not mismatches: - return True - - details = "\n".join( - f" {item['label']}: existing={format_mismatch_value(item['actual'])} | requested={format_mismatch_value(item['expected'])}" - for item in mismatches - ) - print_warning( - "Latest report was generated with an incompatible baseline context.\n" - f"{details}\n" - " Run a full audit first before doing a partial rerun." - ) - return False - - -def _print_output_summary( - headline: str, - report: AuditReport, - outputs: dict[str, object], -) -> None: - print( - f"\n✓ {headline}\n" - f" Average score: {report.average_score:.2f}\n" - f" Tiers: {report.tier_distribution}" - f"{outputs['cache_info']}\n" - f" Reports:\n" - f" {outputs['json_path']}\n" - f" {outputs['md_path']}\n" - f" {outputs['excel_path']}\n" - f" {outputs['pcc_path']}\n" - f" {outputs['raw_path']}\n" - f" {outputs['warehouse_path']}" - f"{outputs['badge_info']}" - f"{outputs['notion_info']}" - f"{outputs['readme_info']}" - f"{outputs['suggestions_info']}" - f"{outputs['html_info']}" - f"{outputs['pdf_info']}" - f"{outputs['review_pack_info']}", - ) - if report.campaign_outcomes_summary.get("summary"): - print_info(f"Post-apply monitoring: {report.campaign_outcomes_summary.get('summary')}") - if report.next_monitoring_step.get("summary"): - print_info(f"Next monitoring step: {report.next_monitoring_step.get('summary')}") - if report.campaign_tuning_summary.get("summary"): - print_info(f"Campaign tuning: {report.campaign_tuning_summary.get('summary')}") - if report.next_tuned_campaign.get("summary"): - print_info( - f"{ACTION_SYNC_CANONICAL_LABELS['next_tie_break_candidate']}: {report.next_tuned_campaign.get('summary')}" - ) - if report.intervention_ledger_summary.get("summary"): - print_info( - f"Historical portfolio intelligence: {report.intervention_ledger_summary.get('summary')}" - ) - if report.next_historical_focus.get("summary"): - print_info(f"Next historical focus: {report.next_historical_focus.get('summary')}") - if report.automation_guidance_summary.get("summary"): - print_info(f"Automation guidance: {report.automation_guidance_summary.get('summary')}") - if report.next_safe_automation_step.get("summary"): - print_info(f"Next safe automation step: {report.next_safe_automation_step.get('summary')}") - print_info(_normal_audit_next_step_hint(report.username)) - - -# ── Partial run modes ───────────────────────────────────────────────── -def _run_targeted_audit( - args, - client: GitHubClient, - output_dir: Path, - *, - all_repos: list[RepoMetadata], - errors: list[dict], - custom_weights: dict[str, float] | None, - scoring_profile_name: str, - existing_report_path: Path | None = None, - existing_report_data: dict | None = None, - watch_plan=None, - latest_trusted_baseline: dict | None = None, -) -> None: - """Audit only specific repos and merge into the most recent full report.""" - target_names = _resolve_repo_names(args.repos) - print_status(f"Targeted audit: {len(target_names)} repos") - - if existing_report_path is None and existing_report_data is None: - existing_report_path, existing_report_data = _load_latest_report(output_dir) - - filtered_repos = _filter_repos( - all_repos, - skip_forks=args.skip_forks, - skip_archived=args.skip_archived, - ) - targeted_repos, missing = _select_target_repos(target_names, filtered_repos) - run_errors = list(errors) - for name in missing: - run_errors.append( - {"repo": f"{args.username}/{name}", "error": "Repo not found in fetched metadata"} - ) - print_warning(f"Repo not found: {name}") - - if not targeted_repos: - print_warning("No repos to audit.") - return - - baseline_context = build_baseline_context_from_args( - args, - scoring_profile=scoring_profile_name, - portfolio_baseline_size=len(filtered_repos), - ) - if not _ensure_partial_run_baseline_compatible(existing_report_data, baseline_context): - return - - portfolio_lang_freq = _portfolio_lang_freq_for_filtered_baseline(filtered_repos) - runtime_stats: dict[str, float] = {} - new_audits = _analyze_repos( - targeted_repos, - args=args, - client=client, - portfolio_lang_freq=portfolio_lang_freq, - custom_weights=custom_weights, - runtime_stats=runtime_stats, - ) - if not new_audits: - return - - # Load existing audits from the latest report so we can merge into them - existing_audits = existing_report_data.get("audits", []) if existing_report_data else [] - if existing_report_path: - print_info( - f"Merging into {existing_report_path.name} ({len(existing_audits)} existing repos)" - ) - - # Replace any existing audit entries for the re-analyzed repos - new_names = {audit.metadata.name for audit in new_audits} - kept_audits = [ - _audit_from_dict(audit_data) - for audit_data in existing_audits - if audit_data["metadata"]["name"] not in new_names - ] - # new_audits first so they appear at the top of the report - merged_audits = list(new_audits) + kept_audits - total_repos = ( - existing_report_data.get("total_repos", len(filtered_repos)) - if existing_report_data - else len(filtered_repos) - ) - - report = AuditReport.from_audits( - args.username, - merged_audits, - run_errors, - total_repos, - scoring_profile=scoring_profile_name, - run_mode="targeted", - portfolio_baseline_size=len(filtered_repos), - baseline_signature=baseline_context["baseline_signature"], - baseline_context=baseline_context, - ) - report.watch_state = build_watch_state( - args, - scoring_profile=scoring_profile_name, - portfolio_baseline_size=len(filtered_repos), - run_mode="targeted", - watch_plan=watch_plan, - latest_trusted_baseline=latest_trusted_baseline, - full_refresh_interval_days=FULL_REFRESH_DAYS, - ) - report.preflight_summary = getattr(args, "_preflight_summary", {}) - report.runtime_breakdown = runtime_stats - _apply_requested_reconciliation(report, args, merged_audits) - - outputs = _write_report_outputs( - report, - args, - output_dir, - client=client, - cache=None, - diff_source=args.diff or existing_report_path, - ) - _print_output_summary( - f"Targeted audit: {len(new_audits)} new/updated + {len(kept_audits)} existing = {len(merged_audits)} total", - report, - outputs, - ) - - -def _regenerate_outputs_from_latest_report( - args, - output_dir: Path, - *, - client: GitHubClient | None, - existing_report_path: Path, - existing_report_data: dict, - watch_state_override: dict | None = None, -) -> None: - report = _report_from_dict(existing_report_data) - if getattr(args, "_preflight_summary", {}): - report.preflight_summary = getattr(args, "_preflight_summary", {}) - if watch_state_override: - report.watch_state = watch_state_override - needs_fresh_json = bool(args.campaign) - outputs = _write_report_outputs( - report, - args, - output_dir, - client=client, - json_path=None if needs_fresh_json else existing_report_path, - write_json=needs_fresh_json, - archive=needs_fresh_json, - save_fingerprint_data=False, - ) - print( - f"\n✓ Regenerated outputs from latest audit for {report.username}\n" - f" Source report: {existing_report_path}\n" - f" Reports:\n" - f" {outputs['md_path']}\n" - f" {outputs['excel_path']}\n" - f" {outputs['pcc_path']}\n" - f" {outputs['raw_path']}\n" - f" {outputs['warehouse_path']}" - f"{outputs['badge_info']}" - f"{outputs['notion_info']}" - f"{outputs['readme_info']}" - f"{outputs['suggestions_info']}" - f"{outputs['html_info']}" - f"{outputs['review_pack_info']}", - ) - - -def _run_incremental_audit( - args, - client: GitHubClient, - output_dir: Path, - *, - all_repos: list[RepoMetadata], - errors: list[dict], - custom_weights: dict[str, float] | None, - scoring_profile_name: str, - watch_plan=None, - latest_trusted_baseline: dict | None = None, -) -> None: - """Only re-audit repos whose pushed_at changed since last run.""" - from src.history import load_fingerprints - - existing_report_path, existing_report_data = _load_latest_report(output_dir) - if not existing_report_path or not existing_report_data: - print_warning("No previous audit report found. Run a full audit first.") - return - - fingerprints = load_fingerprints(output_dir / ".audit-fingerprints.json") - if not fingerprints: - print_warning("No fingerprints found. Run a full audit first.") - print_info(f"Usage: python -m src {args.username}") - return - - repos = _filter_repos(all_repos, skip_forks=args.skip_forks, skip_archived=args.skip_archived) - - # Compare current pushed_at timestamps against stored fingerprints - changed: list[str] = [] - new: list[str] = [] - for repo in repos: - prev = fingerprints.get(repo.name) - curr_pushed = repo.pushed_at.isoformat() if repo.pushed_at else None - if prev is None: - # Repo not seen before — add to audit queue - new.append(repo.name) - elif prev.get("pushed_at") != curr_pushed: - # pushed_at changed — new commits since last run - changed.append(repo.name) - - needs_audit = changed + new - unchanged = len(repos) - len(needs_audit) - print_info( - f"Incremental: {len(needs_audit)} need audit " - f"({len(changed)} changed, {len(new)} new), {unchanged} unchanged" - ) - - if not needs_audit: - effective_watch_plan = watch_plan or argparse.Namespace( - mode="incremental", - reason="manual-incremental-run", - full_refresh_due=False, - ) - print_info("No changes. Regenerating outputs from latest report.") - watch_state = build_watch_state( - args, - scoring_profile=scoring_profile_name, - portfolio_baseline_size=existing_report_data.get("portfolio_baseline_size", len(repos)), - run_mode="incremental", - watch_plan=effective_watch_plan, - latest_trusted_baseline=latest_trusted_baseline, - full_refresh_interval_days=FULL_REFRESH_DAYS, - ) - _regenerate_outputs_from_latest_report( - args, - output_dir, - client=client, - existing_report_path=existing_report_path, - existing_report_data=existing_report_data, - watch_state_override=watch_state, - ) - return - - args.repos = needs_audit - effective_watch_plan = watch_plan or argparse.Namespace( - mode="incremental", - reason="manual-incremental-run", - full_refresh_due=False, - ) - _run_targeted_audit( - args, - client, - output_dir, - all_repos=all_repos, - errors=errors, - custom_weights=custom_weights, - scoring_profile_name=scoring_profile_name, - existing_report_path=existing_report_path, - existing_report_data=existing_report_data, - watch_plan=effective_watch_plan, - latest_trusted_baseline=latest_trusted_baseline, - ) - - -# ── Scoring profile loader ───────────────────────────────────────────── -def _load_scoring_profile(profile_name: str | None) -> tuple[dict[str, float] | None, str]: - normalized = _normalize_profile_name(profile_name) - if not profile_name: - return None, normalized - - profile_path = Path(f"config/scoring-profiles/{profile_name}.json") - if profile_path.is_file(): - print_info(f"Using scoring profile: {profile_name}") - return json.loads(profile_path.read_text()), normalized - - print_warning(f"Scoring profile not found: {profile_path}") - return None, normalized - - -# ── Dry-run preview ─────────────────────────────────────────────────── -def _print_dry_run_summary(repos: list[RepoMetadata]) -> None: - """Print a Rich table of repos that would be audited, then return.""" - from datetime import timezone - - try: - from rich.console import Console - from rich.table import Table - except ImportError: - print(f"[dry-run] {len(repos)} repos would be audited", file=sys.stderr) - for r in repos: - print(f" {r.name}", file=sys.stderr) - return - - console = Console(stderr=True) - table = Table(title=f"[dry-run] {len(repos)} repos would be audited", show_lines=False) - table.add_column("Name") - table.add_column("Language") - table.add_column("Size (KB)", justify="right") - table.add_column("Stars", justify="right") - table.add_column("Days Since Push", justify="right") - - now = datetime.now(timezone.utc) - total_kb = 0 - for r in repos: - days = "" - if r.pushed_at: - pushed = r.pushed_at - if pushed.tzinfo is None: - pushed = pushed.replace(tzinfo=timezone.utc) - days = str((now - pushed).days) - total_kb += r.size_kb or 0 - table.add_row( - r.name, - r.language or "", - str(r.size_kb or 0), - str(r.stars or 0), - days, - ) - - console.print(table) - est_mb = total_kb / 1024 - console.print(f"[dim]{len(repos)} repos would be audited, est {est_mb:.1f} MB[/dim]") - - -# ── Semantic index helpers (Arc F S3.1) ─────────────────────────────── - - -def _maybe_run_reindex(report: "AuditReport", warehouse_path: Path, args: object) -> None: - """Run semantic reindex after audit. Skips gracefully if deps missing.""" - from src.semantic_index import SemanticIndex, _run_reindex - - embedder_name: str = getattr(args, "embedder", "voyage") - force: bool = getattr(args, "reindex_force", False) - - idx = SemanticIndex.from_embedder_name(warehouse_path, embedder_name) - if idx is None: - print_warning( - "Semantic reindex skipped — embedder unavailable. " - "Set VOYAGE_API_KEY or use --embedder local with [semantic] extra installed." - ) - return - - summary = _run_reindex(idx, report.audits, force=force) - print_info( - f"Semantic index: {summary['embedded']} embedded, " - f"{summary['skipped']} skipped, " - f"{summary['total']} total " - f"({summary['duration_s']:.2f}s)" - ) - - -def _run_semantic_search_mode(args: object, query: str) -> None: - """Run a standalone semantic search against the existing warehouse index.""" - from src.semantic_index import SemanticIndex, _run_search - from src.warehouse import WAREHOUSE_FILENAME - - output_dir = Path(getattr(args, "output_dir", "output")) - warehouse_path = output_dir / WAREHOUSE_FILENAME - if not warehouse_path.exists(): - print_warning( - f"Warehouse not found at {warehouse_path}. " - "Run an audit with --reindex first to build the semantic index." - ) - return - - embedder_name: str = getattr(args, "embedder", "voyage") - idx = SemanticIndex.from_embedder_name(warehouse_path, embedder_name) - if idx is None: - print_warning( - "Semantic search unavailable — embedder not configured. " - "Set VOYAGE_API_KEY or use --embedder local." - ) - return - - results = _run_search(idx, query, k=5) - if not results: - print_info("No results found in semantic index. Run --reindex first.") - return - - print_info(f'Semantic search: "{query}"\n') - for i, r in enumerate(results, 1): - print_info(f" {i}. {r.repo_name} (distance={r.score:.4f})") - print_info(f" {r.snippet}") - - -# ── Serve mode ─────────────────────────────────────────────────────────────── -def _run_serve_mode(args: object) -> None: - """Launch the local FastAPI + HTMX web UI (requires [serve] extra).""" - try: - from src.serve.app import run_serve - except ImportError: - import sys - - sys.exit("audit serve requires the [serve] extra.\nInstall with: pip install -e '.[serve]'") - output_dir = Path(getattr(args, "output_dir", "output")) - run_serve( - port=getattr(args, "port", 8080), - host=getattr(args, "host", "127.0.0.1"), - output_dir=output_dir, - ) - - -# ── Subcommand inference for legacy flat invocation ─────────────────── -def _infer_subcommand_from_flags(args: argparse.Namespace) -> str: - """Return the effective subcommand name for a legacy flat invocation.""" - # triage signals - triage_flags = ( - "control_center", - "approval_center", - "triage_view", - "approve_governance", - "approve_packet", - "review_governance", - "review_packet", - "auto_apply_approved", - "reset_prefs", - "acknowledge_target", - "acknowledge_kind", - "semantic_search", - "ask", - "set_initiative", - "initiatives", - "close_initiative", - ) - for flag in triage_flags: - val = getattr(args, flag, None) - if val and val not in (False, "all", None, ""): - return "triage" - if getattr(args, "approval_center", False) or getattr(args, "control_center", False): - return "triage" - - # report signals - report_flags = ( - "portfolio_truth", - "portfolio_context_recovery", - "apply_context_recovery", - "generate_manifest", - "apply_metadata", - "apply_readmes", - "campaign_from_ledger", - "draft_readmes", - "upload_badges", - "notion_sync", - "tier_gaps", - "tier_recalibration_report", - "context_triage", - "propose_automation", - "list_proposals", - "execute_proposals", - ) - for flag in report_flags: - if getattr(args, flag, False): - return "report" - if getattr(args, "campaign", None): - return "report" - if getattr(args, "writeback_target", None): - return "report" - if getattr(args, "approve_proposal", None) or getattr(args, "reject_proposal", None): - return "report" - - return "run" - - -_KNOWN_SUBCOMMANDS: frozenset[str] = frozenset( - {"run", "triage", "report", "serve", "security-burndown", "security-gate"} -) - - -def _emit_legacy_deprecation_warning(inferred: str) -> None: - """Emit the deprecation warning at most once per process.""" - if "legacy-cli" in _LEGACY_WARNING_EVENTS: - return - _LEGACY_WARNING_EVENTS.add("legacy-cli") - warnings.warn( - f"Top-level CLI invocation is deprecated. " - f"Use `audit {inferred} --flag` instead. " - "Legacy form will be removed in a future major version.", - DeprecationWarning, - stacklevel=2, +def _emit_legacy_deprecation_warning(inferred: str) -> None: + """Emit the deprecation warning at most once per process.""" + if "legacy-cli" in _LEGACY_WARNING_EVENTS: + return + _LEGACY_WARNING_EVENTS.add("legacy-cli") + warnings.warn( + f"Top-level CLI invocation is deprecated. " + f"Use `audit {inferred} --flag` instead. " + "Legacy form will be removed in a future major version.", + DeprecationWarning, + stacklevel=2, ) @@ -7256,105 +1931,15 @@ def _rewrite_legacy_argv(argv: list[str]) -> tuple[list[str], bool]: def _run_security_burndown_mode(args) -> None: - """Dispatch for `audit security-burndown `.""" - import datetime - - from src.security_burndown import build_security_burndown, render_burndown_markdown - - output_dir = Path(args.output_dir) - username = args.username + from src.app.security_modes import run_security_burndown_mode - # Load latest ghas-alerts file (mirrors _load_security_alerts_by_name glob) - ghas_files = sorted( - output_dir.glob(f"ghas-alerts-{username}-*.json"), - key=lambda p: p.stat().st_mtime, - ) - if not ghas_files: - print_info( - f"No ghas-alerts-{username}-*.json found in {output_dir}. " - "Run `audit report --ghas-alerts` first." - ) - raise SystemExit(1) - - ghas_path = ghas_files[-1] - try: - with ghas_path.open() as fh: - ghas_data = json.load(fh) - except Exception as exc: # noqa: BLE001 - print_info(f"Could not read {ghas_path}: {exc}") - raise SystemExit(1) - - if not isinstance(ghas_data, dict): - print_info(f"{ghas_path} is not a name-keyed object — cannot build burndown.") - raise SystemExit(1) - - # Detect old counts-only files (no dependabot_details on any entry) - has_details = any( - isinstance(entry.get("dependabot_details"), list) - for entry in ghas_data.values() - if isinstance(entry, dict) - ) - if not has_details: - print_info( - f"Warning: {ghas_path.name} contains counts only — no per-alert detail.\n" - "Re-run `audit report --ghas-alerts` to capture detail, " - "then retry security-burndown." - ) - raise SystemExit(0) - - report = build_security_burndown(ghas_data) - markdown = render_burndown_markdown(report) - - print(markdown) - - today = datetime.date.today().isoformat() - out_path = output_dir / f"security-burndown-{username}-{today}.md" - out_path.write_text(markdown, encoding="utf-8") - print_info(f"Burndown written to {out_path}") - - # JSON sidecar for structured consumers (e.g. PortfolioCommandCenter desktop - # shell), mirroring the per-project security overlay's JSON-first contract. - json_path = output_dir / f"security-burndown-{username}-{today}.json" - json_path.write_text(json.dumps(report.to_dict(), indent=2), encoding="utf-8") - print_info(f"Burndown JSON written to {json_path}") + run_security_burndown_mode(args) def _run_security_gate_mode(args) -> None: - """Dispatch for `audit security-gate`.""" - from src.portfolio_security_gate import ( - build_security_gate_report, - render_security_gate_markdown, - ) + from src.app.security_modes import run_security_gate_mode - truth_path = Path(args.output_dir) / TRUTH_LATEST_FILENAME - if not truth_path.exists(): - print_info( - f"{TRUTH_LATEST_FILENAME} not found in {truth_path.parent}. " - "Run `audit report --portfolio-truth --portfolio-truth-include-security` first." - ) - raise SystemExit(1) - - try: - with truth_path.open(encoding="utf-8") as fh: - portfolio_truth = json.load(fh) - except Exception as exc: # noqa: BLE001 - print_info(f"Could not read {truth_path}: {exc}") - raise SystemExit(1) - - if not isinstance(portfolio_truth, dict): - print_info(f"{truth_path} is not a portfolio-truth object.") - raise SystemExit(1) - - report = build_security_gate_report( - portfolio_truth, - max_age_hours=getattr(args, "max_age_hours", None), - ) - if getattr(args, "json", False): - print(json.dumps(report.to_dict(), indent=2)) - else: - print(render_security_gate_markdown(report)) - if not report.passed: - raise SystemExit(1) + run_security_gate_mode(args) # ── Main entry point ────────────────────────────────────────────────── @@ -7462,7 +2047,7 @@ def main() -> None: return if getattr(args, "auto_apply_approved", False): - _run_auto_apply_approved_mode(args, Path(args.output_dir)) + run_auto_apply_approved_mode(args, Path(args.output_dir)) return if portfolio_truth_mode: @@ -7479,7 +2064,7 @@ def main() -> None: or getattr(args, "approve_proposal", None) or getattr(args, "reject_proposal", None) ): - _run_automation_proposals_mode(args) + run_automation_proposals_mode(args) return if args.doctor: @@ -7513,13 +2098,13 @@ def main() -> None: # ── Initiative tracker (7A.3) ────────────────────────────────────────── if getattr(args, "set_initiative", None): - _run_set_initiative_mode(args) + run_set_initiative_mode(args) return if getattr(args, "initiatives", False): - _run_list_initiatives_mode(args) + run_list_initiatives_mode(args) return if getattr(args, "close_initiative", None): - _run_close_initiative_mode(args) + run_close_initiative_mode(args) return # ── LLM-suggested initiatives (8.4) ─────────────────────────────────── @@ -7575,7 +2160,7 @@ def main() -> None: # ── Semantic search standalone mode (no audit needed) ───────────── query = getattr(args, "semantic_search", None) or getattr(args, "ask", None) if query: - _run_semantic_search_mode(args, query) + run_semantic_search_mode(args, query) return _run_main_audit_cycle(args, config_inspection) diff --git a/src/context_quality.py b/src/context_quality.py index ad8c4b7..bd1f7a5 100644 --- a/src/context_quality.py +++ b/src/context_quality.py @@ -1,11 +1,16 @@ # src/context_quality.py """Composite context_quality_score computation (Arc H H.4).""" + from __future__ import annotations +from typing import Any + +from src.catalog_validator import score_catalog_entry + # Weights must sum to 1.0. _WEIGHTS = { "description_confidence": 0.30, - "readme_freshness": 0.25, # inverted from readme_stale_by_age + "readme_freshness": 0.25, # inverted from readme_stale_by_age "catalog_completeness": 0.25, "completeness_score": 0.20, } @@ -30,3 +35,27 @@ def compute_context_quality_score( + _WEIGHTS["completeness_score"] * complete ) return round(max(0.0, min(1.0, score)), 4) + + +def context_quality_score_for_audit(audit: Any) -> float: + """Compute the composite context_quality_score for a RepoAudit.""" + by_dim = {r.dimension: r for r in audit.analyzer_results} + desc_conf = ( + (by_dim["description"].details or {}).get("description_confidence") + if "description" in by_dim + else None + ) + readme_stale = ( + (by_dim["readme"].details or {}).get("readme_stale_by_age") + if "readme" in by_dim + else None + ) + catalog_comp = score_catalog_entry(audit.portfolio_catalog) + completeness_score = ( + (by_dim["completeness"].score / by_dim["completeness"].max_score) + if "completeness" in by_dim and by_dim["completeness"].max_score + else None + ) + return compute_context_quality_score( + desc_conf, readme_stale, catalog_comp, completeness_score + ) diff --git a/src/control_center_presentation.py b/src/control_center_presentation.py new file mode 100644 index 0000000..c4773a7 --- /dev/null +++ b/src/control_center_presentation.py @@ -0,0 +1,892 @@ +"""User-facing control-center presentation helpers.""" + +from __future__ import annotations + +from src.operator_control_center_artifacts import should_print_control_center_item + + +def _control_center_next_step_hint() -> str: + return ( + "Reading order: workbook Dashboard -> Run Changes -> Review Queue -> Repo Detail. " + "Move into Action Sync only when the local weekly story is already settled." + ) + + +def _normal_audit_next_step_hint(username: str) -> str: + return ( + f"Next step: open the standard workbook first, then run `audit {username} --control-center` " + "for the read-only operator queue." + ) + + +def _print_control_center_summary(snapshot: dict) -> None: + summary = snapshot.get("operator_summary", {}) + queue = snapshot.get("operator_queue", []) + recent_changes = snapshot.get("operator_recent_changes", []) + print( + f"\nOperator Control Center\n {summary.get('headline', 'No operator triage items are currently surfaced.')}" + ) + if summary.get("report_reference"): + print(f" Latest report: {summary['report_reference']}") + if summary.get("source_run_id"): + print(f" Source run: {summary['source_run_id']}") + if summary.get("next_recommended_run_mode"): + print( + " Next recommended run: " + f"{summary.get('next_recommended_run_mode', 'unknown')}" + f" ({summary.get('watch_decision_summary', 'No watch decision summary available.')})" + ) + if summary.get("watch_strategy"): + print(f" Watch strategy: {summary['watch_strategy']}") + if summary.get("what_changed"): + print(f" What changed: {summary['what_changed']}") + if summary.get("why_it_matters"): + print(f" Why it matters: {summary['why_it_matters']}") + if summary.get("what_to_do_next"): + print(f" What to do next: {summary['what_to_do_next']}") + if summary.get("trend_summary"): + print(f" Trend: {summary['trend_summary']}") + if summary.get("accountability_summary"): + print(f" Accountability: {summary['accountability_summary']}") + primary_target = summary.get("primary_target") or {} + if primary_target: + repo = f"{primary_target.get('repo')}: " if primary_target.get("repo") else "" + print(f" Primary target: {repo}{primary_target.get('title', 'Operator target')}") + if summary.get("primary_target_reason"): + print(f" Why this is the top target: {summary['primary_target_reason']}") + if summary.get("primary_target_done_criteria"): + print(f" What counts as done: {summary['primary_target_done_criteria']}") + if summary.get("closure_guidance"): + print(f" Closure guidance: {summary['closure_guidance']}") + if summary.get("primary_target_last_intervention"): + intervention = summary.get("primary_target_last_intervention") or {} + when = (intervention.get("recorded_at") or "")[:10] + event_type = intervention.get("event_type", "recorded") + outcome = intervention.get("outcome", event_type) + print(f" What we tried: {when} {event_type} ({outcome})".strip()) + if summary.get("primary_target_resolution_evidence"): + print(f" Resolution evidence: {summary['primary_target_resolution_evidence']}") + if summary.get("primary_target_confidence_label"): + print( + " Primary target confidence: " + f"{summary.get('primary_target_confidence_label', 'low')} " + f"({summary.get('primary_target_confidence_score', 0.0):.2f})" + ) + if summary.get("primary_target_confidence_reasons"): + print( + " Confidence reasons: " + + ", ".join(summary.get("primary_target_confidence_reasons") or []) + ) + if summary.get("next_action_confidence_label"): + print( + " Next action confidence: " + f"{summary.get('next_action_confidence_label', 'low')} " + f"({summary.get('next_action_confidence_score', 0.0):.2f})" + ) + if summary.get("primary_target_trust_policy"): + print( + " Trust policy: " + f"{summary.get('primary_target_trust_policy', 'monitor')} " + f"({summary.get('primary_target_trust_policy_reason', 'No trust-policy reason is recorded yet.')})" + ) + if summary.get("adaptive_confidence_summary"): + print(f" Why this confidence is actionable: {summary['adaptive_confidence_summary']}") + if summary.get("primary_target_exception_status") not in {None, "", "none"}: + print( + " Trust policy exception: " + f"{summary.get('primary_target_exception_status', 'none')} " + f"({summary.get('primary_target_exception_reason', 'No trust-policy exception reason is recorded yet.')})" + ) + if summary.get("primary_target_exception_pattern_status") not in {None, "", "none"}: + print( + " Exception pattern learning: " + f"{summary.get('primary_target_exception_pattern_status', 'none')} " + f"({summary.get('primary_target_exception_pattern_reason', 'No exception-pattern reason is recorded yet.')})" + ) + if summary.get("primary_target_trust_recovery_status") not in {None, "", "none"}: + print( + " Trust recovery: " + f"{summary.get('primary_target_trust_recovery_status', 'none')} " + f"({summary.get('primary_target_trust_recovery_reason', 'No trust-recovery reason is recorded yet.')})" + ) + if summary.get("primary_target_recovery_confidence_label"): + print( + " Recovery confidence: " + f"{summary.get('primary_target_recovery_confidence_label', 'low')} " + f"({summary.get('primary_target_recovery_confidence_score', 0.0):.2f})" + ) + if summary.get("recovery_confidence_summary"): + print(f" Recovery confidence summary: {summary['recovery_confidence_summary']}") + if summary.get("primary_target_exception_retirement_status") not in {None, "", "none"}: + print( + " Exception retirement: " + f"{summary.get('primary_target_exception_retirement_status', 'none')} " + f"({summary.get('primary_target_exception_retirement_reason', 'No exception-retirement reason is recorded yet.')})" + ) + if summary.get("primary_target_policy_debt_status") not in {None, "", "none"}: + print( + " Policy debt cleanup: " + f"{summary.get('primary_target_policy_debt_status', 'none')} " + f"({summary.get('primary_target_policy_debt_reason', 'No policy-debt reason is recorded yet.')})" + ) + if summary.get("primary_target_class_normalization_status") not in {None, "", "none"}: + print( + " Class-level trust normalization: " + f"{summary.get('primary_target_class_normalization_status', 'none')} " + f"({summary.get('primary_target_class_normalization_reason', 'No class-normalization reason is recorded yet.')})" + ) + if summary.get("primary_target_class_memory_freshness_status"): + print( + " Class memory freshness: " + f"{summary.get('primary_target_class_memory_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_class_memory_freshness_reason', 'No class-memory freshness reason is recorded yet.')})" + ) + if summary.get("primary_target_class_decay_status") is not None: + print( + " Trust decay controls: " + f"{summary.get('primary_target_class_decay_status', 'none')} " + f"({summary.get('primary_target_class_decay_reason', 'No class-decay reason is recorded yet.')})" + ) + if summary.get("primary_target_transition_closure_confidence_label"): + print( + " Transition closure confidence: " + f"{summary.get('primary_target_transition_closure_confidence_label', 'low')} " + f"({summary.get('primary_target_transition_closure_confidence_score', 0.0):.2f}; " + f"{summary.get('primary_target_transition_closure_likely_outcome', 'none')})" + ) + if summary.get("transition_closure_confidence_summary"): + print(f" Transition closure summary: {summary['transition_closure_confidence_summary']}") + if summary.get("primary_target_class_pending_debt_status") not in {None, "", "none"}: + print( + " Class pending debt audit: " + f"{summary.get('primary_target_class_pending_debt_status', 'none')} " + f"({summary.get('primary_target_class_pending_debt_reason', 'No class pending-debt reason is recorded yet.')})" + ) + if summary.get("class_pending_debt_summary"): + print(f" Class pending debt summary: {summary['class_pending_debt_summary']}") + if summary.get("class_pending_resolution_summary"): + print(f" Class pending resolution summary: {summary['class_pending_resolution_summary']}") + if summary.get("primary_target_pending_debt_freshness_status"): + print( + " Pending debt freshness: " + f"{summary.get('primary_target_pending_debt_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_pending_debt_freshness_reason', 'No pending-debt freshness reason is recorded yet.')})" + ) + if summary.get("pending_debt_freshness_summary"): + print(f" Pending debt freshness summary: {summary['pending_debt_freshness_summary']}") + if summary.get("pending_debt_decay_summary"): + print(f" Pending debt decay summary: {summary['pending_debt_decay_summary']}") + if summary.get("primary_target_closure_forecast_reweight_direction"): + print( + " Closure forecast reweighting: " + f"{summary.get('primary_target_closure_forecast_reweight_direction', 'neutral')} " + f"({summary.get('primary_target_closure_forecast_reweight_score', 0.0):.2f})" + ) + if summary.get("closure_forecast_reweighting_summary"): + print( + f" Closure forecast reweighting summary: {summary['closure_forecast_reweighting_summary']}" + ) + if summary.get("primary_target_closure_forecast_momentum_status"): + print( + " Closure forecast momentum: " + f"{summary.get('primary_target_closure_forecast_momentum_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_momentum_score', 0.0):.2f})" + ) + if summary.get("closure_forecast_momentum_summary"): + print( + f" Closure forecast momentum summary: {summary['closure_forecast_momentum_summary']}" + ) + if summary.get("primary_target_closure_forecast_freshness_status"): + print( + " Closure forecast freshness: " + f"{summary.get('primary_target_closure_forecast_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_freshness_reason', 'No closure-forecast freshness reason is recorded yet.')})" + ) + if summary.get("closure_forecast_freshness_summary"): + print( + f" Closure forecast freshness summary: {summary['closure_forecast_freshness_summary']}" + ) + if summary.get("primary_target_closure_forecast_stability_status"): + print( + " Closure forecast hysteresis: " + f"{summary.get('primary_target_closure_forecast_stability_status', 'watch')} " + f"({summary.get('primary_target_closure_forecast_hysteresis_status', 'none')}: " + f"{summary.get('primary_target_closure_forecast_hysteresis_reason', 'No closure-forecast hysteresis reason is recorded yet.')})" + ) + if summary.get("closure_forecast_hysteresis_summary"): + print( + f" Closure forecast hysteresis summary: {summary['closure_forecast_hysteresis_summary']}" + ) + if summary.get("primary_target_closure_forecast_decay_status") not in {None, "", "none"}: + print( + " Hysteresis decay controls: " + f"{summary.get('primary_target_closure_forecast_decay_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_decay_reason', 'No closure-forecast decay reason is recorded yet.')})" + ) + if summary.get("closure_forecast_decay_summary"): + print(f" Closure forecast decay summary: {summary['closure_forecast_decay_summary']}") + if summary.get("primary_target_closure_forecast_refresh_recovery_status") not in { + None, + "", + "none", + }: + print( + " Closure forecast refresh recovery: " + f"{summary.get('primary_target_closure_forecast_refresh_recovery_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_refresh_recovery_score', 0.0):.2f})" + ) + if summary.get("closure_forecast_refresh_recovery_summary"): + print( + f" Closure forecast refresh recovery summary: {summary['closure_forecast_refresh_recovery_summary']}" + ) + if summary.get("primary_target_closure_forecast_reacquisition_status") not in { + None, + "", + "none", + }: + print( + " Reacquisition controls: " + f"{summary.get('primary_target_closure_forecast_reacquisition_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reacquisition_reason', 'No closure-forecast reacquisition reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reacquisition_summary"): + print( + f" Closure forecast reacquisition summary: {summary['closure_forecast_reacquisition_summary']}" + ) + if summary.get("primary_target_closure_forecast_reacquisition_persistence_status") not in { + None, + "", + "none", + }: + print( + " Reacquisition persistence: " + f"{summary.get('primary_target_closure_forecast_reacquisition_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reacquisition_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reacquisition_age_runs', 0)} run(s))" + ) + if summary.get("closure_forecast_reacquisition_persistence_summary"): + print( + f" Reacquisition persistence summary: {summary['closure_forecast_reacquisition_persistence_summary']}" + ) + if summary.get("primary_target_closure_forecast_recovery_churn_status") not in { + None, + "", + "none", + }: + print( + " Recovery churn controls: " + f"{summary.get('primary_target_closure_forecast_recovery_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_recovery_churn_reason', 'No recovery-churn reason is recorded yet.')})" + ) + if summary.get("closure_forecast_recovery_churn_summary"): + print(f" Recovery churn summary: {summary['closure_forecast_recovery_churn_summary']}") + if summary.get("primary_target_closure_forecast_reacquisition_freshness_status") not in { + None, + "", + "insufficient-data", + }: + print( + " Reacquisition freshness: " + f"{summary.get('primary_target_closure_forecast_reacquisition_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_reacquisition_freshness_reason', 'No reacquisition-freshness reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reacquisition_freshness_summary"): + print( + f" Reacquisition freshness summary: {summary['closure_forecast_reacquisition_freshness_summary']}" + ) + if summary.get("primary_target_closure_forecast_persistence_reset_status") not in { + None, + "", + "none", + }: + print( + " Persistence reset controls: " + f"{summary.get('primary_target_closure_forecast_persistence_reset_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_persistence_reset_reason', 'No persistence-reset reason is recorded yet.')})" + ) + if summary.get("closure_forecast_persistence_reset_summary"): + print( + f" Persistence reset summary: {summary['closure_forecast_persistence_reset_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_refresh_recovery_status") not in { + None, + "", + "none", + }: + print( + " Reset refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_refresh_recovery_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_refresh_recovery_score', 0.0):.2f})" + ) + if summary.get("closure_forecast_reset_refresh_recovery_summary"): + print( + f" Reset refresh recovery summary: {summary['closure_forecast_reset_refresh_recovery_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_reason', 'No reset re-entry reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_summary"): + print(f" Reset re-entry summary: {summary['closure_forecast_reset_reentry_summary']}") + if summary.get("primary_target_closure_forecast_reset_reentry_persistence_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry persistence: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reset_reentry_age_runs', 0)} run(s))" + ) + if summary.get("closure_forecast_reset_reentry_persistence_summary"): + print( + " Reset re-entry persistence summary: " + f"{summary['closure_forecast_reset_reentry_persistence_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_churn_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry churn controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_churn_reason', 'No reset re-entry churn reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_churn_summary"): + print( + " Reset re-entry churn summary: " + f"{summary['closure_forecast_reset_reentry_churn_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_freshness_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry freshness: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_freshness_reason', 'No reset re-entry freshness reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_freshness_summary"): + print( + " Reset re-entry freshness summary: " + f"{summary['closure_forecast_reset_reentry_freshness_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_reset_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry reset controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_reset_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_reset_reason', 'No reset re-entry reset reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_reset_summary"): + print( + " Reset re-entry reset summary: " + f"{summary['closure_forecast_reset_reentry_reset_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_refresh_recovery_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_refresh_recovery_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_refresh_recovery_score', 0.0):.2f})" + ) + if summary.get("closure_forecast_reset_reentry_refresh_recovery_summary"): + print( + " Reset re-entry refresh recovery summary: " + f"{summary['closure_forecast_reset_reentry_refresh_recovery_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry rebuild controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reason', 'No reset re-entry rebuild reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_summary"): + print( + " Reset re-entry rebuild summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_freshness_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild freshness: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_freshness_reason', 'No reset re-entry rebuild freshness reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_freshness_summary"): + print( + " Reset re-entry rebuild freshness summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_freshness_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_reset_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry rebuild reset controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reset_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reset_reason', 'No reset re-entry rebuild reset reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reset_summary"): + print( + " Reset re-entry rebuild reset summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reset_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_score', 0.0):.2f})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_refresh_recovery_summary"): + print( + " Reset re-entry rebuild refresh recovery summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_refresh_recovery_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_reentry_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry rebuild re-entry controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_reason', 'No reset re-entry rebuild re-entry reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_summary"): + print( + " Reset re-entry rebuild re-entry summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_persistence_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry persistence: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_age_runs', 0)} run(s))" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_summary"): + print( + " Reset re-entry rebuild re-entry persistence summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_persistence_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry churn controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_reason', 'No reset re-entry rebuild re-entry churn reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_churn_summary"): + print( + " Reset re-entry rebuild re-entry churn summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_churn_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_freshness_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry freshness: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_freshness_reason', 'No reset re-entry rebuild re-entry freshness reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_freshness_summary"): + print( + " Reset re-entry rebuild re-entry freshness summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_freshness_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_reset_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry reset controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_reset_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_reset_reason', 'No reset re-entry rebuild re-entry reset reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_reset_summary"): + print( + " Reset re-entry rebuild re-entry reset summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_reset_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status', 'none')} " + f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary', 'No reset re-entry rebuild re-entry refresh recovery summary is recorded yet.')})" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reason', 'No reset re-entry rebuild re-entry restore reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_summary"): + print( + " Reset re-entry rebuild re-entry restore summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status" + ) not in {None, "", "insufficient-data"}: + print( + " Reset re-entry rebuild re-entry restore freshness: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_reason', 'No reset re-entry rebuild re-entry restore freshness reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_summary"): + print( + " Reset re-entry rebuild re-entry restore freshness summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore reset controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reset_reason', 'No reset re-entry rebuild re-entry restore reset reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reset_summary"): + print( + " Reset re-entry rebuild re-entry restore reset summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_reset_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status', 'none')} " + f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_summary', 'No reset re-entry rebuild re-entry restore refresh recovery summary is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_summary" + ): + print( + " Reset re-entry rebuild re-entry restore refresh recovery summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-restore controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason', 'No reset re-entry rebuild re-entry restore re-restore reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_summary"): + print( + " Reset re-entry rebuild re-entry restore re-restore summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-restore persistence: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_age_runs', 0)} run(s))" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-restore persistence summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-restore churn controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_reason', 'No reset re-entry rebuild re-entry restore re-restore churn reason is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-restore churn summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status" + ) not in {None, "", "insufficient-data"}: + print( + " Reset re-entry rebuild re-entry restore re-restore freshness: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status', 'insufficient-data')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_reason', 'No reset re-entry rebuild re-entry restore re-restore freshness reason is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-restore freshness summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-restore reset controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_reason', 'No reset re-entry rebuild re-entry restore re-restore reset reason is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-restore reset summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-restore refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status', 'none')} " + f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_summary', 'No reset re-entry rebuild re-entry restore re-restore refresh recovery summary is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-restore refresh recovery summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-restore controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason', 'No reset re-entry rebuild re-entry restore re-re-restore reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_summary"): + print( + " Reset re-entry rebuild re-entry restore re-re-restore summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-restore persistence: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs', 0)} run(s))" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-re-restore persistence summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-restore churn controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason', 'No reset re-entry rebuild re-entry restore re-re-restore churn reason is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-re-restore churn summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-restore refresh recovery: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status', 'none')} " + f"({summary.get('closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary', 'No reset re-entry rebuild re-entry restore re-re-restore refresh recovery summary is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-re-restore refresh recovery summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-re-restore controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_reason', 'No reset re-entry rebuild re-entry restore re-re-re-restore reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary"): + print( + " Reset re-entry rebuild re-entry restore re-re-re-restore summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-re-restore persistence: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs', 0)} run(s))" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-re-re-restore persistence summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild re-entry restore re-re-re-restore churn controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason', 'No reset re-entry rebuild re-entry restore re-re-re-restore churn reason is recorded yet.')})" + ) + if summary.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary" + ): + print( + " Reset re-entry rebuild re-entry restore re-re-re-restore churn summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary']}" + ) + if summary.get( + "primary_target_closure_forecast_reset_reentry_rebuild_persistence_status" + ) not in {None, "", "none"}: + print( + " Reset re-entry rebuild persistence: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_persistence_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_persistence_score', 0.0):.2f}; " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_age_runs', 0)} run(s))" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_persistence_summary"): + print( + " Reset re-entry rebuild persistence summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_persistence_summary']}" + ) + if summary.get("primary_target_closure_forecast_reset_reentry_rebuild_churn_status") not in { + None, + "", + "none", + }: + print( + " Reset re-entry rebuild churn controls: " + f"{summary.get('primary_target_closure_forecast_reset_reentry_rebuild_churn_status', 'none')} " + f"({summary.get('primary_target_closure_forecast_reset_reentry_rebuild_churn_reason', 'No reset re-entry rebuild churn reason is recorded yet.')})" + ) + if summary.get("closure_forecast_reset_reentry_rebuild_churn_summary"): + print( + " Reset re-entry rebuild churn summary: " + f"{summary['closure_forecast_reset_reentry_rebuild_churn_summary']}" + ) + if summary.get("recommendation_drift_status"): + print( + " Recommendation drift: " + f"{summary.get('recommendation_drift_status', 'stable')} " + f"({summary.get('recommendation_drift_summary', 'No recommendation-drift summary is recorded yet.')})" + ) + if summary.get("exception_pattern_summary"): + print(f" Exception pattern summary: {summary['exception_pattern_summary']}") + if summary.get("exception_retirement_summary"): + print(f" Exception retirement summary: {summary['exception_retirement_summary']}") + if summary.get("policy_debt_summary"): + print(f" Policy debt summary: {summary['policy_debt_summary']}") + if summary.get("trust_normalization_summary"): + print(f" Trust normalization summary: {summary['trust_normalization_summary']}") + if summary.get("class_memory_summary"): + print(f" Class memory summary: {summary['class_memory_summary']}") + if summary.get("class_decay_summary"): + print(f" Class decay summary: {summary['class_decay_summary']}") + if summary.get("recommendation_quality_summary"): + print(f" Recommendation quality: {summary['recommendation_quality_summary']}") + if summary.get("confidence_validation_status"): + print( + " Confidence validation: " + f"{summary.get('confidence_validation_status', 'insufficient-data')} " + f"({summary.get('confidence_calibration_summary', 'No confidence-calibration summary is recorded yet.')})" + ) + if summary.get("recent_validation_outcomes"): + recent_bits = [] + for item in (summary.get("recent_validation_outcomes") or [])[:3]: + recent_bits.append( + f"{item.get('target_label', 'Operator target')} " + f"[{item.get('confidence_label', 'low')}] -> {str(item.get('outcome', 'unresolved')).replace('_', ' ')}" + ) + print(" Recent confidence outcomes: " + "; ".join(recent_bits)) + if summary.get("follow_through_summary"): + print(f" Follow-through: {summary['follow_through_summary']}") + lane_labels = [ + ("blocked", "Blocked"), + ("urgent", "Needs Attention Now"), + ("ready", "Ready for Manual Action"), + ("deferred", "Safe to Defer"), + ] + for lane, label in lane_labels: + lane_items = [item for item in queue if item.get("lane") == lane] + items = [item for item in lane_items if should_print_control_center_item(item)] + if not items: + continue + print(f"\n{label}") + for item in items[:8]: + repo = f"{item['repo']}: " if item.get("repo") else "" + print(f" - {repo}{item.get('title', 'Triage item')}") + print(f" {item.get('summary', '')}") + print(f" Why: {item.get('lane_reason', item.get('lane_label', ''))}") + print(f" Next: {item.get('recommended_action', '')}") + if item.get("catalog_line"): + print(f" Catalog: {item.get('catalog_line')}") + if item.get("intent_alignment"): + print( + " Intent alignment: " + f"{item.get('intent_alignment')} ({item.get('intent_alignment_reason', 'No alignment reason is recorded yet.')})" + ) + omitted_count = len(lane_items) - len(items) + if omitted_count > 0: + print(f" ({omitted_count} experiment/manual-only item(s) hidden from default view.)") + if recent_changes: + print("\nRecently Changed") + for item in recent_changes[:5]: + subject = ( + item.get("repo") or item.get("repo_full_name") or item.get("item_id") or "portfolio" + ) + print( + f" - {item.get('generated_at', '')[:10]} {subject}: {item.get('summary', item.get('kind', 'change'))}" + ) diff --git a/src/control_center_report_state.py b/src/control_center_report_state.py new file mode 100644 index 0000000..4c3a955 --- /dev/null +++ b/src/control_center_report_state.py @@ -0,0 +1,54 @@ +"""Refresh the report state consumed by control-center flows.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.diff import diff_reports +from src.governance_activation import build_governance_summary +from src.history import find_previous +from src.models import AuditReport +from src.operator_control_center import normalize_review_state +from src.report_operator_state import enrich_report_with_operator_state +from src.report_portfolio_catalog import apply_portfolio_catalog +from src.report_state import load_latest_report, report_from_dict + + +def refresh_latest_report_state( + output_dir: Path, + args: Any, +) -> tuple[Path, dict, AuditReport]: + report_path, report_data = load_latest_report(output_dir) + if not report_path or not report_data: + raise FileNotFoundError("No existing audit report found in output directory") + diff_dict = None + previous_path = find_previous(report_path.name) + if previous_path: + diff_dict = diff_reports( + previous_path, + report_path, + portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ).to_dict() + report = report_from_dict(report_data) + report_data = normalize_review_state( + report.to_dict(), + output_dir=output_dir, + diff_data=diff_dict, + portfolio_profile=args.portfolio_profile, + collection_name=args.collection, + ) + report_data["latest_report_path"] = str(report_path) + report_data["governance_summary"] = build_governance_summary(report_data) + report = report_from_dict(report_data) + report = apply_portfolio_catalog(report, args) + report = enrich_report_with_operator_state( + report, + output_dir=output_dir, + diff_dict=diff_dict, + triage_view=getattr(args, "triage_view", "all"), + portfolio_profile=args.portfolio_profile, + collection=args.collection, + ) + return report_path, diff_dict or {}, report diff --git a/src/control_center_snapshot.py b/src/control_center_snapshot.py new file mode 100644 index 0000000..9932641 --- /dev/null +++ b/src/control_center_snapshot.py @@ -0,0 +1,77 @@ +"""Catalog and scorecard enrichment for control-center snapshots.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.portfolio_catalog import ( + DEFAULT_CATALOG_PATH, + build_catalog_line, + catalog_entry_for_repo, + evaluate_intent_alignment, + load_portfolio_catalog, +) +from src.report_enrichment import build_operator_focus +from src.report_operating_paths import apply_operating_paths +from src.report_portfolio_catalog import apply_portfolio_catalog +from src.report_scorecards import apply_scorecards +from src.report_state import report_from_dict + + +def enrich_control_center_snapshot_from_report( + report_data: dict, + snapshot: dict, + args: Any, +) -> dict: + report = report_from_dict( + { + **report_data, + "operator_summary": snapshot.get("operator_summary", {}), + "operator_queue": snapshot.get("operator_queue", []), + } + ) + catalog_path = getattr(args, "catalog", None) or DEFAULT_CATALOG_PATH + catalog_data = load_portfolio_catalog(Path(catalog_path)) + queue_by_repo = { + str(item.get("repo") or item.get("repo_name") or "").strip(): item + for item in report.operator_queue + if str(item.get("repo") or item.get("repo_name") or "").strip() + } + for audit in report.audits: + if (audit.portfolio_catalog or {}).get("has_explicit_entry"): + continue + base_entry = catalog_entry_for_repo(audit.metadata.to_dict(), catalog_data) + if not base_entry.get("has_explicit_entry"): + continue + operator_focus = build_operator_focus(queue_by_repo.get(audit.metadata.name, {})) + intent_alignment, intent_alignment_reason = evaluate_intent_alignment( + base_entry, + completeness_tier=audit.completeness_tier, + archived=audit.metadata.archived, + operator_focus=operator_focus, + ) + audit.portfolio_catalog = { + **base_entry, + "catalog_line": build_catalog_line(base_entry), + "intent_alignment": intent_alignment, + "intent_alignment_reason": intent_alignment_reason, + "intent_alignment_line": f"{intent_alignment}: {intent_alignment_reason}", + "operator_focus": operator_focus, + } + if any(audit.portfolio_catalog for audit in report.audits): + audit_lookup = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} + for item in report.operator_queue: + catalog_entry = audit_lookup.get(str(item.get("repo") or item.get("repo_name") or "").strip(), {}) + if catalog_entry: + item["portfolio_catalog"] = dict(catalog_entry) + item["catalog_line"] = catalog_entry.get("catalog_line", "") + item["intent_alignment"] = catalog_entry.get("intent_alignment", "missing-contract") + item["intent_alignment_reason"] = catalog_entry.get("intent_alignment_reason", "") + else: + report = apply_portfolio_catalog(report, args) + report = apply_scorecards(report, args) + report = apply_operating_paths(report) + snapshot["operator_summary"] = report.operator_summary + snapshot["operator_queue"] = report.operator_queue + return snapshot diff --git a/src/models.py b/src/models.py index d2e2f12..762f499 100644 --- a/src/models.py +++ b/src/models.py @@ -7,6 +7,7 @@ from typing import Optional + def _parse_dt(value: str | None) -> Optional[datetime]: """Parse GitHub API datetime string to timezone-aware datetime.""" if not value: @@ -37,7 +38,9 @@ class RepoMetadata: topics: list[str] = field(default_factory=list) @classmethod - def from_api_response(cls, data: dict, languages: dict[str, int] | None = None) -> RepoMetadata: + def from_api_response( + cls, data: dict, languages: dict[str, int] | None = None + ) -> RepoMetadata: """Build RepoMetadata from a GitHub API repo object.""" return cls( name=data["name"], @@ -108,32 +111,9 @@ class RepoAudit: scorecard: dict = field(default_factory=dict) ossf_scorecard: dict = field(default_factory=dict) - def _context_quality_score(self) -> float: - from src.catalog_validator import score_catalog_entry - from src.context_quality import compute_context_quality_score - - by_dim = {r.dimension: r for r in self.analyzer_results} - desc_conf = ( - (by_dim["description"].details or {}).get("description_confidence") - if "description" in by_dim - else None - ) - readme_stale = ( - (by_dim["readme"].details or {}).get("readme_stale_by_age") - if "readme" in by_dim - else None - ) - catalog_comp = score_catalog_entry(self.portfolio_catalog) - completeness_score = ( - (by_dim["completeness"].score / by_dim["completeness"].max_score) - if "completeness" in by_dim and by_dim["completeness"].max_score - else None - ) - return compute_context_quality_score( - desc_conf, readme_stale, catalog_comp, completeness_score - ) - def to_dict(self) -> dict: + from src.context_quality import context_quality_score_for_audit + return { "metadata": self.metadata.to_dict(), "analyzer_results": [r.to_dict() for r in self.analyzer_results], @@ -155,7 +135,7 @@ def to_dict(self) -> dict: "portfolio_catalog": self.portfolio_catalog, "scorecard": self.scorecard, "ossf_scorecard": self.ossf_scorecard, - "context_quality_score": round(self._context_quality_score(), 3), + "context_quality_score": round(context_quality_score_for_audit(self), 3), } @@ -285,7 +265,9 @@ def from_audits( # Language distribution from collections import Counter - lang_dist = dict(Counter(a.metadata.language or "Unknown" for a in audits).most_common()) + lang_dist = dict( + Counter(a.metadata.language or "Unknown" for a in audits).most_common() + ) # Summary lists (top/bottom 5) sorted_by_score = sorted(audits, key=lambda a: a.overall_score, reverse=True) @@ -328,7 +310,9 @@ def _activity_score(audit: RepoAudit) -> float: # Best work: top 5 by weighted combo best = sorted( - audits, key=lambda a: a.overall_score * 0.6 + a.interest_score * 0.4, reverse=True + audits, + key=lambda a: a.overall_score * 0.6 + a.interest_score * 0.4, + reverse=True, ) best_work = [a.metadata.name for a in best[:5]] portfolio_lenses = portfolio_intelligence.build_portfolio_lens_summary(audits) @@ -339,7 +323,9 @@ def _activity_score(audit: RepoAudit) -> float: implementation_hotspots_summary = ( implementation_hotspots.build_implementation_hotspots_summary(audits) ) - portfolio_security = portfolio_intelligence.build_portfolio_security_posture(audits) + portfolio_security = portfolio_intelligence.build_portfolio_security_posture( + audits + ) security_governance_preview = ( portfolio_intelligence.build_portfolio_security_governance_preview(audits) ) @@ -540,5 +526,7 @@ def to_dict(self) -> dict: }, "audits": [a.to_dict() for a in self.audits], "errors": self.errors, - "reconciliation": self.reconciliation.to_dict() if self.reconciliation else None, + "reconciliation": self.reconciliation.to_dict() + if self.reconciliation + else None, } diff --git a/src/operator_approval_artifacts.py b/src/operator_approval_artifacts.py new file mode 100644 index 0000000..796b820 --- /dev/null +++ b/src/operator_approval_artifacts.py @@ -0,0 +1,124 @@ +"""Approval-center artifact construction independent of CLI dispatch.""" + +from __future__ import annotations + +import json +from datetime import datetime +from pathlib import Path + +from src.approval_ledger import load_approval_ledger_bundle, render_approval_center_markdown +from src.models import AuditReport +from src.operator_artifact_paths import ( + approval_center_paths, + approval_receipt_paths, + followup_review_receipt_paths, +) + + +def write_approval_center_artifacts( + report: AuditReport, + output_dir: Path, + *, + approval_view: str, +) -> tuple[Path, Path, dict]: + report_data = report.to_dict() + bundle = load_approval_ledger_bundle( + output_dir, + report_data, + list(report.operator_queue or []), + approval_view=approval_view, + ) + report.approval_ledger = bundle["approval_ledger"] + report.approval_workflow_summary = bundle["approval_workflow_summary"] + report.next_approval_review = bundle["next_approval_review"] + report.operator_queue = bundle.get("operator_queue", report.operator_queue) + report.operator_summary = { + **report.operator_summary, + "approval_ledger": bundle["approval_ledger"], + "approval_workflow_summary": bundle["approval_workflow_summary"], + "next_approval_review": bundle["next_approval_review"], + "top_ready_for_review_approvals": bundle["top_ready_for_review_approvals"], + "top_needs_reapproval_approvals": bundle["top_needs_reapproval_approvals"], + "top_overdue_approval_followups": bundle["top_overdue_approval_followups"], + "top_due_soon_approval_followups": bundle["top_due_soon_approval_followups"], + "top_approved_manual_approvals": bundle["top_approved_manual_approvals"], + "top_blocked_approvals": bundle["top_blocked_approvals"], + } + generated_at = report.generated_at + username = report.username + json_path, md_path = approval_center_paths(output_dir, username, generated_at) + payload = { + "username": username, + "generated_at": generated_at.isoformat(), + "approval_view": approval_view, + "approval_workflow_summary": bundle["approval_workflow_summary"], + "next_approval_review": bundle["next_approval_review"], + "approval_ledger": bundle["approval_ledger"], + "top_ready_for_review_approvals": bundle["top_ready_for_review_approvals"], + "top_needs_reapproval_approvals": bundle["top_needs_reapproval_approvals"], + "top_overdue_approval_followups": bundle["top_overdue_approval_followups"], + "top_due_soon_approval_followups": bundle["top_due_soon_approval_followups"], + "top_approved_manual_approvals": bundle["top_approved_manual_approvals"], + "top_blocked_approvals": bundle["top_blocked_approvals"], + "operator_summary": report.operator_summary, + } + json_path.write_text(json.dumps(payload, indent=2)) + md_path.write_text(render_approval_center_markdown(payload)) + return json_path, md_path, payload + + +def write_approval_receipt( + output_dir: Path, + username: str, + *, + generated_at: datetime, + receipt: dict, +) -> tuple[Path, Path]: + json_path, md_path = approval_receipt_paths(output_dir, username, generated_at) + json_path.write_text(json.dumps(receipt, indent=2)) + lines = [ + f"# Approval Receipt: {username}", + "", + f"- Generated: `{generated_at.isoformat()}`", + f"- Subject: {receipt.get('label', 'Approval')}", + f"- State: {receipt.get('approval_state', 'approved')}", + f"- Reviewer: {receipt.get('approved_by', '') or 'local-operator'}", + f"- Approved At: `{receipt.get('approved_at', '')}`", + f"- Note: {receipt.get('approval_note', '') or '—'}", + f"- Summary: {receipt.get('summary', 'Local approval captured.')}", + ] + if receipt.get("approval_command"): + lines.append(f"- Approval Command: `{receipt.get('approval_command')}`") + if receipt.get("manual_apply_command"): + lines.append(f"- Manual Apply Command: `{receipt.get('manual_apply_command')}`") + md_path.write_text("\n".join(lines) + "\n") + return json_path, md_path + + +def write_followup_review_receipt( + output_dir: Path, + username: str, + *, + generated_at: datetime, + receipt: dict, +) -> tuple[Path, Path]: + json_path, md_path = followup_review_receipt_paths(output_dir, username, generated_at) + json_path.write_text(json.dumps(receipt, indent=2)) + lines = [ + f"# Approval Follow-Up Receipt: {username}", + "", + f"- Generated: `{generated_at.isoformat()}`", + f"- Subject: {receipt.get('label', 'Approval')}", + f"- State: {receipt.get('approval_state', 'approved')} / {receipt.get('follow_up_state', 'not-applicable')}", + f"- Reviewer: {receipt.get('reviewed_by', '') or 'local-operator'}", + f"- Reviewed At: `{receipt.get('reviewed_at', '')}`", + f"- Next Follow-Up Due: `{receipt.get('next_follow_up_due_at', '') or '—'}`", + f"- Note: {receipt.get('review_note', '') or '—'}", + f"- Summary: {receipt.get('summary', 'Local follow-up review captured.')}", + ] + if receipt.get("follow_up_command"): + lines.append(f"- Follow-Up Command: `{receipt.get('follow_up_command')}`") + if receipt.get("manual_apply_command"): + lines.append(f"- Manual Apply Command: `{receipt.get('manual_apply_command')}`") + md_path.write_text("\n".join(lines) + "\n") + return json_path, md_path diff --git a/src/operator_artifact_paths.py b/src/operator_artifact_paths.py new file mode 100644 index 0000000..b0b9062 --- /dev/null +++ b/src/operator_artifact_paths.py @@ -0,0 +1,56 @@ +"""Stable artifact path builders for operator-facing outputs.""" + +from __future__ import annotations + +from datetime import datetime +from pathlib import Path + + +def control_center_paths( + output_dir: Path, username: str, generated_at: datetime +) -> tuple[Path, Path]: + stamp = generated_at.strftime("%Y-%m-%d") + return ( + output_dir / f"operator-control-center-{username}-{stamp}.json", + output_dir / f"operator-control-center-{username}-{stamp}.md", + ) + + +def weekly_command_center_paths( + output_dir: Path, username: str, generated_at: datetime +) -> tuple[Path, Path]: + stamp = generated_at.strftime("%Y-%m-%d") + return ( + output_dir / f"weekly-command-center-{username}-{stamp}.json", + output_dir / f"weekly-command-center-{username}-{stamp}.md", + ) + + +def approval_center_paths( + output_dir: Path, username: str, generated_at: datetime +) -> tuple[Path, Path]: + stamp = generated_at.strftime("%Y-%m-%d") + return ( + output_dir / f"approval-center-{username}-{stamp}.json", + output_dir / f"approval-center-{username}-{stamp}.md", + ) + + +def approval_receipt_paths( + output_dir: Path, username: str, generated_at: datetime +) -> tuple[Path, Path]: + stamp = generated_at.strftime("%Y-%m-%d") + return ( + output_dir / f"approval-receipt-{username}-{stamp}.json", + output_dir / f"approval-receipt-{username}-{stamp}.md", + ) + + +def followup_review_receipt_paths( + output_dir: Path, username: str, generated_at: datetime +) -> tuple[Path, Path]: + stamp = generated_at.strftime("%Y-%m-%d") + return ( + output_dir / f"approval-followup-receipt-{username}-{stamp}.json", + output_dir / f"approval-followup-receipt-{username}-{stamp}.md", + ) diff --git a/src/operator_control_center_artifacts.py b/src/operator_control_center_artifacts.py new file mode 100644 index 0000000..6f8309a --- /dev/null +++ b/src/operator_control_center_artifacts.py @@ -0,0 +1,93 @@ +"""Control-center filtering and artifact generation outside CLI dispatch.""" + +from __future__ import annotations + +import json +from datetime import datetime +from pathlib import Path + +from src.cache import contains_sensitive_data +from src.operator_artifact_paths import control_center_paths +from src.operator_control_center import ( + control_center_artifact_payload, + render_control_center_markdown, +) +from src.weekly_command_center import ( + build_weekly_command_center_digest, + load_latest_portfolio_truth, + write_weekly_command_center_artifacts, +) + + +def should_print_control_center_item(item: dict) -> bool: + catalog = item.get("portfolio_catalog") or {} + lifecycle = str(catalog.get("lifecycle_state") or "").strip().lower() + intended = str(catalog.get("intended_disposition") or "").strip().lower() + program = str(catalog.get("maturity_program") or "").strip().lower() + operating_path = str( + item.get("operating_path") or catalog.get("operating_path") or "" + ).strip().lower() + if lifecycle in {"archived", "archive"}: + return False + if intended == "archive" or program == "archive" or operating_path == "archive": + return False + if lifecycle in {"experiment", "experimental"}: + return False + if intended == "experiment" or program == "experiment" or operating_path == "experiment": + return False + return True + + +def filter_snapshot_for_default_view(snapshot: dict) -> dict: + queue = snapshot.get("operator_queue") + if not isinstance(queue, list): + return snapshot + snapshot["operator_queue"] = [ + item + for item in queue + if isinstance(item, dict) and should_print_control_center_item(item) + ] + return snapshot + + +def write_control_center_artifacts( + report_data: dict, + snapshot: dict, + output_dir: Path, + *, + username: str, + generated_at: datetime, + report_reference: str, + diff_dict: dict | None = None, +) -> tuple[Path, Path, Path, Path, dict]: + filter_snapshot_for_default_view(snapshot) + json_path, md_path = control_center_paths(output_dir, username, generated_at) + snapshot.setdefault("operator_summary", {})["control_center_reference"] = str(json_path) + portfolio_truth_path, portfolio_truth = load_latest_portfolio_truth(output_dir) + weekly_digest = build_weekly_command_center_digest( + report_data, + snapshot, + diff_data=diff_dict, + portfolio_truth=portfolio_truth, + portfolio_truth_reference=str(portfolio_truth_path) if portfolio_truth_path else "", + control_center_reference=str(json_path), + report_reference=report_reference, + generated_at=generated_at.isoformat(), + ) + weekly_json, weekly_md = write_weekly_command_center_artifacts( + output_dir, + username=username, + generated_at=generated_at, + digest=weekly_digest, + ) + payload = control_center_artifact_payload(report_data, snapshot) + payload["weekly_command_center_digest_v1"] = weekly_digest + payload["weekly_command_center_reference"] = { + "json_path": str(weekly_json), + "markdown_path": str(weekly_md), + } + if contains_sensitive_data(payload) or contains_sensitive_data(snapshot): + raise ValueError("control-center artifacts must not persist credential fields") + json_path.write_text(json.dumps(payload, indent=2)) # codeql[py/clear-text-storage-sensitive-data] guarded above + md_path.write_text(render_control_center_markdown(snapshot, username, generated_at.isoformat())) # codeql[py/clear-text-storage-sensitive-data] guarded above + return json_path, md_path, weekly_json, weekly_md, payload diff --git a/src/operator_resolution_trend.py b/src/operator_resolution_trend.py index b67de94..5919965 100644 --- a/src/operator_resolution_trend.py +++ b/src/operator_resolution_trend.py @@ -1,6 +1,5 @@ from __future__ import annotations -from functools import lru_cache from typing import NamedTuple from src.operator_trend_apply_chain import ( @@ -40,305 +39,150 @@ target_closure_forecast_history as _target_closure_forecast_history_helper, ) from src.operator_trend_closure_forecast_freshness_controls import ( - apply_closure_forecast_decay_control as _apply_closure_forecast_decay_control_helper, + apply_closure_forecast_decay_control as _apply_closure_forecast_decay_control, ) from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_event_has_evidence as _closure_forecast_event_has_evidence_helper, + closure_forecast_freshness_for_target as _closure_forecast_freshness_for_target, ) from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_event_is_clearance_like as _closure_forecast_event_is_clearance_like_helper, + closure_forecast_freshness_hotspots as _closure_forecast_freshness_hotspots, ) from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_event_is_confirmation_like as _closure_forecast_event_is_confirmation_like_helper, -) -from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_event_signal_label as _closure_forecast_event_signal_label_helper, -) -from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_freshness_for_target as _closure_forecast_freshness_for_target_helper, -) -from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_freshness_hotspots as _closure_forecast_freshness_hotspots_helper, -) -from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_freshness_reason as _closure_forecast_freshness_reason_helper, -) -from src.operator_trend_closure_forecast_freshness_controls import ( - closure_forecast_freshness_status as _closure_forecast_freshness_status_helper, -) -from src.operator_trend_closure_forecast_freshness_controls import ( - recent_closure_forecast_signal_mix as _recent_closure_forecast_signal_mix_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - apply_closure_forecast_reacquisition_control as _apply_closure_forecast_reacquisition_control_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - apply_reacquisition_freshness_reset_control as _apply_reacquisition_freshness_reset_control_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - apply_reacquisition_persistence_and_churn_control as _apply_reacquisition_persistence_and_churn_control_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_persistence_reset_summary as _closure_forecast_persistence_reset_summary_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_freshness_for_target as _closure_forecast_reacquisition_freshness_for_target_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_freshness_hotspots as _closure_forecast_reacquisition_freshness_hotspots_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_freshness_reason as _closure_forecast_reacquisition_freshness_reason_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_freshness_summary as _closure_forecast_reacquisition_freshness_summary_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_hotspots as _closure_forecast_reacquisition_hotspots_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_path_label as _closure_forecast_reacquisition_path_label_helper, + closure_forecast_freshness_status as _closure_forecast_freshness_status, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_persistence_for_target as _closure_forecast_reacquisition_persistence_for_target_helper, + apply_closure_forecast_reacquisition_control as _apply_closure_forecast_reacquisition_control, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_persistence_summary as _closure_forecast_reacquisition_persistence_summary_helper, + apply_reacquisition_freshness_reset_control as _apply_reacquisition_freshness_reset_control, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_side_from_event as _closure_forecast_reacquisition_side_from_event_helper, + apply_reacquisition_persistence_and_churn_control as _apply_reacquisition_persistence_and_churn_control, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_side_from_status as _closure_forecast_reacquisition_side_from_status_helper, + closure_forecast_persistence_reset_summary as _closure_forecast_persistence_reset_summary, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_summary as _closure_forecast_reacquisition_summary_helper, + closure_forecast_reacquisition_freshness_for_target as _closure_forecast_reacquisition_freshness_for_target, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_recovery_churn_for_target as _closure_forecast_recovery_churn_for_target_helper, + closure_forecast_reacquisition_freshness_hotspots as _closure_forecast_reacquisition_freshness_hotspots, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_recovery_churn_summary as _closure_forecast_recovery_churn_summary_helper, + closure_forecast_reacquisition_freshness_summary as _closure_forecast_reacquisition_freshness_summary, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_refresh_hotspots as _closure_forecast_refresh_hotspots_helper, + closure_forecast_reacquisition_hotspots as _closure_forecast_reacquisition_hotspots, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_refresh_path_label as _closure_forecast_refresh_path_label_helper, + closure_forecast_reacquisition_persistence_for_target as _closure_forecast_reacquisition_persistence_for_target, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_refresh_recovery_for_target as _closure_forecast_refresh_recovery_for_target_helper, + closure_forecast_reacquisition_persistence_summary as _closure_forecast_reacquisition_persistence_summary, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_refresh_recovery_summary as _closure_forecast_refresh_recovery_summary_helper, + closure_forecast_reacquisition_summary as _closure_forecast_reacquisition_summary, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_refresh_signal_from_event as _closure_forecast_refresh_signal_from_event_helper, + closure_forecast_recovery_churn_for_target as _closure_forecast_recovery_churn_for_target, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - reacquisition_event_has_evidence as _reacquisition_event_has_evidence_helper, + closure_forecast_recovery_churn_summary as _closure_forecast_recovery_churn_summary, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - reacquisition_event_is_clearance_like as _reacquisition_event_is_clearance_like_helper, + closure_forecast_refresh_hotspots as _closure_forecast_refresh_hotspots, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - reacquisition_event_is_confirmation_like as _reacquisition_event_is_confirmation_like_helper, + closure_forecast_refresh_recovery_for_target as _closure_forecast_refresh_recovery_for_target, ) from src.operator_trend_closure_forecast_reacquisition_controls import ( - reacquisition_event_signal_label as _reacquisition_event_signal_label_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - recent_closure_forecast_weakened_side as _recent_closure_forecast_weakened_side_helper, -) -from src.operator_trend_closure_forecast_reacquisition_controls import ( - recent_reacquisition_signal_mix as _recent_reacquisition_signal_mix_helper, + closure_forecast_refresh_recovery_summary as _closure_forecast_refresh_recovery_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_freshness_reset_control as _apply_reset_reentry_freshness_reset_control_helper, + apply_reset_reentry_freshness_reset_control as _apply_reset_reentry_freshness_reset_control, ) from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_rebuild_freshness_and_reset as _apply_reset_reentry_rebuild_freshness_and_reset_helper, ) from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_freshness_reset_control as _apply_reset_reentry_rebuild_freshness_reset_control_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_persistence_and_churn_control as _apply_reset_reentry_rebuild_persistence_and_churn_control_helper, + apply_reset_reentry_rebuild_persistence_and_churn_control as _apply_reset_reentry_rebuild_persistence_and_churn_control, ) from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore as _apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore_helper, ) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_reentry_refresh_restore_control as _apply_reset_reentry_rebuild_reentry_refresh_restore_control_helper, -) from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn as _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_helper, ) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control as _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control_helper, -) from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset as _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset_helper, ) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control as _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control_helper, -) from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn as _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_helper, ) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control as _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control_helper, -) from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and_rerererestore as _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and_rerererestore_helper, ) from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control as _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_reentry_refresh_rebuild_control as _apply_reset_reentry_refresh_rebuild_control_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - apply_reset_refresh_reentry_control as _apply_reset_refresh_reentry_control_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_freshness_for_target as _closure_forecast_reset_reentry_freshness_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_freshness_hotspots as _closure_forecast_reset_reentry_freshness_hotspots_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_freshness_summary as _closure_forecast_reset_reentry_freshness_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_churn_for_target as _closure_forecast_reset_reentry_rebuild_churn_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_churn_summary as _closure_forecast_reset_reentry_rebuild_churn_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_freshness_for_target as _closure_forecast_reset_reentry_rebuild_freshness_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_freshness_hotspots as _closure_forecast_reset_reentry_rebuild_freshness_hotspots_helper, + apply_reset_reentry_refresh_rebuild_control as _apply_reset_reentry_refresh_rebuild_control, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_freshness_summary as _closure_forecast_reset_reentry_rebuild_freshness_summary_helper, + apply_reset_refresh_reentry_control as _apply_reset_refresh_reentry_control, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_hotspots as _closure_forecast_reset_reentry_rebuild_hotspots_helper, + closure_forecast_reset_reentry_freshness_for_target as _closure_forecast_reset_reentry_freshness_for_target, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_persistence_for_target as _closure_forecast_reset_reentry_rebuild_persistence_for_target_helper, + closure_forecast_reset_reentry_freshness_hotspots as _closure_forecast_reset_reentry_freshness_hotspots, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_persistence_summary as _closure_forecast_reset_reentry_rebuild_persistence_summary_helper, + closure_forecast_reset_reentry_freshness_summary as _closure_forecast_reset_reentry_freshness_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots as _closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots_helper, + closure_forecast_reset_reentry_rebuild_churn_for_target as _closure_forecast_reset_reentry_rebuild_churn_for_target, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_for_target as _closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_for_target_helper, + closure_forecast_reset_reentry_rebuild_churn_summary as _closure_forecast_reset_reentry_rebuild_churn_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary as _closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary_helper, + closure_forecast_reset_reentry_rebuild_hotspots as _closure_forecast_reset_reentry_rebuild_hotspots, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target_helper, + closure_forecast_reset_reentry_rebuild_persistence_for_target as _closure_forecast_reset_reentry_rebuild_persistence_for_target, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary_helper, + closure_forecast_reset_reentry_rebuild_persistence_summary as _closure_forecast_reset_reentry_rebuild_persistence_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots_helper, + closure_forecast_reset_reentry_rebuild_summary as _closure_forecast_reset_reentry_rebuild_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target_helper, + closure_forecast_reset_reentry_refresh_hotspots as _closure_forecast_reset_reentry_refresh_hotspots, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary_helper, + closure_forecast_reset_reentry_refresh_recovery_for_target as _closure_forecast_reset_reentry_refresh_recovery_for_target, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary_helper, + closure_forecast_reset_reentry_refresh_recovery_summary as _closure_forecast_reset_reentry_refresh_recovery_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_text as _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_text_helper, + closure_forecast_reset_reentry_reset_summary as _closure_forecast_reset_reentry_reset_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target_helper, + closure_forecast_reset_reentry_summary as _closure_forecast_reset_reentry_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary_helper, + closure_forecast_reset_refresh_hotspots as _closure_forecast_reset_refresh_hotspots, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target_helper, + closure_forecast_reset_refresh_recovery_for_target as _closure_forecast_reset_refresh_recovery_for_target, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots_helper, + closure_forecast_reset_refresh_recovery_summary as _closure_forecast_reset_refresh_recovery_summary, ) from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reentry_restore_summary as _closure_forecast_reset_reentry_rebuild_reentry_restore_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_reset_summary as _closure_forecast_reset_reentry_rebuild_reset_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_rebuild_summary as _closure_forecast_reset_reentry_rebuild_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_refresh_hotspots as _closure_forecast_reset_reentry_refresh_hotspots_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_refresh_recovery_for_target as _closure_forecast_reset_reentry_refresh_recovery_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_refresh_recovery_summary as _closure_forecast_reset_reentry_refresh_recovery_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_reset_summary as _closure_forecast_reset_reentry_reset_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_reentry_summary as _closure_forecast_reset_reentry_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_refresh_hotspots as _closure_forecast_reset_refresh_hotspots_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_refresh_path_label as _closure_forecast_reset_refresh_path_label_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_refresh_recovery_for_target as _closure_forecast_reset_refresh_recovery_for_target_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_refresh_recovery_summary as _closure_forecast_reset_refresh_recovery_summary_helper, -) -from src.operator_trend_closure_forecast_reset_controls import ( - closure_forecast_reset_side_from_status as _closure_forecast_reset_side_from_status_helper, + closure_forecast_reset_side_from_status as _closure_forecast_reset_side_from_status, ) + from src.operator_trend_confidence_calibration import ( build_confidence_calibration as _build_confidence_calibration_helper, ) @@ -410,6 +254,30 @@ from src.operator_trend_summary_context import ( build_trend_summary_context as _build_trend_summary_context_helper, ) +from src.operator_trend_support import ( + class_direction_flip_count as _class_direction_flip_count, +) +from src.operator_trend_support import ( + clamp_round as _clamp_round, +) +from src.operator_trend_support import ( + closure_forecast_direction_majority as _closure_forecast_direction_majority, +) +from src.operator_trend_support import ( + closure_forecast_direction_reversing as _closure_forecast_direction_reversing, +) +from src.operator_trend_support import ( + normalized_closure_forecast_direction as _normalized_closure_forecast_direction, +) +from src.operator_trend_support import ( + target_class_key as _target_class_key, +) +from src.operator_trend_support import ( + target_label as _target_label, +) +from src.operator_trend_support import ( + target_specific_normalization_noise as _target_specific_normalization_noise, +) from src.operator_trend_support import ( ATTENTION_LANES, CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS, @@ -425,16 +293,10 @@ CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS, CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS, CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS, - CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_PERSISTENCE_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_REENTRY_FRESHNESS_WINDOW_RUNS, - CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_FRESHNESS_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_REFRESH_WINDOW_RUNS, - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERERESTORE_WINDOW_RUNS, - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS, - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_FRESHNESS_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_REFRESH_WINDOW_RUNS, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_WINDOW_RUNS, @@ -514,6 +376,137 @@ ) +from src.operator_trend_support import ( + closure_forecast_reset_reentry_side_from_event as _closure_forecast_reset_reentry_side_from_event, +) +from src.operator_trend_support import ( + closure_forecast_reset_reentry_side_from_recovery_status as _closure_forecast_reset_reentry_side_from_recovery_status, +) +from src.operator_trend_support import ( + closure_forecast_reset_reentry_side_from_status as _closure_forecast_reset_reentry_side_from_status, +) +from src.operator_trend_support import ( + ordered_reset_reentry_events_for_target as _ordered_reset_reentry_events_for_target, +) +from src.operator_trend_support import ( + queue_identity as _queue_identity, +) +from src.operator_trend_support import ( + recommendation_bucket as _recommendation_bucket, +) +from src.operator_trend_support import ( + resolve_side as _resolve_side, +) + + +def _apply_reset_reentry_rebuild_freshness_and_reset( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + return _apply_reset_reentry_rebuild_freshness_and_reset_helper( + resolution_targets, + history, + current_generated_at=current_generated_at, + confidence_calibration=confidence_calibration, + class_closure_forecast_events=_class_closure_forecast_events, + class_transition_events=_class_transition_events, + target_class_transition_history=_target_class_transition_history, + ) + + +def _apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + return _apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore_helper( + resolution_targets, + history, + current_generated_at=current_generated_at, + confidence_calibration=confidence_calibration, + class_closure_forecast_events=_class_closure_forecast_events, + class_transition_events=_class_transition_events, + target_class_transition_history=_target_class_transition_history, + ) + + +def _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + return _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_helper( + resolution_targets, + history, + current_generated_at=current_generated_at, + confidence_calibration=confidence_calibration, + class_closure_forecast_events=_class_closure_forecast_events, + class_transition_events=_class_transition_events, + target_class_transition_history=_target_class_transition_history, + ) + + +def _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + return _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset_helper( + resolution_targets, + history, + current_generated_at=current_generated_at, + confidence_calibration=confidence_calibration, + class_closure_forecast_events=_class_closure_forecast_events, + class_transition_events=_class_transition_events, + target_class_transition_history=_target_class_transition_history, + ) + + +def _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + return _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_helper( + resolution_targets, + history, + current_generated_at=current_generated_at, + confidence_calibration=confidence_calibration, + class_closure_forecast_events=_class_closure_forecast_events, + class_transition_events=_class_transition_events, + target_class_transition_history=_target_class_transition_history, + ) + + +def _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and_rerererestore( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + return _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and_rerererestore_helper( + resolution_targets, + history, + current_generated_at=current_generated_at, + confidence_calibration=confidence_calibration, + class_closure_forecast_events=_class_closure_forecast_events, + class_transition_events=_class_transition_events, + target_class_transition_history=_target_class_transition_history, + ) + + def _build_confidence_calibration(history: list[dict]) -> dict: return _build_confidence_calibration_helper( history, @@ -636,11 +629,13 @@ def _build_resolution_trend( primary_target_done_criteria_fn=_primary_target_done_criteria, closure_guidance_fn=_closure_guidance, accountability_summary_fn=_accountability_summary, - summary_decision_memory_fn=lambda primary_target, recent_runs, queue_identity: _summary_decision_memory( - primary_target, - decision_memory_map, - recent_runs, - queue_identity=queue_identity, + summary_decision_memory_fn=lambda primary_target, recent_runs, queue_identity: ( + _summary_decision_memory( + primary_target, + decision_memory_map, + recent_runs, + queue_identity=queue_identity, + ) ), trend_summary_fn=_trend_summary, queue_identity=_queue_identity, @@ -713,9 +708,9 @@ def _snapshot_from_history(entry: dict) -> dict: queue = entry.get("operator_queue", []) or [] items = {_queue_identity(item): item for item in queue} summary = entry.get("operator_summary", {}) or {} - has_attention = summary.get("counts", {}).get("blocked", 0) or summary.get("counts", {}).get( - "urgent", 0 - ) + has_attention = summary.get("counts", {}).get("blocked", 0) or summary.get( + "counts", {} + ).get("urgent", 0) return { "items": items, "has_attention": bool(has_attention), @@ -778,7 +773,8 @@ def _resolution_targets( ( match.get("age_days", 0) for snapshot in recent_runs[1:] - if (match := snapshot["items"].get(key)) and match.get("lane") != "deferred" + if (match := snapshot["items"].get(key)) + and match.get("lane") != "deferred" ), default=0, ) @@ -787,7 +783,9 @@ def _resolution_targets( for snapshot in recent_runs[1:] if (match := snapshot["items"].get(key)) and match.get("lane") != "deferred" ) - is_repeat_urgent = item.get("lane") in ATTENTION_LANES and repeat_attention_appearances >= 2 + is_repeat_urgent = ( + item.get("lane") in ATTENTION_LANES and repeat_attention_appearances >= 2 + ) is_reopened = ( item.get("lane") in ATTENTION_LANES and key not in previous_attention_keys @@ -797,7 +795,10 @@ def _resolution_targets( previous_aging_status = _aging_status( previous_non_deferred_appearances, previous_earliest_days ) - newly_stale = current_aging_status in {"stale", "chronic"} and previous_aging_status in { + newly_stale = current_aging_status in { + "stale", + "chronic", + } and previous_aging_status in { "fresh", "watch", } @@ -807,7 +808,9 @@ def _resolution_targets( "repo": item.get("repo", ""), "title": item.get("title", ""), "lane": item.get("lane", ""), - "lane_label": item.get("lane_label", LANE_LABELS.get(item.get("lane", ""), "")), + "lane_label": item.get( + "lane_label", LANE_LABELS.get(item.get("lane", ""), "") + ), "kind": item.get("kind", ""), "priority": item.get("priority", 0), "recommended_action": item.get("recommended_action", ""), @@ -886,7 +889,9 @@ def _apply_trust_policy_exceptions( exception_status = "none" exception_reason = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) if _recommendation_bucket(target) == current_bucket: ( @@ -916,8 +921,12 @@ def _apply_trust_policy_exceptions( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] return { - "primary_target_exception_status": primary_target.get("trust_exception_status", "none"), - "primary_target_exception_reason": primary_target.get("trust_exception_reason", ""), + "primary_target_exception_status": primary_target.get( + "trust_exception_status", "none" + ), + "primary_target_exception_reason": primary_target.get( + "trust_exception_reason", "" + ), "recommendation_drift_status": _recommendation_drift_status( primary_target.get("policy_flip_count", 0), policy_flip_hotspots, @@ -969,15 +978,21 @@ def _apply_exception_pattern_learning( stable_policy_run_count = 0 recent_exception_path = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") - pre_retirement_policy = final_policy + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) + pre_retirement_policy = final_policy pre_retirement_reason = final_reason if _recommendation_bucket(target) == current_bucket: - history_meta = _target_exception_history(target, exception_events, historical_cases) + history_meta = _target_exception_history( + target, exception_events, historical_cases + ) stable_policy_run_count = history_meta["stable_policy_run_count"] recent_exception_path = history_meta["recent_exception_path"] - pattern_status, pattern_reason = _exception_pattern_for_target(target, history_meta) + pattern_status, pattern_reason = _exception_pattern_for_target( + target, history_meta + ) pre_retirement_policy = final_policy pre_retirement_reason = final_reason ( @@ -994,7 +1009,9 @@ def _apply_exception_pattern_learning( ) if recovery_status in {"candidate", "earned"}: pattern_status = "recovering" - pattern_reason = _recovery_pattern_reason(recovery_status, recovery_reason) + pattern_reason = _recovery_pattern_reason( + recovery_status, recovery_reason + ) elif recovery_status == "blocked" and pattern_status == "none": pattern_status = "recovering" pattern_reason = recovery_reason @@ -1024,8 +1041,12 @@ def _apply_exception_pattern_learning( "primary_target_exception_pattern_reason": primary_target.get( "exception_pattern_reason", "" ), - "primary_target_trust_recovery_status": primary_target.get("trust_recovery_status", "none"), - "primary_target_trust_recovery_reason": primary_target.get("trust_recovery_reason", ""), + "primary_target_trust_recovery_status": primary_target.get( + "trust_recovery_status", "none" + ), + "primary_target_trust_recovery_reason": primary_target.get( + "trust_recovery_reason", "" + ), "exception_pattern_summary": _exception_pattern_summary( primary_target, false_positive_hotspots ), @@ -1074,16 +1095,22 @@ def _apply_exception_retirement( retirement_status = "none" retirement_reason = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) if _recommendation_bucket(target) == current_bucket: - history_meta = _target_retirement_history(target, retirement_events, historical_cases) + history_meta = _target_retirement_history( + target, retirement_events, historical_cases + ) stable_after_exception_runs = history_meta["stable_after_exception_runs"] recent_retirement_path = history_meta["recent_retirement_path"] - recovery_score, recovery_label, recovery_reasons = _recovery_confidence_for_target( - target, - history_meta, - confidence_calibration, + recovery_score, recovery_label, recovery_reasons = ( + _recovery_confidence_for_target( + target, + history_meta, + confidence_calibration, + ) ) ( retirement_status, @@ -1196,7 +1223,9 @@ def _apply_class_trust_normalization( class_sticky_rate = 0.0 recent_class_policy_path = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) if _recommendation_bucket(target) == current_bucket: history_meta = _target_class_normalization_history( @@ -1226,7 +1255,9 @@ def _apply_class_trust_normalization( updated_targets.append( { **target, - "pre_class_normalization_trust_policy": target.get("trust_policy", "monitor"), + "pre_class_normalization_trust_policy": target.get( + "trust_policy", "monitor" + ), "pre_class_normalization_trust_policy_reason": target.get( "trust_policy_reason", "No trust-policy reason is recorded yet.", @@ -1256,15 +1287,21 @@ def _apply_class_trust_normalization( mode="normalized", ) return { - "primary_target_policy_debt_status": primary_target.get("policy_debt_status", "none"), - "primary_target_policy_debt_reason": primary_target.get("policy_debt_reason", ""), + "primary_target_policy_debt_status": primary_target.get( + "policy_debt_status", "none" + ), + "primary_target_policy_debt_reason": primary_target.get( + "policy_debt_reason", "" + ), "primary_target_class_normalization_status": primary_target.get( "class_normalization_status", "none" ), "primary_target_class_normalization_reason": primary_target.get( "class_normalization_reason", "" ), - "policy_debt_summary": _policy_debt_summary(primary_target, policy_debt_hotspots), + "policy_debt_summary": _policy_debt_summary( + primary_target, policy_debt_hotspots + ), "trust_normalization_summary": _trust_normalization_summary( primary_target, normalized_class_hotspots, @@ -1316,7 +1353,9 @@ def _apply_class_memory_decay( class_decay_status = "none" class_decay_reason = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) policy_debt_status = target.get("policy_debt_status", "none") policy_debt_reason = target.get("policy_debt_reason", "") class_normalization_status = target.get("class_normalization_status", "none") @@ -1329,7 +1368,9 @@ def _apply_class_memory_decay( freshness_status = history_meta["class_memory_freshness_status"] freshness_reason = history_meta["class_memory_freshness_reason"] class_memory_weight = history_meta["class_memory_weight"] - decayed_class_retirement_rate = history_meta["decayed_class_retirement_rate"] + decayed_class_retirement_rate = history_meta[ + "decayed_class_retirement_rate" + ] decayed_class_sticky_rate = history_meta["decayed_class_sticky_rate"] recent_class_signal_mix = history_meta["recent_class_signal_mix"] ( @@ -1375,8 +1416,12 @@ def _apply_class_memory_decay( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - stale_class_memory_hotspots = _class_memory_hotspots(resolution_targets, mode="stale") - fresh_class_signal_hotspots = _class_memory_hotspots(resolution_targets, mode="fresh") + stale_class_memory_hotspots = _class_memory_hotspots( + resolution_targets, mode="stale" + ) + fresh_class_signal_hotspots = _class_memory_hotspots( + resolution_targets, mode="fresh" + ) return { "primary_target_class_memory_freshness_status": primary_target.get( "class_memory_freshness_status", "insufficient-data" @@ -1384,8 +1429,12 @@ def _apply_class_memory_decay( "primary_target_class_memory_freshness_reason": primary_target.get( "class_memory_freshness_reason", "" ), - "primary_target_class_decay_status": primary_target.get("class_decay_status", "none"), - "primary_target_class_decay_reason": primary_target.get("class_decay_reason", ""), + "primary_target_class_decay_status": primary_target.get( + "class_decay_status", "none" + ), + "primary_target_class_decay_reason": primary_target.get( + "class_decay_reason", "" + ), "class_memory_summary": _class_memory_summary( primary_target, fresh_class_signal_hotspots, stale_class_memory_hotspots ), @@ -1437,7 +1486,9 @@ def _apply_class_trust_reweighting( class_trust_reweight_effect = "none" class_trust_reweight_effect_reason = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) policy_debt_status = target.get("policy_debt_status", "none") policy_debt_reason = target.get("policy_debt_reason", "") class_normalization_status = target.get("class_normalization_status", "none") @@ -1500,8 +1551,12 @@ def _apply_class_trust_reweighting( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - supporting_class_hotspots = _class_reweight_hotspots(resolution_targets, mode="supporting") - caution_class_hotspots = _class_reweight_hotspots(resolution_targets, mode="caution") + supporting_class_hotspots = _class_reweight_hotspots( + resolution_targets, mode="supporting" + ) + caution_class_hotspots = _class_reweight_hotspots( + resolution_targets, mode="caution" + ) return { "primary_target_weighted_class_support_score": primary_target.get( "weighted_class_support_score", 0.0 @@ -1646,9 +1701,7 @@ def _class_trust_support_reason( if target.get("trust_recovery_status") in {"candidate", "earned"}: return "Trust recovery is reinforcing healthier class behavior." if decayed_class_retirement_rate * freshness_multiplier >= 0.30: - return ( - "Fresh retired-like class evidence is still carrying meaningful normalization support." - ) + return "Fresh retired-like class evidence is still carrying meaningful normalization support." return "" @@ -1709,9 +1762,16 @@ def _class_trust_reweight_for_target( ) can_strengthen = ( - freshness_status == "fresh" and not local_noise and calibration_status == "healthy" + freshness_status == "fresh" + and not local_noise + and calibration_status == "healthy" ) - can_soften = freshness_status in {"fresh", "mixed-age", "stale", "insufficient-data"} + can_soften = freshness_status in { + "fresh", + "mixed-age", + "stale", + "insufficient-data", + } if ( class_normalization_status == "candidate" @@ -1730,9 +1790,15 @@ def _class_trust_reweight_for_target( boosted_reason, ) - if class_normalization_status == "applied" and class_trust_reweight_score < 0.10 and can_soften: + if ( + class_normalization_status == "applied" + and class_trust_reweight_score < 0.10 + and can_soften + ): softened_reason = "Class normalization stayed visible, but fresh support is no longer strong enough to keep the full stronger posture in place." - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) if trust_policy == "act-with-review" and reverted_policy == "verify-first": trust_policy = reverted_policy trust_policy_reason = softened_reason @@ -1752,9 +1818,7 @@ def _class_trust_reweight_for_target( and class_trust_reweight_score <= -0.20 and freshness_status == "fresh" ): - strengthened_reason = ( - "Fresh class caution is still strong enough to keep this class in sticky caution." - ) + strengthened_reason = "Fresh class caution is still strong enough to keep this class in sticky caution." return ( "policy-debt-strengthened", strengthened_reason, @@ -1766,7 +1830,11 @@ def _class_trust_reweight_for_target( class_normalization_reason, ) - if policy_debt_status == "class-debt" and class_trust_reweight_score > -0.10 and can_soften: + if ( + policy_debt_status == "class-debt" + and class_trust_reweight_score > -0.10 + and can_soften + ): softened_reason = "Class-level caution is fading rather than disappearing all at once, so this class softens from class-debt to watch." return ( "policy-debt-softened", @@ -1791,7 +1859,9 @@ def _class_trust_reweight_for_target( ) -def _class_reweight_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: +def _class_reweight_hotspots( + resolution_targets: list[dict], *, mode: str +) -> list[dict]: grouped: dict[str, dict] = {} for target in resolution_targets: class_key = _target_class_key(target) @@ -1803,19 +1873,27 @@ def _class_reweight_hotspots(resolution_targets: list[dict], *, mode: str) -> li "label": class_key, "direction": target.get("class_trust_reweight_direction", "neutral"), "reweight_score": target.get("class_trust_reweight_score", 0.0), - "weighted_class_support_score": target.get("weighted_class_support_score", 0.0), - "weighted_class_caution_score": target.get("weighted_class_caution_score", 0.0), + "weighted_class_support_score": target.get( + "weighted_class_support_score", 0.0 + ), + "weighted_class_caution_score": target.get( + "weighted_class_caution_score", 0.0 + ), "class_memory_freshness_status": target.get( "class_memory_freshness_status", "insufficient-data" ), "effect": target.get("class_trust_reweight_effect", "none"), } - if existing is None or abs(current["reweight_score"]) > abs(existing["reweight_score"]): + if existing is None or abs(current["reweight_score"]) > abs( + existing["reweight_score"] + ): grouped[class_key] = current hotspots = list(grouped.values()) if mode == "supporting": - hotspots = [item for item in hotspots if item.get("reweight_score", 0.0) >= 0.20] + hotspots = [ + item for item in hotspots if item.get("reweight_score", 0.0) >= 0.20 + ] hotspots.sort( key=lambda item: ( -item.get("reweight_score", 0.0), @@ -1824,7 +1902,9 @@ def _class_reweight_hotspots(resolution_targets: list[dict], *, mode: str) -> li ) ) else: - hotspots = [item for item in hotspots if item.get("reweight_score", 0.0) <= -0.20] + hotspots = [ + item for item in hotspots if item.get("reweight_score", 0.0) <= -0.20 + ] hotspots.sort( key=lambda item: ( item.get("reweight_score", 0.0), @@ -1909,7 +1989,9 @@ def _apply_class_trust_momentum( transition_reason = "" recent_path = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) policy_debt_status = target.get("policy_debt_status", "none") policy_debt_reason = target.get("policy_debt_reason", "") class_normalization_status = target.get("class_normalization_status", "none") @@ -1918,8 +2000,12 @@ def _apply_class_trust_momentum( if _recommendation_bucket(target) == current_bucket: history_meta = _target_class_reweight_history(target, reweight_events) momentum_score = history_meta.get("class_trust_momentum_score", 0.0) - momentum_status = history_meta.get("class_trust_momentum_status", "insufficient-data") - stability_status = history_meta.get("class_reweight_stability_status", "watch") + momentum_status = history_meta.get( + "class_trust_momentum_status", "insufficient-data" + ) + stability_status = history_meta.get( + "class_reweight_stability_status", "watch" + ) recent_path = history_meta.get("recent_class_reweight_path", "") ( transition_status, @@ -1962,8 +2048,12 @@ def _apply_class_trust_momentum( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - sustained_class_hotspots = _class_momentum_hotspots(resolution_targets, mode="sustained") - oscillating_class_hotspots = _class_momentum_hotspots(resolution_targets, mode="oscillating") + sustained_class_hotspots = _class_momentum_hotspots( + resolution_targets, mode="sustained" + ) + oscillating_class_hotspots = _class_momentum_hotspots( + resolution_targets, mode="oscillating" + ) return { "primary_target_class_trust_momentum_score": primary_target.get( "class_trust_momentum_score", 0.0 @@ -2032,7 +2122,9 @@ def _apply_class_transition_resolution( transition_age_runs = 0 recent_transition_path = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") policy_debt_status = target.get("policy_debt_status", "none") @@ -2093,8 +2185,12 @@ def _apply_class_transition_resolution( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - stalled_transition_hotspots = _class_transition_hotspots(resolution_targets, mode="stalled") - resolving_transition_hotspots = _class_transition_hotspots(resolution_targets, mode="resolving") + stalled_transition_hotspots = _class_transition_hotspots( + resolution_targets, mode="stalled" + ) + resolving_transition_hotspots = _class_transition_hotspots( + resolution_targets, mode="resolving" + ) return { "primary_target_class_transition_health_status": primary_target.get( "class_transition_health_status", "none" @@ -2170,7 +2266,9 @@ def _apply_transition_closure_confidence( pending_resolution_rate = 0.0 recent_pending_debt_path = "" final_policy = target.get("trust_policy", "monitor") - final_reason = target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + final_reason = target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) health_status = target.get("class_transition_health_status", "none") health_reason = target.get("class_transition_health_reason", "") resolution_status = target.get("class_transition_resolution_status", "none") @@ -2185,7 +2283,9 @@ def _apply_transition_closure_confidence( if _recommendation_bucket(target) == current_bucket: history_meta = _target_class_transition_history(target, transition_events) transition_score_delta = history_meta.get("transition_score_delta", 0.0) - recent_transition_score_path = history_meta.get("recent_transition_score_path", "") + recent_transition_score_path = history_meta.get( + "recent_transition_score_path", "" + ) ( closure_score, closure_label, @@ -2268,7 +2368,9 @@ def _apply_transition_closure_confidence( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - pending_debt_hotspots = _class_pending_debt_hotspots(resolution_targets, mode="debt") + pending_debt_hotspots = _class_pending_debt_hotspots( + resolution_targets, mode="debt" + ) healthy_pending_resolution_hotspots = _class_pending_debt_hotspots( resolution_targets, mode="healthy", @@ -2380,7 +2482,9 @@ def _apply_pending_debt_freshness_and_closure_forecast_reweighting( closure_forecast_reweight_reasons: list[str] = [] closure_forecast_reweight_effect = "none" closure_forecast_reweight_effect_reason = "" - transition_closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") + transition_closure_likely_outcome = target.get( + "transition_closure_likely_outcome", "none" + ) transition_closure_confidence_label = target.get( "transition_closure_confidence_label", "low" ) @@ -2400,19 +2504,31 @@ def _apply_pending_debt_freshness_and_closure_forecast_reweighting( class_normalization_reason = target.get("class_normalization_reason", "") if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) pending_history_meta = _pending_debt_freshness_for_target( target, historical_transition_events, ) - pending_debt_freshness_status = pending_history_meta["pending_debt_freshness_status"] - pending_debt_freshness_reason = pending_history_meta["pending_debt_freshness_reason"] - pending_debt_memory_weight = pending_history_meta["pending_debt_memory_weight"] - decayed_pending_debt_rate = pending_history_meta["decayed_pending_debt_rate"] + pending_debt_freshness_status = pending_history_meta[ + "pending_debt_freshness_status" + ] + pending_debt_freshness_reason = pending_history_meta[ + "pending_debt_freshness_reason" + ] + pending_debt_memory_weight = pending_history_meta[ + "pending_debt_memory_weight" + ] + decayed_pending_debt_rate = pending_history_meta[ + "decayed_pending_debt_rate" + ] decayed_pending_resolution_rate = pending_history_meta[ "decayed_pending_resolution_rate" ] - recent_pending_signal_mix = pending_history_meta["recent_pending_signal_mix"] + recent_pending_signal_mix = pending_history_meta[ + "recent_pending_signal_mix" + ] ( weighted_pending_resolution_support_score, weighted_pending_debt_caution_score, @@ -2496,7 +2612,9 @@ def _apply_pending_debt_freshness_and_closure_forecast_reweighting( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - pending_debt_hotspots = _class_pending_debt_hotspots(resolution_targets, mode="debt") + pending_debt_hotspots = _class_pending_debt_hotspots( + resolution_targets, mode="debt" + ) healthy_pending_resolution_hotspots = _class_pending_debt_hotspots( resolution_targets, mode="healthy", @@ -2639,7 +2757,9 @@ def _class_transition_events( ) -def _target_class_transition_history(target: dict, transition_events: list[dict]) -> dict: +def _target_class_transition_history( + target: dict, transition_events: list[dict] +) -> dict: return _target_class_transition_history_helper( target, transition_events, @@ -2663,7 +2783,9 @@ def _pending_transition_direction(transition_status: str) -> str: return _pending_transition_direction_helper(transition_status) -def _current_transition_strengthening(transition_status: str, scores: list[float]) -> bool: +def _current_transition_strengthening( + transition_status: str, scores: list[float] +) -> bool: return _current_transition_strengthening_helper(transition_status, scores) @@ -2675,7 +2797,9 @@ def _transition_closure_confidence_for_target( target, history_meta, target_specific_normalization_noise=_target_specific_normalization_noise, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), + clamp_round=lambda value, lower, upper: _clamp_round( + value, lower=lower, upper=upper + ), ) @@ -2726,7 +2850,9 @@ def _class_pending_debt_for_target( target, transition_events, target_class_key=_target_class_key, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), + clamp_round=lambda value, lower, upper: _clamp_round( + value, lower=lower, upper=upper + ), class_pending_debt_window_runs=CLASS_PENDING_DEBT_WINDOW_RUNS, ) @@ -2735,7 +2861,9 @@ def _pending_debt_event_outcome(event: dict) -> str: return _pending_debt_event_outcome_helper(event) -def _class_pending_debt_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: +def _class_pending_debt_hotspots( + resolution_targets: list[dict], *, mode: str +) -> list[dict]: return _class_pending_debt_hotspots_helper( resolution_targets, mode=mode, @@ -2743,7 +2871,9 @@ def _class_pending_debt_hotspots(resolution_targets: list[dict], *, mode: str) - ) -def _pending_debt_freshness_for_target(target: dict, transition_events: list[dict]) -> dict: +def _pending_debt_freshness_for_target( + target: dict, transition_events: list[dict] +) -> dict: return _pending_debt_freshness_for_target_helper( target, transition_events, @@ -2805,7 +2935,9 @@ def _closure_forecast_reweight_scores_for_target( transition_history_meta, pending_history_meta, target_specific_normalization_noise=_target_specific_normalization_noise, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), + clamp_round=lambda value, lower, upper: _clamp_round( + value, lower=lower, upper=upper + ), ) @@ -2855,7 +2987,9 @@ def _apply_closure_forecast_reweighting_control( ) -def _pending_debt_freshness_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: +def _pending_debt_freshness_hotspots( + resolution_targets: list[dict], *, mode: str +) -> list[dict]: return _pending_debt_freshness_hotspots_helper( resolution_targets, mode=mode, @@ -2863,7 +2997,9 @@ def _pending_debt_freshness_hotspots(resolution_targets: list[dict], *, mode: st ) -def _closure_forecast_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: +def _closure_forecast_hotspots( + resolution_targets: list[dict], *, mode: str +) -> list[dict]: return _closure_forecast_hotspots_helper( resolution_targets, mode=mode, @@ -2922,7 +3058,9 @@ def _apply_closure_forecast_momentum_and_hysteresis( hysteresis_status = "none" hysteresis_reason = "" recent_path = "" - transition_closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") + transition_closure_likely_outcome = target.get( + "transition_closure_likely_outcome", "none" + ) transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") resolution_status = target.get("class_transition_resolution_status", "none") @@ -2940,8 +3078,12 @@ def _apply_closure_forecast_momentum_and_hysteresis( transition_history_meta: dict = {} if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) - history_meta = _target_closure_forecast_history(target, closure_forecast_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) + history_meta = _target_closure_forecast_history( + target, closure_forecast_events + ) momentum_score = history_meta["closure_forecast_momentum_score"] momentum_status = history_meta["closure_forecast_momentum_status"] stability_status = history_meta["closure_forecast_stability_status"] @@ -3008,7 +3150,9 @@ def _apply_closure_forecast_momentum_and_hysteresis( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - pending_debt_hotspots = _class_pending_debt_hotspots(resolution_targets, mode="debt") + pending_debt_hotspots = _class_pending_debt_hotspots( + resolution_targets, mode="debt" + ) healthy_pending_resolution_hotspots = _class_pending_debt_hotspots( resolution_targets, mode="healthy", @@ -3161,7 +3305,9 @@ def _apply_closure_forecast_freshness_and_decay( decay_status = "none" decay_reason = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -3179,12 +3325,18 @@ def _apply_closure_forecast_freshness_and_decay( class_normalization_reason = target.get("class_normalization_reason", "") if _recommendation_bucket(target) == current_bucket: - freshness_meta = _closure_forecast_freshness_for_target(target, closure_forecast_events) - transition_history_meta = _target_class_transition_history(target, transition_events) + freshness_meta = _closure_forecast_freshness_for_target( + target, closure_forecast_events + ) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) freshness_status = freshness_meta["closure_forecast_freshness_status"] freshness_reason = freshness_meta["closure_forecast_freshness_reason"] memory_weight = freshness_meta["closure_forecast_memory_weight"] - decayed_confirmation_rate = freshness_meta["decayed_confirmation_forecast_rate"] + decayed_confirmation_rate = freshness_meta[ + "decayed_confirmation_forecast_rate" + ] decayed_clearance_rate = freshness_meta["decayed_clearance_forecast_rate"] signal_mix = freshness_meta["recent_closure_forecast_signal_mix"] ( @@ -3335,7 +3487,9 @@ def _apply_closure_forecast_refresh_recovery_and_reacquisition( reacquisition_reason = "" refresh_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -3353,14 +3507,20 @@ def _apply_closure_forecast_refresh_recovery_and_reacquisition( class_normalization_reason = target.get("class_normalization_reason", "") if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) refresh_meta = _closure_forecast_refresh_recovery_for_target( target, closure_forecast_events, transition_history_meta, ) - refresh_recovery_score = refresh_meta["closure_forecast_refresh_recovery_score"] - refresh_recovery_status = refresh_meta["closure_forecast_refresh_recovery_status"] + refresh_recovery_score = refresh_meta[ + "closure_forecast_refresh_recovery_score" + ] + refresh_recovery_status = refresh_meta[ + "closure_forecast_refresh_recovery_status" + ] reacquisition_status = refresh_meta["closure_forecast_reacquisition_status"] reacquisition_reason = refresh_meta["closure_forecast_reacquisition_reason"] refresh_path = refresh_meta["recent_closure_forecast_refresh_path"] @@ -3515,7 +3675,9 @@ def _apply_reacquisition_persistence_and_recovery_churn( churn_reason = "" churn_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -3533,7 +3695,9 @@ def _apply_reacquisition_persistence_and_recovery_churn( class_normalization_reason = target.get("class_normalization_reason", "") if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) persistence_meta = _closure_forecast_reacquisition_persistence_for_target( target, closure_forecast_events, @@ -3544,8 +3708,12 @@ def _apply_reacquisition_persistence_and_recovery_churn( closure_forecast_events, transition_history_meta, ) - persistence_age_runs = persistence_meta["closure_forecast_reacquisition_age_runs"] - persistence_score = persistence_meta["closure_forecast_reacquisition_persistence_score"] + persistence_age_runs = persistence_meta[ + "closure_forecast_reacquisition_age_runs" + ] + persistence_score = persistence_meta[ + "closure_forecast_reacquisition_persistence_score" + ] persistence_status = persistence_meta[ "closure_forecast_reacquisition_persistence_status" ] @@ -3721,7 +3889,9 @@ def _apply_reacquisition_freshness_and_persistence_reset( persistence_reset_status = "none" persistence_reset_reason = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -3737,15 +3907,25 @@ def _apply_reacquisition_freshness_and_persistence_reset( policy_debt_reason = target.get("policy_debt_reason", "") class_normalization_status = target.get("class_normalization_status", "none") class_normalization_reason = target.get("class_normalization_reason", "") - reacquisition_status = target.get("closure_forecast_reacquisition_status", "none") + reacquisition_status = target.get( + "closure_forecast_reacquisition_status", "none" + ) reacquisition_reason = target.get("closure_forecast_reacquisition_reason", "") persistence_age_runs = target.get("closure_forecast_reacquisition_age_runs", 0) - persistence_score = target.get("closure_forecast_reacquisition_persistence_score", 0.0) - persistence_status = target.get("closure_forecast_reacquisition_persistence_status", "none") - persistence_reason = target.get("closure_forecast_reacquisition_persistence_reason", "") + persistence_score = target.get( + "closure_forecast_reacquisition_persistence_score", 0.0 + ) + persistence_status = target.get( + "closure_forecast_reacquisition_persistence_status", "none" + ) + persistence_reason = target.get( + "closure_forecast_reacquisition_persistence_reason", "" + ) if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) freshness_meta = _closure_forecast_reacquisition_freshness_for_target( target, closure_forecast_events, @@ -3762,8 +3942,12 @@ def _apply_reacquisition_freshness_and_persistence_reset( decayed_reacquired_confirmation_rate = freshness_meta[ "decayed_reacquired_confirmation_rate" ] - decayed_reacquired_clearance_rate = freshness_meta["decayed_reacquired_clearance_rate"] - recent_reacquisition_signal_mix = freshness_meta["recent_reacquisition_signal_mix"] + decayed_reacquired_clearance_rate = freshness_meta[ + "decayed_reacquired_clearance_rate" + ] + recent_reacquisition_signal_mix = freshness_meta[ + "recent_reacquisition_signal_mix" + ] control_updates = _apply_reacquisition_freshness_reset_control( target, freshness_meta=freshness_meta, @@ -3790,11 +3974,21 @@ def _apply_reacquisition_freshness_and_persistence_reset( persistence_status=persistence_status, persistence_reason=persistence_reason, ) - persistence_reset_status = control_updates["closure_forecast_persistence_reset_status"] - persistence_reset_reason = control_updates["closure_forecast_persistence_reset_reason"] - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + persistence_reset_status = control_updates[ + "closure_forecast_persistence_reset_status" + ] + persistence_reset_reason = control_updates[ + "closure_forecast_persistence_reset_reason" + ] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -3807,10 +4001,18 @@ def _apply_reacquisition_freshness_and_persistence_reset( policy_debt_reason = control_updates["policy_debt_reason"] class_normalization_status = control_updates["class_normalization_status"] class_normalization_reason = control_updates["class_normalization_reason"] - reacquisition_status = control_updates["closure_forecast_reacquisition_status"] - reacquisition_reason = control_updates["closure_forecast_reacquisition_reason"] - persistence_age_runs = control_updates["closure_forecast_reacquisition_age_runs"] - persistence_score = control_updates["closure_forecast_reacquisition_persistence_score"] + reacquisition_status = control_updates[ + "closure_forecast_reacquisition_status" + ] + reacquisition_reason = control_updates[ + "closure_forecast_reacquisition_reason" + ] + persistence_age_runs = control_updates[ + "closure_forecast_reacquisition_age_runs" + ] + persistence_score = control_updates[ + "closure_forecast_reacquisition_persistence_score" + ] persistence_status = control_updates[ "closure_forecast_reacquisition_persistence_status" ] @@ -3859,9 +4061,11 @@ def _apply_reacquisition_freshness_and_persistence_reset( resolution_targets, mode="stale", ) - fresh_reacquisition_signal_hotspots = _closure_forecast_reacquisition_freshness_hotspots( - resolution_targets, - mode="fresh", + fresh_reacquisition_signal_hotspots = ( + _closure_forecast_reacquisition_freshness_hotspots( + resolution_targets, + mode="fresh", + ) ) return { "primary_target_closure_forecast_reacquisition_freshness_status": primary_target.get( @@ -3896,107 +4100,6 @@ def _apply_reacquisition_freshness_and_persistence_reset( } -def _closure_forecast_reset_side_from_status(status: str) -> str: - return _closure_forecast_reset_side_from_status_helper(status) - - -def _closure_forecast_reset_refresh_path_label(event: dict) -> str: - return _closure_forecast_reset_refresh_path_label_helper( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ) - - -def _closure_forecast_reset_refresh_recovery_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_refresh_recovery_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - target_class_key=_target_class_key, - closure_forecast_reset_side_from_status=_closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_refresh_path_label=_closure_forecast_reset_refresh_path_label, - class_reset_reentry_window_runs=CLASS_RESET_REENTRY_WINDOW_RUNS, - ) - - -def _apply_reset_refresh_reentry_control( - target: dict, - *, - refresh_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reacquisition_status: str, - reacquisition_reason: str, -) -> dict: - return _apply_reset_refresh_reentry_control_helper( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reacquisition_status=reacquisition_status, - reacquisition_reason=reacquisition_reason, - ) - - -def _closure_forecast_reset_refresh_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_refresh_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_refresh_recovery_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_refresh_recovery_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - def _apply_reacquisition_reset_refresh_recovery_and_reentry( resolution_targets: list[dict], history: list[dict], @@ -4038,21 +4141,35 @@ def _apply_reacquisition_reset_refresh_recovery_and_reentry( reset_reentry_reason = "" reset_refresh_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") resolution_status = target.get("class_transition_resolution_status", "none") resolution_reason = target.get("class_transition_resolution_reason", "") - reacquisition_status = target.get("closure_forecast_reacquisition_status", "none") + reacquisition_status = target.get( + "closure_forecast_reacquisition_status", "none" + ) reacquisition_reason = target.get("closure_forecast_reacquisition_reason", "") - reacquisition_age_runs = target.get("closure_forecast_reacquisition_age_runs", 0) - persistence_score = target.get("closure_forecast_reacquisition_persistence_score", 0.0) - persistence_status = target.get("closure_forecast_reacquisition_persistence_status", "none") - persistence_reason = target.get("closure_forecast_reacquisition_persistence_reason", "") + reacquisition_age_runs = target.get( + "closure_forecast_reacquisition_age_runs", 0 + ) + persistence_score = target.get( + "closure_forecast_reacquisition_persistence_score", 0.0 + ) + persistence_status = target.get( + "closure_forecast_reacquisition_persistence_status", "none" + ) + persistence_reason = target.get( + "closure_forecast_reacquisition_persistence_reason", "" + ) if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) refresh_meta = _closure_forecast_reset_refresh_recovery_for_target( target, closure_forecast_events, @@ -4081,17 +4198,31 @@ def _apply_reacquisition_reset_refresh_recovery_and_reentry( reacquisition_status=reacquisition_status, reacquisition_reason=reacquisition_reason, ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] resolution_reason = control_updates["class_transition_resolution_reason"] - reacquisition_status = control_updates["closure_forecast_reacquisition_status"] - reacquisition_reason = control_updates["closure_forecast_reacquisition_reason"] - reacquisition_age_runs = control_updates["closure_forecast_reacquisition_age_runs"] - persistence_score = control_updates["closure_forecast_reacquisition_persistence_score"] + reacquisition_status = control_updates[ + "closure_forecast_reacquisition_status" + ] + reacquisition_reason = control_updates[ + "closure_forecast_reacquisition_reason" + ] + reacquisition_age_runs = control_updates[ + "closure_forecast_reacquisition_age_runs" + ] + persistence_score = control_updates[ + "closure_forecast_reacquisition_persistence_score" + ] persistence_status = control_updates[ "closure_forecast_reacquisition_persistence_status" ] @@ -4125,9 +4256,11 @@ def _apply_reacquisition_reset_refresh_recovery_and_reentry( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - recovering_from_confirmation_reset_hotspots = _closure_forecast_reset_refresh_hotspots( - resolution_targets, - mode="confirmation", + recovering_from_confirmation_reset_hotspots = ( + _closure_forecast_reset_refresh_hotspots( + resolution_targets, + mode="confirmation", + ) ) recovering_from_clearance_reset_hotspots = _closure_forecast_reset_refresh_hotspots( resolution_targets, @@ -4166,63 +4299,20 @@ def _apply_reacquisition_reset_refresh_recovery_and_reentry( } -@lru_cache(maxsize=None) -def _side_sets(confirmation_members: tuple[str, ...]) -> tuple[frozenset[str], frozenset[str]]: - return ( - frozenset(confirmation_members), - frozenset(member.replace("confirmation", "clearance") for member in confirmation_members), - ) - - -def _resolve_side(status: str, *confirmation_members: str) -> str: - # Shared side classifier for the reset/reentry/rebuild/restore status families. The - # clearance-side set is the confirmation-side set with "confirmation" swapped for - # "clearance"; confirmation membership wins, so a confirmation-only token (e.g. - # "just-rererestored") resolves to confirmation even though the swap also lands it - # in clearance. Returns "none" for anything unrecognized. - confirmation, clearance = _side_sets(confirmation_members) - if status in confirmation: - return "confirmation" - if status in clearance: - return "clearance" - return "none" - - -def _closure_forecast_reset_reentry_side_from_status(status: str) -> str: - return _resolve_side( - status, - "pending-confirmation-reentry", - "reentered-confirmation", - ) - - -def _closure_forecast_reset_reentry_side_from_recovery_status(status: str) -> str: - return _resolve_side( - status, - "recovering-confirmation-reset", - "reentering-confirmation", - ) - - -def _closure_forecast_reset_reentry_side_from_event(event: dict) -> str: - side = _closure_forecast_reset_reentry_side_from_status( - event.get("closure_forecast_reset_reentry_status", "none") - ) - if side != "none": - return side - return _closure_forecast_reset_reentry_side_from_recovery_status( - event.get("closure_forecast_reset_refresh_recovery_status", "none") - ) - - def _closure_forecast_reset_reentry_path_label(event: dict) -> str: - reentry_status = event.get("closure_forecast_reset_reentry_status", "none") or "none" + reentry_status = ( + event.get("closure_forecast_reset_reentry_status", "none") or "none" + ) if reentry_status != "none": return reentry_status - recovery_status = event.get("closure_forecast_reset_refresh_recovery_status", "none") or "none" + recovery_status = ( + event.get("closure_forecast_reset_refresh_recovery_status", "none") or "none" + ) if recovery_status != "none": return recovery_status - reset_status = event.get("closure_forecast_persistence_reset_status", "none") or "none" + reset_status = ( + event.get("closure_forecast_persistence_reset_status", "none") or "none" + ) if reset_status != "none": return reset_status likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" @@ -4231,326 +4321,6 @@ def _closure_forecast_reset_reentry_path_label(event: dict) -> str: return "hold" -def _closure_forecast_event_matches_target_state(event: dict, target: dict) -> bool: - return ( - event.get("key") == _queue_identity(target) - and event.get("class_key") == _target_class_key(target) - and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) - == float(target.get("closure_forecast_reweight_score", 0.0) or 0.0) - and event.get("closure_forecast_reweight_direction", "neutral") - == target.get("closure_forecast_reweight_direction", "neutral") - and event.get("closure_forecast_reset_refresh_recovery_status", "none") - == target.get("closure_forecast_reset_refresh_recovery_status", "none") - and event.get("closure_forecast_reset_reentry_status", "none") - == target.get("closure_forecast_reset_reentry_status", "none") - and event.get("closure_forecast_reset_reentry_persistence_status", "none") - == target.get("closure_forecast_reset_reentry_persistence_status", "none") - and event.get("closure_forecast_reset_reentry_churn_status", "none") - == target.get("closure_forecast_reset_reentry_churn_status", "none") - and event.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") - == target.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") - and event.get("closure_forecast_reset_reentry_reset_status", "none") - == target.get("closure_forecast_reset_reentry_reset_status", "none") - and event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") - == target.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") - and event.get( - "closure_forecast_reset_reentry_rebuild_freshness_status", "insufficient-data" - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_freshness_status", "insufficient-data" - ) - and event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_refresh_recovery_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_refresh_recovery_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_status", "none") - and event.get("closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none") - and event.get( - "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", "insufficient-data" - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", "insufficient-data" - ) - and event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") - and event.get( - "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", "none" - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", "none" - ) - and event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") - and event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", "none" - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", "none" - ) - and event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", "none") - and event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", - "insufficient-data", - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", - "insufficient-data", - ) - and event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status", "none") - == target.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status", "none") - and event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", "none" - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", "none" - ) - and event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", "none" - ) - == target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", "none" - ) - and event.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") - == target.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") - and event.get("closure_forecast_persistence_reset_status", "none") - == target.get("closure_forecast_persistence_reset_status", "none") - and event.get("transition_closure_likely_outcome", "none") - == target.get("transition_closure_likely_outcome", "none") - ) - - -def _current_closure_forecast_event_for_target(target: dict) -> dict: - return { - "key": _queue_identity(target), - "class_key": _target_class_key(target), - "label": _target_label(target), - "generated_at": "", - "closure_forecast_reweight_score": target.get("closure_forecast_reweight_score", 0.0), - "closure_forecast_reweight_direction": target.get( - "closure_forecast_reweight_direction", - "neutral", - ), - "transition_closure_likely_outcome": target.get( - "transition_closure_likely_outcome", - "none", - ), - "class_reweight_transition_status": target.get( - "class_reweight_transition_status", - "none", - ), - "class_transition_resolution_status": target.get( - "class_transition_resolution_status", - "none", - ), - "closure_forecast_hysteresis_status": target.get( - "closure_forecast_hysteresis_status", - "none", - ), - "closure_forecast_momentum_status": target.get( - "closure_forecast_momentum_status", - "insufficient-data", - ), - "closure_forecast_stability_status": target.get( - "closure_forecast_stability_status", - "watch", - ), - "closure_forecast_freshness_status": target.get( - "closure_forecast_freshness_status", - "insufficient-data", - ), - "closure_forecast_decay_status": target.get( - "closure_forecast_decay_status", - "none", - ), - "closure_forecast_refresh_recovery_status": target.get( - "closure_forecast_refresh_recovery_status", - "none", - ), - "closure_forecast_reacquisition_status": target.get( - "closure_forecast_reacquisition_status", - "none", - ), - "closure_forecast_reacquisition_persistence_status": target.get( - "closure_forecast_reacquisition_persistence_status", - "none", - ), - "closure_forecast_recovery_churn_status": target.get( - "closure_forecast_recovery_churn_status", - "none", - ), - "closure_forecast_reacquisition_freshness_status": target.get( - "closure_forecast_reacquisition_freshness_status", - "insufficient-data", - ), - "closure_forecast_persistence_reset_status": target.get( - "closure_forecast_persistence_reset_status", - "none", - ), - "closure_forecast_reset_refresh_recovery_status": target.get( - "closure_forecast_reset_refresh_recovery_status", - "none", - ), - "closure_forecast_reset_reentry_status": target.get( - "closure_forecast_reset_reentry_status", - "none", - ), - "closure_forecast_reset_reentry_persistence_status": target.get( - "closure_forecast_reset_reentry_persistence_status", - "none", - ), - "closure_forecast_reset_reentry_churn_status": target.get( - "closure_forecast_reset_reentry_churn_status", - "none", - ), - "closure_forecast_reset_reentry_freshness_status": target.get( - "closure_forecast_reset_reentry_freshness_status", - "insufficient-data", - ), - "closure_forecast_reset_reentry_reset_status": target.get( - "closure_forecast_reset_reentry_reset_status", - "none", - ), - "closure_forecast_reset_reentry_refresh_recovery_status": target.get( - "closure_forecast_reset_reentry_refresh_recovery_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_status": target.get( - "closure_forecast_reset_reentry_rebuild_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_persistence_status": target.get( - "closure_forecast_reset_reentry_rebuild_persistence_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_churn_status": target.get( - "closure_forecast_reset_reentry_rebuild_churn_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_freshness_status": target.get( - "closure_forecast_reset_reentry_rebuild_freshness_status", - "insufficient-data", - ), - "closure_forecast_reset_reentry_rebuild_reset_status": target.get( - "closure_forecast_reset_reentry_rebuild_reset_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_refresh_recovery_status": target.get( - "closure_forecast_reset_reentry_rebuild_refresh_recovery_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_persistence_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_churn_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_churn_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_freshness_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", - "insufficient-data", - ), - "closure_forecast_reset_reentry_rebuild_reentry_reset_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_reset_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", - "insufficient-data", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", - "none", - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status": target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", - "none", - ), - } - - -def _ordered_reset_reentry_events_for_target( - target: dict, - closure_forecast_events: list[dict], -) -> list[dict]: - class_key = _target_class_key(target) - matching_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key - ][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] - if not matching_events: - return [_current_closure_forecast_event_for_target(target)] - - current_index = next( - ( - index - for index, event in enumerate(matching_events) - if event.get("generated_at", "") == "" and event.get("key") == _queue_identity(target) - ), - None, - ) - if current_index is not None: - if current_index == 0: - return matching_events - current_event = matching_events[current_index] - remainder = matching_events[:current_index] + matching_events[current_index + 1 :] - return [current_event, *remainder][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] - - matching_index = next( - ( - index - for index, event in enumerate(matching_events) - if _closure_forecast_event_matches_target_state(event, target) - ), - None, - ) - if matching_index is not None: - if matching_index == 0: - return matching_events - current_event = matching_events[matching_index] - remainder = matching_events[:matching_index] + matching_events[matching_index + 1 :] - return [current_event, *remainder][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] - - return [ - _current_closure_forecast_event_for_target(target), - *matching_events, - ][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] - - def _closure_forecast_reset_reentry_persistence_for_target( target: dict, closure_forecast_events: list[dict], @@ -4580,11 +4350,17 @@ def _closure_forecast_reset_reentry_persistence_for_target( weighted_total = 0.0 weight_sum = 0.0 directions: list[str] = [] - for index, event in enumerate(relevant_events[:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS]): - weight = (1.0, 0.8, 0.6, 0.4)[min(index, CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS - 1)] + for index, event in enumerate( + relevant_events[:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] + ): + weight = (1.0, 0.8, 0.6, 0.4)[ + min(index, CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS - 1) + ] event_side = _closure_forecast_reset_reentry_side_from_event(event) sign = 1.0 if event_side == "confirmation" else -1.0 - directions.append("supporting-confirmation" if sign > 0 else "supporting-clearance") + directions.append( + "supporting-confirmation" if sign > 0 else "supporting-clearance" + ) magnitude = 0.0 if event.get("closure_forecast_reset_reentry_status", "none") in { "reentered-confirmation", @@ -4596,10 +4372,12 @@ def _closure_forecast_reset_reentry_persistence_for_target( "reentering-clearance", }: magnitude += 0.10 - momentum_status = event.get("closure_forecast_momentum_status", "insufficient-data") - if (event_side == "confirmation" and momentum_status == "sustained-confirmation") or ( - event_side == "clearance" and momentum_status == "sustained-clearance" - ): + momentum_status = event.get( + "closure_forecast_momentum_status", "insufficient-data" + ) + if ( + event_side == "confirmation" and momentum_status == "sustained-confirmation" + ) or (event_side == "clearance" and momentum_status == "sustained-clearance"): magnitude += 0.10 stability_status = event.get("closure_forecast_stability_status", "watch") if stability_status == "stable": @@ -4626,7 +4404,9 @@ def _closure_forecast_reset_reentry_persistence_for_target( lower=-0.95, upper=0.95, ) - current_momentum_status = target.get("closure_forecast_momentum_status", "insufficient-data") + current_momentum_status = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) current_stability_status = target.get("closure_forecast_stability_status", "watch") current_freshness_status = target.get( "closure_forecast_reacquisition_freshness_status", @@ -4673,9 +4453,17 @@ def _closure_forecast_reset_reentry_persistence_for_target( and current_stability_status != "oscillating" ): persistence_status = "sustained-clearance-reentry" - elif current_side == "confirmation" and persistence_age_runs >= 2 and persistence_score > 0: + elif ( + current_side == "confirmation" + and persistence_age_runs >= 2 + and persistence_score > 0 + ): persistence_status = "holding-confirmation-reentry" - elif current_side == "clearance" and persistence_age_runs >= 2 and persistence_score < 0: + elif ( + current_side == "clearance" + and persistence_age_runs >= 2 + and persistence_score < 0 + ): persistence_status = "holding-clearance-reentry" else: persistence_status = "none" @@ -4703,7 +4491,9 @@ def _closure_forecast_reset_reentry_persistence_for_target( "closure_forecast_reset_reentry_persistence_status": persistence_status, "closure_forecast_reset_reentry_persistence_reason": persistence_reason, "recent_reset_reentry_persistence_path": " -> ".join( - _closure_forecast_reset_reentry_path_label(event) for event in matching_events if event + _closure_forecast_reset_reentry_path_label(event) + for event in matching_events + if event ), } @@ -4723,7 +4513,8 @@ def _closure_forecast_reset_reentry_churn_for_target( if _closure_forecast_reset_reentry_side_from_event(event) != "none" ] side_path = [ - _closure_forecast_reset_reentry_side_from_event(event) for event in relevant_events + _closure_forecast_reset_reentry_side_from_event(event) + for event in relevant_events ] current_side = side_path[0] if side_path else "none" local_noise = _target_specific_normalization_noise(target, transition_history_meta) @@ -4734,13 +4525,17 @@ def _closure_forecast_reset_reentry_churn_for_target( else: flip_count = _class_direction_flip_count( [ - "supporting-confirmation" if side == "confirmation" else "supporting-clearance" + "supporting-confirmation" + if side == "confirmation" + else "supporting-clearance" for side in side_path ] ) churn_score = float(flip_count) * 0.20 stability_status = target.get("closure_forecast_stability_status", "watch") - momentum_status = target.get("closure_forecast_momentum_status", "insufficient-data") + momentum_status = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) if stability_status == "oscillating": churn_score += 0.15 if momentum_status == "reversing": @@ -4748,11 +4543,14 @@ def _closure_forecast_reset_reentry_churn_for_target( if momentum_status == "unstable": churn_score += 0.10 freshness_path = [ - event.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") + event.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) for event in relevant_events ] if any( - previous == "fresh" and current in {"mixed-age", "stale", "insufficient-data"} + previous == "fresh" + and current in {"mixed-age", "stale", "insufficient-data"} for previous, current in zip(freshness_path, freshness_path[1:]) ): churn_score += 0.10 @@ -4783,9 +4581,7 @@ def _closure_forecast_reset_reentry_churn_for_target( churn_reason = "Reset re-entry recovery is flipping enough that restored posture should be softened quickly." elif churn_score >= 0.20: churn_status = "watch" - churn_reason = ( - "Reset re-entry recovery is wobbling and may lose its restored strength soon." - ) + churn_reason = "Reset re-entry recovery is wobbling and may lose its restored strength soon." else: churn_status = "none" churn_reason = "" @@ -4795,7 +4591,9 @@ def _closure_forecast_reset_reentry_churn_for_target( "closure_forecast_reset_reentry_churn_status": churn_status, "closure_forecast_reset_reentry_churn_reason": churn_reason, "recent_reset_reentry_churn_path": " -> ".join( - _closure_forecast_reset_reentry_path_label(event) for event in matching_events if event + _closure_forecast_reset_reentry_path_label(event) + for event in matching_events + if event ), } @@ -4831,7 +4629,9 @@ def _apply_reset_reentry_persistence_and_churn_control( ) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) recent_pending_status = transition_history_meta.get("recent_pending_status", "none") - current_side = _closure_forecast_reset_reentry_side_from_status(current_reentry_status) + current_side = _closure_forecast_reset_reentry_side_from_status( + current_reentry_status + ) if current_side == "none": current_side = _closure_forecast_reset_reentry_side_from_recovery_status( target.get("closure_forecast_reset_refresh_recovery_status", "none") @@ -4856,7 +4656,9 @@ def _apply_reset_reentry_persistence_and_churn_control( closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": closure_hysteresis_status = "pending-confirmation" - closure_hysteresis_reason = churn_reason or persistence_reason or closure_hysteresis_reason + closure_hysteresis_reason = ( + churn_reason or persistence_reason or closure_hysteresis_reason + ) return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -5015,7 +4817,9 @@ def _hotspots_base( "label": class_key, spec.age_key: target.get(spec.age_key, 0), spec.persistence_score_key: target.get(spec.persistence_score_key, 0.0), - spec.persistence_status_key: target.get(spec.persistence_status_key, "none"), + spec.persistence_status_key: target.get( + spec.persistence_status_key, "none" + ), spec.churn_score_key: target.get(spec.churn_score_key, 0.0), spec.churn_status_key: target.get(spec.churn_status_key, "none"), spec.persistence_path_key: target.get(spec.persistence_path_key, ""), @@ -5070,51 +4874,79 @@ def _hotspots_base( _RESET_REENTRY_HOTSPOTS_SPEC = _HotspotsTierSpec( - age_key='closure_forecast_reset_reentry_age_runs', - persistence_score_key='closure_forecast_reset_reentry_persistence_score', - persistence_status_key='closure_forecast_reset_reentry_persistence_status', - churn_score_key='closure_forecast_reset_reentry_churn_score', - churn_status_key='closure_forecast_reset_reentry_churn_status', - persistence_path_key='recent_reset_reentry_persistence_path', - churn_path_key='recent_reset_reentry_churn_path', - just_mode='just-reentered', - holding_statuses=frozenset({'holding-clearance-reentry', 'holding-confirmation-reentry', 'sustained-clearance-reentry', 'sustained-confirmation-reentry'}), + age_key="closure_forecast_reset_reentry_age_runs", + persistence_score_key="closure_forecast_reset_reentry_persistence_score", + persistence_status_key="closure_forecast_reset_reentry_persistence_status", + churn_score_key="closure_forecast_reset_reentry_churn_score", + churn_status_key="closure_forecast_reset_reentry_churn_status", + persistence_path_key="recent_reset_reentry_persistence_path", + churn_path_key="recent_reset_reentry_churn_path", + just_mode="just-reentered", + holding_statuses=frozenset( + { + "holding-clearance-reentry", + "holding-confirmation-reentry", + "sustained-clearance-reentry", + "sustained-confirmation-reentry", + } + ), ) _REBUILD_REENTRY_HOTSPOTS_SPEC = _HotspotsTierSpec( - age_key='closure_forecast_reset_reentry_rebuild_reentry_age_runs', - persistence_score_key='closure_forecast_reset_reentry_rebuild_reentry_persistence_score', - persistence_status_key='closure_forecast_reset_reentry_rebuild_reentry_persistence_status', - churn_score_key='closure_forecast_reset_reentry_rebuild_reentry_churn_score', - churn_status_key='closure_forecast_reset_reentry_rebuild_reentry_churn_status', - persistence_path_key='recent_reset_reentry_rebuild_reentry_persistence_path', - churn_path_key='recent_reset_reentry_rebuild_reentry_churn_path', - just_mode='just-reentered', - holding_statuses=frozenset({'holding-clearance-rebuild-reentry', 'holding-confirmation-rebuild-reentry', 'sustained-clearance-rebuild-reentry', 'sustained-confirmation-rebuild-reentry'}), + age_key="closure_forecast_reset_reentry_rebuild_reentry_age_runs", + persistence_score_key="closure_forecast_reset_reentry_rebuild_reentry_persistence_score", + persistence_status_key="closure_forecast_reset_reentry_rebuild_reentry_persistence_status", + churn_score_key="closure_forecast_reset_reentry_rebuild_reentry_churn_score", + churn_status_key="closure_forecast_reset_reentry_rebuild_reentry_churn_status", + persistence_path_key="recent_reset_reentry_rebuild_reentry_persistence_path", + churn_path_key="recent_reset_reentry_rebuild_reentry_churn_path", + just_mode="just-reentered", + holding_statuses=frozenset( + { + "holding-clearance-rebuild-reentry", + "holding-confirmation-rebuild-reentry", + "sustained-clearance-rebuild-reentry", + "sustained-confirmation-rebuild-reentry", + } + ), ) _RESTORE_HOTSPOTS_SPEC = _HotspotsTierSpec( - age_key='closure_forecast_reset_reentry_rebuild_reentry_restore_age_runs', - persistence_score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_score', - persistence_status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status', - churn_score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_churn_score', - churn_status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status', - persistence_path_key='recent_reset_reentry_rebuild_reentry_restore_persistence_path', - churn_path_key='recent_reset_reentry_rebuild_reentry_restore_churn_path', - just_mode='just-restored', - holding_statuses=frozenset({'holding-clearance-rebuild-reentry-restore', 'holding-confirmation-rebuild-reentry-restore', 'sustained-clearance-rebuild-reentry-restore', 'sustained-confirmation-rebuild-reentry-restore'}), + age_key="closure_forecast_reset_reentry_rebuild_reentry_restore_age_runs", + persistence_score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_score", + persistence_status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + churn_score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_churn_score", + churn_status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", + persistence_path_key="recent_reset_reentry_rebuild_reentry_restore_persistence_path", + churn_path_key="recent_reset_reentry_rebuild_reentry_restore_churn_path", + just_mode="just-restored", + holding_statuses=frozenset( + { + "holding-clearance-rebuild-reentry-restore", + "holding-confirmation-rebuild-reentry-restore", + "sustained-clearance-rebuild-reentry-restore", + "sustained-confirmation-rebuild-reentry-restore", + } + ), ) _RERESTORE_HOTSPOTS_SPEC = _HotspotsTierSpec( - age_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_age_runs', - persistence_score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_score', - persistence_status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status', - churn_score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_score', - churn_status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status', - persistence_path_key='recent_reset_reentry_rebuild_reentry_restore_rerestore_persistence_path', - churn_path_key='recent_reset_reentry_rebuild_reentry_restore_rerestore_churn_path', - just_mode='just-rerestored', - holding_statuses=frozenset({'holding-clearance-rebuild-reentry-rerestore', 'holding-confirmation-rebuild-reentry-rerestore', 'sustained-clearance-rebuild-reentry-rerestore', 'sustained-confirmation-rebuild-reentry-rerestore'}), + age_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_age_runs", + persistence_score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_score", + persistence_status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status", + churn_score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_score", + churn_status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status", + persistence_path_key="recent_reset_reentry_rebuild_reentry_restore_rerestore_persistence_path", + churn_path_key="recent_reset_reentry_rebuild_reentry_restore_rerestore_churn_path", + just_mode="just-rerestored", + holding_statuses=frozenset( + { + "holding-clearance-rebuild-reentry-rerestore", + "holding-confirmation-rebuild-reentry-rerestore", + "sustained-clearance-rebuild-reentry-rerestore", + "sustained-confirmation-rebuild-reentry-rerestore", + } + ), ) @@ -5168,7 +5000,9 @@ def _closure_forecast_reset_reentry_persistence_summary( f"Reset re-entry posture is holding most cleanly around {hotspot.get('label', 'recent hotspots')}, " "so those classes are closest to keeping restored re-entry strength safely." ) - return "No reset re-entry posture is active enough yet to judge whether it can hold." + return ( + "No reset re-entry posture is active enough yet to judge whether it can hold." + ) def _closure_forecast_reset_reentry_churn_summary( @@ -5245,7 +5079,9 @@ def _apply_reset_reentry_persistence_and_churn( churn_reason = "" churn_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -5253,7 +5089,9 @@ def _apply_reset_reentry_persistence_and_churn( resolution_reason = target.get("class_transition_resolution_reason", "") if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) persistence_meta = _closure_forecast_reset_reentry_persistence_for_target( target, closure_forecast_events, @@ -5264,8 +5102,12 @@ def _apply_reset_reentry_persistence_and_churn( closure_forecast_events, transition_history_meta, ) - persistence_age_runs = persistence_meta["closure_forecast_reset_reentry_age_runs"] - persistence_score = persistence_meta["closure_forecast_reset_reentry_persistence_score"] + persistence_age_runs = persistence_meta[ + "closure_forecast_reset_reentry_age_runs" + ] + persistence_score = persistence_meta[ + "closure_forecast_reset_reentry_persistence_score" + ] persistence_status = persistence_meta[ "closure_forecast_reset_reentry_persistence_status" ] @@ -5290,9 +5132,15 @@ def _apply_reset_reentry_persistence_and_churn( resolution_status=resolution_status, resolution_reason=resolution_reason, ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -5379,246 +5227,6 @@ def _apply_reset_reentry_persistence_and_churn( } -def _closure_forecast_reset_reentry_side_from_persistence_status(status: str) -> str: - return _resolve_side( - status, - "holding-confirmation-reentry", - "sustained-confirmation-reentry", - ) - - -def _closure_forecast_reset_reentry_memory_side_from_event(event: dict) -> str: - side = _closure_forecast_reset_reentry_side_from_persistence_status( - event.get("closure_forecast_reset_reentry_persistence_status", "none") - ) - if side != "none": - return side - return _closure_forecast_reset_reentry_side_from_event(event) - - -def _reset_reentry_event_is_confirmation_like(event: dict) -> bool: - event_side = _closure_forecast_reset_reentry_memory_side_from_event(event) - persistence_status = event.get("closure_forecast_reset_reentry_persistence_status", "none") - return ( - event.get("closure_forecast_reset_reentry_status", "none") - in {"pending-confirmation-reentry", "reentered-confirmation"} - or ( - persistence_status - in { - "just-reentered", - "holding-confirmation-reentry", - "sustained-confirmation-reentry", - } - and event_side == "confirmation" - ) - or event.get("closure_forecast_hysteresis_status", "none") - in {"pending-confirmation", "confirmed-confirmation"} - or event.get("transition_closure_likely_outcome", "none") == "confirm-soon" - ) - - -def _reset_reentry_event_is_clearance_like(event: dict) -> bool: - event_side = _closure_forecast_reset_reentry_memory_side_from_event(event) - persistence_status = event.get("closure_forecast_reset_reentry_persistence_status", "none") - return ( - event.get("closure_forecast_reset_reentry_status", "none") - in {"pending-clearance-reentry", "reentered-clearance"} - or ( - persistence_status - in { - "just-reentered", - "holding-clearance-reentry", - "sustained-clearance-reentry", - } - and event_side == "clearance" - ) - or event.get("closure_forecast_hysteresis_status", "none") - in {"pending-clearance", "confirmed-clearance"} - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} - ) - - -def _reset_reentry_event_has_evidence(event: dict) -> bool: - return ( - _reset_reentry_event_is_confirmation_like(event) - or _reset_reentry_event_is_clearance_like(event) - or event.get("closure_forecast_reset_reentry_churn_status", "none") - in {"watch", "churn", "blocked"} - ) - - -def _reset_reentry_event_signal_label(event: dict) -> str: - if _reset_reentry_event_is_confirmation_like(event): - return "confirmation-like" - if _reset_reentry_event_is_clearance_like(event): - return "clearance-like" - return "neutral" - - -def _closure_forecast_reset_reentry_freshness_reason( - freshness_status: str, - weighted_reset_reentry_evidence_count: float, - recent_window_weight_share: float, - decayed_confirmation_rate: float, - decayed_clearance_rate: float, -) -> str: - if freshness_status == "fresh": - return ( - "Recent reset re-entry evidence is still current enough to trust, with " - f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest " - f"{CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS} runs." - ) - if freshness_status == "mixed-age": - return ( - "Reset re-entry memory is still useful, but it is partly aging: " - f"{recent_window_weight_share:.0%} of the weighted signal is recent and the rest is older carry-forward." - ) - if freshness_status == "stale": - return "Older reset re-entry strength is carrying more of the signal than recent runs, so it should not keep stronger posture alive on memory alone." - return ( - "Reset re-entry memory is still too lightly exercised to judge freshness, with " - f"{weighted_reset_reentry_evidence_count:.2f} weighted reset re-entry run(s), " - f"{decayed_confirmation_rate:.0%} confirmation-like signal, and {decayed_clearance_rate:.0%} clearance-like signal." - ) - - -def _recent_reset_reentry_signal_mix( - weighted_reset_reentry_evidence_count: float, - weighted_confirmation_like: float, - weighted_clearance_like: float, - recent_window_weight_share: float, -) -> str: - return ( - f"{weighted_reset_reentry_evidence_count:.2f} weighted reset re-entry run(s) with " - f"{weighted_confirmation_like:.2f} confirmation-like, {weighted_clearance_like:.2f} clearance-like, " - f"and {recent_window_weight_share:.0%} of the signal from the freshest runs." - ) - - -def _closure_forecast_reset_reentry_freshness_for_target( - target: dict, - closure_forecast_events: list[dict], -) -> dict: - return _closure_forecast_reset_reentry_freshness_for_target_helper( - target, - closure_forecast_events, - target_class_key=_target_class_key, - reset_reentry_event_has_evidence=_reset_reentry_event_has_evidence, - reset_reentry_event_signal_label=_reset_reentry_event_signal_label, - closure_forecast_reset_reentry_side_from_persistence_status=( - _closure_forecast_reset_reentry_side_from_persistence_status - ), - closure_forecast_reset_reentry_side_from_status=( - _closure_forecast_reset_reentry_side_from_status - ), - closure_forecast_reset_reentry_memory_side_from_event=( - _closure_forecast_reset_reentry_memory_side_from_event - ), - class_memory_recency_weights=CLASS_MEMORY_RECENCY_WEIGHTS, - history_window_runs=HISTORY_WINDOW_RUNS, - class_reset_reentry_freshness_window_runs=( - CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS - ), - closure_forecast_freshness_status=_closure_forecast_freshness_status, - closure_forecast_reset_reentry_freshness_reason=( - _closure_forecast_reset_reentry_freshness_reason - ), - recent_reset_reentry_signal_mix=_recent_reset_reentry_signal_mix, - reset_reentry_event_is_confirmation_like=( - _reset_reentry_event_is_confirmation_like - ), - reset_reentry_event_is_clearance_like=_reset_reentry_event_is_clearance_like, - ) - - -def _apply_reset_reentry_freshness_reset_control( - target: dict, - *, - freshness_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reacquisition_status: str, - reacquisition_reason: str, - reentry_status: str, - reentry_reason: str, - persistence_age_runs: int, - persistence_score: float, - persistence_status: str, - persistence_reason: str, -) -> dict: - return _apply_reset_reentry_freshness_reset_control_helper( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reacquisition_status=reacquisition_status, - reacquisition_reason=reacquisition_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - closure_forecast_reset_reentry_side_from_persistence_status=( - _closure_forecast_reset_reentry_side_from_persistence_status - ), - closure_forecast_reset_reentry_side_from_status=( - _closure_forecast_reset_reentry_side_from_status - ), - target_specific_normalization_noise=_target_specific_normalization_noise, - ) - - -def _closure_forecast_reset_reentry_freshness_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_freshness_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_freshness_summary( - primary_target: dict, - stale_reset_reentry_hotspots: list[dict], - fresh_reset_reentry_signal_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_freshness_summary_helper( - primary_target, - stale_reset_reentry_hotspots, - fresh_reset_reentry_signal_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_reset_summary( - primary_target: dict, - stale_reset_reentry_hotspots: list[dict], - fresh_reset_reentry_signal_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_reset_summary_helper( - primary_target, - stale_reset_reentry_hotspots, - fresh_reset_reentry_signal_hotspots, - target_label=_target_label, - ) - - def _apply_reset_reentry_freshness_and_reset( resolution_targets: list[dict], history: list[dict], @@ -5663,32 +5271,54 @@ def _apply_reset_reentry_freshness_and_reset( reset_status = "none" reset_reason = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") resolution_status = target.get("class_transition_resolution_status", "none") resolution_reason = target.get("class_transition_resolution_reason", "") - reacquisition_status = target.get("closure_forecast_reacquisition_status", "none") + reacquisition_status = target.get( + "closure_forecast_reacquisition_status", "none" + ) reacquisition_reason = target.get("closure_forecast_reacquisition_reason", "") reentry_status = target.get("closure_forecast_reset_reentry_status", "none") reentry_reason = target.get("closure_forecast_reset_reentry_reason", "") persistence_age_runs = target.get("closure_forecast_reset_reentry_age_runs", 0) - persistence_score = target.get("closure_forecast_reset_reentry_persistence_score", 0.0) - persistence_status = target.get("closure_forecast_reset_reentry_persistence_status", "none") - persistence_reason = target.get("closure_forecast_reset_reentry_persistence_reason", "") + persistence_score = target.get( + "closure_forecast_reset_reentry_persistence_score", 0.0 + ) + persistence_status = target.get( + "closure_forecast_reset_reentry_persistence_status", "none" + ) + persistence_reason = target.get( + "closure_forecast_reset_reentry_persistence_reason", "" + ) if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) freshness_meta = _closure_forecast_reset_reentry_freshness_for_target( target, closure_forecast_events, ) - freshness_status = freshness_meta["closure_forecast_reset_reentry_freshness_status"] - freshness_reason = freshness_meta["closure_forecast_reset_reentry_freshness_reason"] - memory_weight = freshness_meta["closure_forecast_reset_reentry_memory_weight"] - decayed_confirmation_rate = freshness_meta["decayed_reset_reentered_confirmation_rate"] - decayed_clearance_rate = freshness_meta["decayed_reset_reentered_clearance_rate"] + freshness_status = freshness_meta[ + "closure_forecast_reset_reentry_freshness_status" + ] + freshness_reason = freshness_meta[ + "closure_forecast_reset_reentry_freshness_reason" + ] + memory_weight = freshness_meta[ + "closure_forecast_reset_reentry_memory_weight" + ] + decayed_confirmation_rate = freshness_meta[ + "decayed_reset_reentered_confirmation_rate" + ] + decayed_clearance_rate = freshness_meta[ + "decayed_reset_reentered_clearance_rate" + ] signal_mix = freshness_meta["recent_reset_reentry_signal_mix"] control_updates = _apply_reset_reentry_freshness_reset_control( target, @@ -5710,21 +5340,39 @@ def _apply_reset_reentry_freshness_and_reset( persistence_status=persistence_status, persistence_reason=persistence_reason, ) - reset_status = control_updates["closure_forecast_reset_reentry_reset_status"] - reset_reason = control_updates["closure_forecast_reset_reentry_reset_reason"] - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + reset_status = control_updates[ + "closure_forecast_reset_reentry_reset_status" + ] + reset_reason = control_updates[ + "closure_forecast_reset_reentry_reset_reason" + ] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] resolution_reason = control_updates["class_transition_resolution_reason"] - reacquisition_status = control_updates["closure_forecast_reacquisition_status"] - reacquisition_reason = control_updates["closure_forecast_reacquisition_reason"] + reacquisition_status = control_updates[ + "closure_forecast_reacquisition_status" + ] + reacquisition_reason = control_updates[ + "closure_forecast_reacquisition_reason" + ] reentry_status = control_updates["closure_forecast_reset_reentry_status"] reentry_reason = control_updates["closure_forecast_reset_reentry_reason"] - persistence_age_runs = control_updates["closure_forecast_reset_reentry_age_runs"] - persistence_score = control_updates["closure_forecast_reset_reentry_persistence_score"] + persistence_age_runs = control_updates[ + "closure_forecast_reset_reentry_age_runs" + ] + persistence_score = control_updates[ + "closure_forecast_reset_reentry_persistence_score" + ] persistence_status = control_updates[ "closure_forecast_reset_reentry_persistence_status" ] @@ -5767,9 +5415,11 @@ def _apply_reset_reentry_freshness_and_reset( resolution_targets, mode="stale", ) - fresh_reset_reentry_signal_hotspots = _closure_forecast_reset_reentry_freshness_hotspots( - resolution_targets, - mode="fresh", + fresh_reset_reentry_signal_hotspots = ( + _closure_forecast_reset_reentry_freshness_hotspots( + resolution_targets, + mode="fresh", + ) ) return { "primary_target_closure_forecast_reset_reentry_freshness_status": primary_target.get( @@ -5804,207 +5454,76 @@ def _apply_reset_reentry_freshness_and_reset( } -def _closure_forecast_reset_reentry_rebuild_side_from_status(status: str) -> str: - return _resolve_side( - status, - "pending-confirmation-rebuild", - "rebuilt-confirmation-reentry", - ) - +def _apply_reset_reentry_refresh_recovery_and_rebuild( + resolution_targets: list[dict], + history: list[dict], + *, + current_generated_at: str, + confidence_calibration: dict, +) -> dict: + if not resolution_targets: + return { + "primary_target_closure_forecast_reset_reentry_refresh_recovery_score": 0.0, + "primary_target_closure_forecast_reset_reentry_refresh_recovery_status": "none", + "primary_target_closure_forecast_reset_reentry_rebuild_status": "none", + "primary_target_closure_forecast_reset_reentry_rebuild_reason": "", + "closure_forecast_reset_reentry_refresh_recovery_summary": "No reset re-entry refresh recovery is recorded because there is no active target.", + "closure_forecast_reset_reentry_rebuild_summary": "No reset re-entry rebuild is recorded because there is no active target.", + "closure_forecast_reset_reentry_refresh_window_runs": CLASS_RESET_REENTRY_REFRESH_REBUILD_WINDOW_RUNS, + "recovering_from_confirmation_reentry_reset_hotspots": [], + "recovering_from_clearance_reentry_reset_hotspots": [], + } -def _closure_forecast_reset_reentry_rebuild_side_from_recovery_status(status: str) -> str: - return _resolve_side( - status, - "recovering-confirmation-reentry-reset", - "rebuilding-confirmation-reentry", + current_primary_target = resolution_targets[0] + current_bucket = _recommendation_bucket(current_primary_target) + closure_forecast_events = _class_closure_forecast_events( + history, + current_primary_target=current_primary_target, + current_generated_at=current_generated_at, ) - - -def _closure_forecast_reset_reentry_refresh_path_label(event: dict) -> str: - rebuild_status = event.get("closure_forecast_reset_reentry_rebuild_status", "none") or "none" - if rebuild_status != "none": - return rebuild_status - recovery_status = ( - event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") or "none" + transition_events = _class_transition_events( + history, + current_primary_target=current_primary_target, + current_generated_at=current_generated_at, ) - if recovery_status != "none": - return recovery_status - reset_status = event.get("closure_forecast_reset_reentry_reset_status", "none") or "none" - if reset_status != "none": - return reset_status - reentry_status = event.get("closure_forecast_reset_reentry_status", "none") or "none" - if reentry_status != "none": - return reentry_status - likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" - if likely_outcome != "none": - return likely_outcome - return "hold" - -def _closure_forecast_reset_reentry_refresh_recovery_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_refresh_recovery_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=_closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_reentry_refresh_path_label=( - _closure_forecast_reset_reentry_refresh_path_label - ), - class_reset_reentry_refresh_rebuild_window_runs=( - CLASS_RESET_REENTRY_REFRESH_REBUILD_WINDOW_RUNS - ), - ) - - -def _apply_reset_reentry_refresh_rebuild_control( - target: dict, - *, - refresh_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reacquisition_status: str, - reacquisition_reason: str, - reentry_status: str, - reentry_reason: str, - persistence_age_runs: int, - persistence_score: float, - persistence_status: str, - persistence_reason: str, -) -> dict: - return _apply_reset_reentry_refresh_rebuild_control_helper( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reacquisition_status=reacquisition_status, - reacquisition_reason=reacquisition_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - ) - - -def _closure_forecast_reset_reentry_refresh_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_refresh_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_refresh_recovery_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_refresh_recovery_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _apply_reset_reentry_refresh_recovery_and_rebuild( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - if not resolution_targets: - return { - "primary_target_closure_forecast_reset_reentry_refresh_recovery_score": 0.0, - "primary_target_closure_forecast_reset_reentry_refresh_recovery_status": "none", - "primary_target_closure_forecast_reset_reentry_rebuild_status": "none", - "primary_target_closure_forecast_reset_reentry_rebuild_reason": "", - "closure_forecast_reset_reentry_refresh_recovery_summary": "No reset re-entry refresh recovery is recorded because there is no active target.", - "closure_forecast_reset_reentry_rebuild_summary": "No reset re-entry rebuild is recorded because there is no active target.", - "closure_forecast_reset_reentry_refresh_window_runs": CLASS_RESET_REENTRY_REFRESH_REBUILD_WINDOW_RUNS, - "recovering_from_confirmation_reentry_reset_hotspots": [], - "recovering_from_clearance_reentry_reset_hotspots": [], - } - - current_primary_target = resolution_targets[0] - current_bucket = _recommendation_bucket(current_primary_target) - closure_forecast_events = _class_closure_forecast_events( - history, - current_primary_target=current_primary_target, - current_generated_at=current_generated_at, - ) - transition_events = _class_transition_events( - history, - current_primary_target=current_primary_target, - current_generated_at=current_generated_at, - ) - - updated_targets: list[dict] = [] - for target in resolution_targets: - refresh_recovery_score = 0.0 - refresh_recovery_status = "none" - rebuild_status = "none" - rebuild_reason = "" - refresh_path = "" - closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") - closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") - transition_status = target.get("class_reweight_transition_status", "none") - transition_reason = target.get("class_reweight_transition_reason", "") - resolution_status = target.get("class_transition_resolution_status", "none") - resolution_reason = target.get("class_transition_resolution_reason", "") - reacquisition_status = target.get("closure_forecast_reacquisition_status", "none") - reacquisition_reason = target.get("closure_forecast_reacquisition_reason", "") - reentry_status = target.get("closure_forecast_reset_reentry_status", "none") - reentry_reason = target.get("closure_forecast_reset_reentry_reason", "") - persistence_age_runs = target.get("closure_forecast_reset_reentry_age_runs", 0) - persistence_score = target.get("closure_forecast_reset_reentry_persistence_score", 0.0) - persistence_status = target.get("closure_forecast_reset_reentry_persistence_status", "none") - persistence_reason = target.get("closure_forecast_reset_reentry_persistence_reason", "") + updated_targets: list[dict] = [] + for target in resolution_targets: + refresh_recovery_score = 0.0 + refresh_recovery_status = "none" + rebuild_status = "none" + rebuild_reason = "" + refresh_path = "" + closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) + closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") + transition_status = target.get("class_reweight_transition_status", "none") + transition_reason = target.get("class_reweight_transition_reason", "") + resolution_status = target.get("class_transition_resolution_status", "none") + resolution_reason = target.get("class_transition_resolution_reason", "") + reacquisition_status = target.get( + "closure_forecast_reacquisition_status", "none" + ) + reacquisition_reason = target.get("closure_forecast_reacquisition_reason", "") + reentry_status = target.get("closure_forecast_reset_reentry_status", "none") + reentry_reason = target.get("closure_forecast_reset_reentry_reason", "") + persistence_age_runs = target.get("closure_forecast_reset_reentry_age_runs", 0) + persistence_score = target.get( + "closure_forecast_reset_reentry_persistence_score", 0.0 + ) + persistence_status = target.get( + "closure_forecast_reset_reentry_persistence_status", "none" + ) + persistence_reason = target.get( + "closure_forecast_reset_reentry_persistence_reason", "" + ) if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) + transition_history_meta = _target_class_transition_history( + target, transition_events + ) refresh_meta = _closure_forecast_reset_reentry_refresh_recovery_for_target( target, closure_forecast_events, @@ -6016,8 +5535,12 @@ def _apply_reset_reentry_refresh_recovery_and_rebuild( refresh_recovery_status = refresh_meta[ "closure_forecast_reset_reentry_refresh_recovery_status" ] - rebuild_status = refresh_meta["closure_forecast_reset_reentry_rebuild_status"] - rebuild_reason = refresh_meta["closure_forecast_reset_reentry_rebuild_reason"] + rebuild_status = refresh_meta[ + "closure_forecast_reset_reentry_rebuild_status" + ] + rebuild_reason = refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reason" + ] refresh_path = refresh_meta["recent_reset_reentry_refresh_path"] control_updates = _apply_reset_reentry_refresh_rebuild_control( target, @@ -6039,19 +5562,33 @@ def _apply_reset_reentry_refresh_recovery_and_rebuild( persistence_status=persistence_status, persistence_reason=persistence_reason, ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] resolution_reason = control_updates["class_transition_resolution_reason"] - reacquisition_status = control_updates["closure_forecast_reacquisition_status"] - reacquisition_reason = control_updates["closure_forecast_reacquisition_reason"] + reacquisition_status = control_updates[ + "closure_forecast_reacquisition_status" + ] + reacquisition_reason = control_updates[ + "closure_forecast_reacquisition_reason" + ] reentry_status = control_updates["closure_forecast_reset_reentry_status"] reentry_reason = control_updates["closure_forecast_reset_reentry_reason"] - persistence_age_runs = control_updates["closure_forecast_reset_reentry_age_runs"] - persistence_score = control_updates["closure_forecast_reset_reentry_persistence_score"] + persistence_age_runs = control_updates[ + "closure_forecast_reset_reentry_age_runs" + ] + persistence_score = control_updates[ + "closure_forecast_reset_reentry_persistence_score" + ] persistence_status = control_updates[ "closure_forecast_reset_reentry_persistence_status" ] @@ -6128,182 +5665,6 @@ def _apply_reset_reentry_refresh_recovery_and_rebuild( } -def _closure_forecast_reset_reentry_rebuild_side_from_persistence_status(status: str) -> str: - return _resolve_side( - status, - "holding-confirmation-rebuild", - "sustained-confirmation-rebuild", - ) - - -def _closure_forecast_reset_reentry_rebuild_side_from_event(event: dict) -> str: - side = _closure_forecast_reset_reentry_rebuild_side_from_persistence_status( - event.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") - ) - if side != "none": - return side - side = _closure_forecast_reset_reentry_rebuild_side_from_status( - event.get("closure_forecast_reset_reentry_rebuild_status", "none") - ) - if side != "none": - return side - return _closure_forecast_reset_reentry_rebuild_side_from_recovery_status( - event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") - ) - - -def _closure_forecast_reset_reentry_rebuild_path_label(event: dict) -> str: - persistence_status = ( - event.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") or "none" - ) - if persistence_status != "none": - return persistence_status - churn_status = ( - event.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") or "none" - ) - if churn_status != "none": - return churn_status - rebuild_status = event.get("closure_forecast_reset_reentry_rebuild_status", "none") or "none" - if rebuild_status != "none": - return rebuild_status - recovery_status = ( - event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") or "none" - ) - if recovery_status != "none": - return recovery_status - reset_status = event.get("closure_forecast_reset_reentry_reset_status", "none") or "none" - if reset_status != "none": - return reset_status - reentry_status = event.get("closure_forecast_reset_reentry_status", "none") or "none" - if reentry_status != "none": - return reentry_status - likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" - if likely_outcome != "none": - return likely_outcome - return "hold" - - -def _closure_forecast_reset_reentry_rebuild_persistence_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_rebuild_persistence_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - closure_forecast_direction_majority=_closure_forecast_direction_majority, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - clamp_round=_clamp_round, - closure_forecast_reset_reentry_rebuild_path_label=( - _closure_forecast_reset_reentry_rebuild_path_label - ), - class_reset_reentry_rebuild_persistence_window_runs=( - CLASS_RESET_REENTRY_REBUILD_PERSISTENCE_WINDOW_RUNS - ), - ) - - -def _closure_forecast_reset_reentry_rebuild_churn_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_rebuild_churn_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - class_direction_flip_count=_class_direction_flip_count, - target_specific_normalization_noise=_target_specific_normalization_noise, - clamp_round=_clamp_round, - closure_forecast_reset_reentry_rebuild_path_label=( - _closure_forecast_reset_reentry_rebuild_path_label - ), - class_reset_reentry_rebuild_persistence_window_runs=( - CLASS_RESET_REENTRY_REBUILD_PERSISTENCE_WINDOW_RUNS - ), - ) - - -def _apply_reset_reentry_rebuild_persistence_and_churn_control( - target: dict, - *, - persistence_meta: dict, - churn_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_persistence_and_churn_control_helper( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - closure_forecast_reset_reentry_rebuild_side_from_status=( - _closure_forecast_reset_reentry_rebuild_side_from_status - ), - closure_forecast_reset_reentry_rebuild_side_from_recovery_status=( - _closure_forecast_reset_reentry_rebuild_side_from_recovery_status - ), - ) - - -def _closure_forecast_reset_reentry_rebuild_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_rebuild_persistence_summary( - primary_target: dict, - just_rebuilt_hotspots: list[dict], - holding_reset_reentry_rebuild_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_persistence_summary_helper( - primary_target, - just_rebuilt_hotspots, - holding_reset_reentry_rebuild_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_churn_summary( - primary_target: dict, - reset_reentry_rebuild_churn_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_churn_summary_helper( - primary_target, - reset_reentry_rebuild_churn_hotspots, - target_label=_target_label, - ) - - def _apply_reset_reentry_rebuild_persistence_and_churn( resolution_targets: list[dict], history: list[dict], @@ -6353,7 +5714,9 @@ def _apply_reset_reentry_rebuild_persistence_and_churn( churn_reason = "" churn_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -6361,13 +5724,17 @@ def _apply_reset_reentry_rebuild_persistence_and_churn( resolution_reason = target.get("class_transition_resolution_reason", "") if _recommendation_bucket(target) == current_bucket: - transition_history_meta = _target_class_transition_history(target, transition_events) - persistence_meta = _closure_forecast_reset_reentry_rebuild_persistence_for_target( - target, - closure_forecast_events, - transition_history_meta, + transition_history_meta = _target_class_transition_history( + target, transition_events ) - churn_meta = _closure_forecast_reset_reentry_rebuild_churn_for_target( + persistence_meta = ( + _closure_forecast_reset_reentry_rebuild_persistence_for_target( + target, + closure_forecast_events, + transition_history_meta, + ) + ) + churn_meta = _closure_forecast_reset_reentry_rebuild_churn_for_target( target, closure_forecast_events, transition_history_meta, @@ -6384,27 +5751,43 @@ def _apply_reset_reentry_rebuild_persistence_and_churn( persistence_reason = persistence_meta[ "closure_forecast_reset_reentry_rebuild_persistence_reason" ] - persistence_path = persistence_meta["recent_reset_reentry_rebuild_persistence_path"] - churn_score = churn_meta["closure_forecast_reset_reentry_rebuild_churn_score"] - churn_status = churn_meta["closure_forecast_reset_reentry_rebuild_churn_status"] - churn_reason = churn_meta["closure_forecast_reset_reentry_rebuild_churn_reason"] + persistence_path = persistence_meta[ + "recent_reset_reentry_rebuild_persistence_path" + ] + churn_score = churn_meta[ + "closure_forecast_reset_reentry_rebuild_churn_score" + ] + churn_status = churn_meta[ + "closure_forecast_reset_reentry_rebuild_churn_status" + ] + churn_reason = churn_meta[ + "closure_forecast_reset_reentry_rebuild_churn_reason" + ] churn_path = churn_meta["recent_reset_reentry_rebuild_churn_path"] - control_updates = _apply_reset_reentry_rebuild_persistence_and_churn_control( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, + control_updates = ( + _apply_reset_reentry_rebuild_persistence_and_churn_control( + target, + persistence_meta=persistence_meta, + churn_meta=churn_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + ) ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -6438,13 +5821,17 @@ def _apply_reset_reentry_rebuild_persistence_and_churn( resolution_targets, mode="just-rebuilt", ) - holding_reset_reentry_rebuild_hotspots = _closure_forecast_reset_reentry_rebuild_hotspots( - resolution_targets, - mode="holding", + holding_reset_reentry_rebuild_hotspots = ( + _closure_forecast_reset_reentry_rebuild_hotspots( + resolution_targets, + mode="holding", + ) ) - reset_reentry_rebuild_churn_hotspots = _closure_forecast_reset_reentry_rebuild_hotspots( - resolution_targets, - mode="churn", + reset_reentry_rebuild_churn_hotspots = ( + _closure_forecast_reset_reentry_rebuild_hotspots( + resolution_targets, + mode="churn", + ) ) return { "primary_target_closure_forecast_reset_reentry_rebuild_age_runs": primary_target.get( @@ -6491,153 +5878,6 @@ def _apply_reset_reentry_rebuild_persistence_and_churn( } -def _closure_forecast_reset_reentry_rebuild_freshness_for_target( - target: dict, - closure_forecast_events: list[dict], -) -> dict: - return _closure_forecast_reset_reentry_rebuild_freshness_for_target_helper( - target, - closure_forecast_events, - target_class_key=_target_class_key, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - _closure_forecast_reset_reentry_rebuild_side_from_status - ), - closure_forecast_freshness_status=_closure_forecast_freshness_status, - class_memory_recency_weights=CLASS_MEMORY_RECENCY_WEIGHTS, - class_reset_reentry_rebuild_freshness_window_runs=( - CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS - ), - history_window_runs=HISTORY_WINDOW_RUNS, - ) - - -def _apply_reset_reentry_rebuild_freshness_reset_control( - target: dict, - *, - freshness_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - rebuild_status: str, - rebuild_reason: str, - persistence_age_runs: int, - persistence_score: float, - persistence_status: str, - persistence_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_freshness_reset_control_helper( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - rebuild_status=rebuild_status, - rebuild_reason=rebuild_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - _closure_forecast_reset_reentry_rebuild_side_from_status - ), - target_specific_normalization_noise=_target_specific_normalization_noise, - ) - - -def _closure_forecast_reset_reentry_rebuild_freshness_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_freshness_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_rebuild_freshness_summary( - primary_target: dict, - stale_reset_reentry_rebuild_hotspots: list[dict], - fresh_reset_reentry_rebuild_signal_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_freshness_summary_helper( - primary_target, - stale_reset_reentry_rebuild_hotspots, - fresh_reset_reentry_rebuild_signal_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_reset_summary( - primary_target: dict, - stale_reset_reentry_rebuild_hotspots: list[dict], - fresh_reset_reentry_rebuild_signal_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reset_summary_helper( - primary_target, - stale_reset_reentry_rebuild_hotspots, - fresh_reset_reentry_rebuild_signal_hotspots, - target_label=_target_label, - ) - - -def _apply_reset_reentry_rebuild_freshness_and_reset( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - return _apply_reset_reentry_rebuild_freshness_and_reset_helper( - resolution_targets, - history, - current_generated_at=current_generated_at, - confidence_calibration=confidence_calibration, - recommendation_bucket=_recommendation_bucket, - class_closure_forecast_events=_class_closure_forecast_events, - class_transition_events=_class_transition_events, - target_class_transition_history=_target_class_transition_history, - target_class_key=_target_class_key, - target_label=_target_label, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - _closure_forecast_reset_reentry_rebuild_side_from_status - ), - closure_forecast_freshness_status=_closure_forecast_freshness_status, - target_specific_normalization_noise=_target_specific_normalization_noise, - class_memory_recency_weights=CLASS_MEMORY_RECENCY_WEIGHTS, - class_reset_reentry_rebuild_freshness_window_runs=( - CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS - ), - history_window_runs=HISTORY_WINDOW_RUNS, - ) - - def _closure_forecast_reset_reentry_rebuild_side_from_refresh_recovery_status( status: str, ) -> str: @@ -6648,7 +5888,9 @@ def _closure_forecast_reset_reentry_rebuild_side_from_refresh_recovery_status( ) -def _closure_forecast_reset_reentry_rebuild_side_from_reentry_status(status: str) -> str: +def _closure_forecast_reset_reentry_rebuild_side_from_reentry_status( + status: str, +) -> str: return _resolve_side( status, "pending-confirmation-rebuild-reentry", @@ -6658,7 +5900,8 @@ def _closure_forecast_reset_reentry_rebuild_side_from_reentry_status(status: str def _closure_forecast_reset_reentry_rebuild_refresh_path_label(event: dict) -> str: reentry_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") or "none" + event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") + or "none" ) if reentry_status != "none": return reentry_status @@ -6672,7 +5915,8 @@ def _closure_forecast_reset_reentry_rebuild_refresh_path_label(event: dict) -> s if recovery_status != "none": return recovery_status reset_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") or "none" + event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + or "none" ) if reset_status != "none": return reset_status @@ -6736,7 +5980,10 @@ def _closure_forecast_reset_reentry_rebuild_refresh_recovery_for_target( continue relevant_events.append(event) directions.append(direction) - if len(relevant_events) > CLASS_RESET_REENTRY_REBUILD_REFRESH_REENTRY_WINDOW_RUNS: + if ( + len(relevant_events) + > CLASS_RESET_REENTRY_REBUILD_REFRESH_REENTRY_WINDOW_RUNS + ): break if direction == "neutral": signal_strength = 0.0 @@ -6791,9 +6038,11 @@ def _closure_forecast_reset_reentry_rebuild_refresh_recovery_for_target( earlier_majority, ) opposes_reset = ( - recent_rebuild_reset_side == "confirmation" and current_direction == "supporting-clearance" + recent_rebuild_reset_side == "confirmation" + and current_direction == "supporting-clearance" ) or ( - recent_rebuild_reset_side == "clearance" and current_direction == "supporting-confirmation" + recent_rebuild_reset_side == "clearance" + and current_direction == "supporting-confirmation" ) aligned_fresh_runs_after_reset = 0 if latest_reset_index is not None and latest_reset_index > 0: @@ -6828,7 +6077,8 @@ def _closure_forecast_reset_reentry_rebuild_refresh_recovery_for_target( ) current_event_already_counted = any( event.get("generated_at", "") == "" - and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) == current_score + and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + == current_score and event.get("closure_forecast_reweight_direction", "neutral") == target.get("closure_forecast_reweight_direction", "neutral") for event in matching_events[: latest_reset_index or 0] @@ -6897,9 +6147,7 @@ def _closure_forecast_reset_reentry_rebuild_refresh_recovery_for_target( and aligned_fresh_runs_after_reset >= 2 ): reentry_status = "reentered-clearance-rebuild" - reentry_reason = ( - "Fresh clearance-side pressure has re-earned stronger rebuilt clearance posture." - ) + reentry_reason = "Fresh clearance-side pressure has re-earned stronger rebuilt clearance posture." elif local_noise and recovery_status in { "recovering-confirmation-rebuild-reset", "reentering-confirmation-rebuild", @@ -6977,7 +6225,9 @@ def _apply_reset_reentry_rebuild_refresh_reentry_control( current_stability = target.get("closure_forecast_stability_status", "watch") transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) recent_pending_status = transition_history_meta.get("recent_pending_status", "none") - decayed_clearance_rate = float(target.get("decayed_rebuilt_clearance_reentry_rate", 0.0) or 0.0) + decayed_clearance_rate = float( + target.get("decayed_rebuilt_clearance_reentry_rate", 0.0) or 0.0 + ) if reentry_status == "blocked": if recent_rebuild_reset_side == "confirmation": @@ -7066,7 +6316,10 @@ def _apply_reset_reentry_rebuild_refresh_reentry_control( "closure_forecast_reset_reentry_rebuild_persistence_status": "none", "closure_forecast_reset_reentry_rebuild_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -7103,7 +6356,10 @@ def _apply_reset_reentry_rebuild_refresh_reentry_control( "closure_forecast_reset_reentry_rebuild_persistence_status": "none", "closure_forecast_reset_reentry_rebuild_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -7200,27 +6456,51 @@ def _refresh_hotspots_base( _REBUILD_REFRESH_HOTSPOTS_SPEC = _RefreshHotspotsSpec( - score_key='closure_forecast_reset_reentry_rebuild_refresh_recovery_score', - status_key='closure_forecast_reset_reentry_rebuild_refresh_recovery_status', - path_key='recent_reset_reentry_rebuild_refresh_path', - confirmation_statuses=frozenset({'recovering-confirmation-rebuild-reset', 'reentering-confirmation-rebuild'}), - clearance_statuses=frozenset({'recovering-clearance-rebuild-reset', 'reentering-clearance-rebuild'}), + score_key="closure_forecast_reset_reentry_rebuild_refresh_recovery_score", + status_key="closure_forecast_reset_reentry_rebuild_refresh_recovery_status", + path_key="recent_reset_reentry_rebuild_refresh_path", + confirmation_statuses=frozenset( + {"recovering-confirmation-rebuild-reset", "reentering-confirmation-rebuild"} + ), + clearance_statuses=frozenset( + {"recovering-clearance-rebuild-reset", "reentering-clearance-rebuild"} + ), ) _RESTORE_REFRESH_HOTSPOTS_SPEC = _RefreshHotspotsSpec( - score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_score', - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status', - path_key='recent_reset_reentry_rebuild_reentry_restore_refresh_path', - confirmation_statuses=frozenset({'recovering-confirmation-rebuild-reentry-restore-reset', 'rerestoring-confirmation-rebuild-reentry'}), - clearance_statuses=frozenset({'recovering-clearance-rebuild-reentry-restore-reset', 'rerestoring-clearance-rebuild-reentry'}), + score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_score", + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", + path_key="recent_reset_reentry_rebuild_reentry_restore_refresh_path", + confirmation_statuses=frozenset( + { + "recovering-confirmation-rebuild-reentry-restore-reset", + "rerestoring-confirmation-rebuild-reentry", + } + ), + clearance_statuses=frozenset( + { + "recovering-clearance-rebuild-reentry-restore-reset", + "rerestoring-clearance-rebuild-reentry", + } + ), ) _RERESTORE_REFRESH_HOTSPOTS_SPEC = _RefreshHotspotsSpec( - score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_score', - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status', - path_key='recent_reset_reentry_rebuild_reentry_restore_rerestore_refresh_path', - confirmation_statuses=frozenset({'recovering-confirmation-rebuild-reentry-rerestore-reset', 'rererestoring-confirmation-rebuild-reentry'}), - clearance_statuses=frozenset({'recovering-clearance-rebuild-reentry-rerestore-reset', 'rererestoring-clearance-rebuild-reentry'}), + score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_score", + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", + path_key="recent_reset_reentry_rebuild_reentry_restore_rerestore_refresh_path", + confirmation_statuses=frozenset( + { + "recovering-confirmation-rebuild-reentry-rerestore-reset", + "rererestoring-confirmation-rebuild-reentry", + } + ), + clearance_statuses=frozenset( + { + "recovering-clearance-rebuild-reentry-rerestore-reset", + "rererestoring-clearance-rebuild-reentry", + } + ), ) @@ -7303,60 +6583,60 @@ def _refresh_recovery_summary_base( _REBUILD_REFRESH_RECOVERY_SUMMARY_SPEC = _RefreshRecoverySummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_refresh_recovery_status', - score_key='closure_forecast_reset_reentry_rebuild_refresh_recovery_score', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_reason', - recovering_confirmation_status='recovering-confirmation-rebuild-reset', - recovering_clearance_status='recovering-clearance-rebuild-reset', - reentering_confirmation_status='reentering-confirmation-rebuild', - reentering_clearance_status='reentering-clearance-rebuild', - recovering_confirmation_text='Fresh confirmation-side evidence is returning after rebuilt posture softened or reset for {label}, but it has not yet re-earned stronger rebuilt posture ({score:.2f}).', - recovering_clearance_text='Fresh clearance-side evidence is returning after rebuilt posture softened or reset for {label}, but it has not yet re-earned stronger rebuilt posture ({score:.2f}).', - reentering_confirmation_text='Confirmation-side rebuilt posture for {label} is recovering strongly enough that stronger restored posture may be re-earned soon ({score:.2f}).', - reentering_clearance_text='Clearance-side rebuilt posture for {label} is recovering strongly enough that stronger restored caution may be re-earned soon ({score:.2f}).', - reversing_text='The post-reset rebuilt recovery attempt for {label} is changing direction, so stronger rebuilt posture stays blocked ({score:.2f}).', - blocked_reason_default='Local target instability is still preventing positive confirmation-side rebuilt re-entry for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side rebuilt recovery is strongest around {hotspot_label}, so those classes are closest to re-earning stronger rebuilt confirmation posture.', - recovering_clearance_hotspot_text='Clearance-side rebuilt recovery is strongest around {hotspot_label}, so those classes are closest to re-earning stronger rebuilt clearance posture.', - default_text='No rebuilt reset re-entry recovery attempt is active enough yet to re-earn stronger restored posture.', + status_key="closure_forecast_reset_reentry_rebuild_refresh_recovery_status", + score_key="closure_forecast_reset_reentry_rebuild_refresh_recovery_score", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_reason", + recovering_confirmation_status="recovering-confirmation-rebuild-reset", + recovering_clearance_status="recovering-clearance-rebuild-reset", + reentering_confirmation_status="reentering-confirmation-rebuild", + reentering_clearance_status="reentering-clearance-rebuild", + recovering_confirmation_text="Fresh confirmation-side evidence is returning after rebuilt posture softened or reset for {label}, but it has not yet re-earned stronger rebuilt posture ({score:.2f}).", + recovering_clearance_text="Fresh clearance-side evidence is returning after rebuilt posture softened or reset for {label}, but it has not yet re-earned stronger rebuilt posture ({score:.2f}).", + reentering_confirmation_text="Confirmation-side rebuilt posture for {label} is recovering strongly enough that stronger restored posture may be re-earned soon ({score:.2f}).", + reentering_clearance_text="Clearance-side rebuilt posture for {label} is recovering strongly enough that stronger restored caution may be re-earned soon ({score:.2f}).", + reversing_text="The post-reset rebuilt recovery attempt for {label} is changing direction, so stronger rebuilt posture stays blocked ({score:.2f}).", + blocked_reason_default="Local target instability is still preventing positive confirmation-side rebuilt re-entry for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side rebuilt recovery is strongest around {hotspot_label}, so those classes are closest to re-earning stronger rebuilt confirmation posture.", + recovering_clearance_hotspot_text="Clearance-side rebuilt recovery is strongest around {hotspot_label}, so those classes are closest to re-earning stronger rebuilt clearance posture.", + default_text="No rebuilt reset re-entry recovery attempt is active enough yet to re-earn stronger restored posture.", ) _RESTORE_REFRESH_RECOVERY_SUMMARY_SPEC = _RefreshRecoverySummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status', - score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_score', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason', - recovering_confirmation_status='recovering-confirmation-rebuild-reentry-restore-reset', - recovering_clearance_status='recovering-clearance-rebuild-reentry-restore-reset', - reentering_confirmation_status='rerestoring-confirmation-rebuild-reentry', - reentering_clearance_status='rerestoring-clearance-rebuild-reentry', - recovering_confirmation_text='Fresh confirmation-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but it has not yet re-restored stronger restored posture ({score:.2f}).', - recovering_clearance_text='Fresh clearance-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but it has not yet re-restored stronger restored posture ({score:.2f}).', - reentering_confirmation_text='Confirmation-side restored rebuilt re-entry for {label} is recovering strongly enough that stronger restored posture may be re-restored soon ({score:.2f}).', - reentering_clearance_text='Clearance-side restored rebuilt re-entry for {label} is recovering strongly enough that stronger restored posture may be re-restored soon ({score:.2f}).', - reversing_text='The post-reset restored rebuilt re-entry recovery attempt for {label} is changing direction, so stronger restored posture stays blocked ({score:.2f}).', - blocked_reason_default='Local target instability is still preventing positive confirmation-side restored rebuilt re-entry re-restore for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side restored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-restoring stronger restored confirmation posture.', - recovering_clearance_hotspot_text='Clearance-side restored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-restoring stronger restored clearance posture.', - default_text='No restored rebuilt re-entry recovery attempt is active enough yet to re-restore stronger posture.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", + score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_score", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason", + recovering_confirmation_status="recovering-confirmation-rebuild-reentry-restore-reset", + recovering_clearance_status="recovering-clearance-rebuild-reentry-restore-reset", + reentering_confirmation_status="rerestoring-confirmation-rebuild-reentry", + reentering_clearance_status="rerestoring-clearance-rebuild-reentry", + recovering_confirmation_text="Fresh confirmation-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but it has not yet re-restored stronger restored posture ({score:.2f}).", + recovering_clearance_text="Fresh clearance-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but it has not yet re-restored stronger restored posture ({score:.2f}).", + reentering_confirmation_text="Confirmation-side restored rebuilt re-entry for {label} is recovering strongly enough that stronger restored posture may be re-restored soon ({score:.2f}).", + reentering_clearance_text="Clearance-side restored rebuilt re-entry for {label} is recovering strongly enough that stronger restored posture may be re-restored soon ({score:.2f}).", + reversing_text="The post-reset restored rebuilt re-entry recovery attempt for {label} is changing direction, so stronger restored posture stays blocked ({score:.2f}).", + blocked_reason_default="Local target instability is still preventing positive confirmation-side restored rebuilt re-entry re-restore for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side restored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-restoring stronger restored confirmation posture.", + recovering_clearance_hotspot_text="Clearance-side restored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-restoring stronger restored clearance posture.", + default_text="No restored rebuilt re-entry recovery attempt is active enough yet to re-restore stronger posture.", ) _RERESTORE_REFRESH_RECOVERY_SUMMARY_SPEC = _RefreshRecoverySummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status', - score_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_score', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason', - recovering_confirmation_status='recovering-confirmation-rebuild-reentry-rerestore-reset', - recovering_clearance_status='recovering-clearance-rebuild-reentry-rerestore-reset', - reentering_confirmation_status='rererestoring-confirmation-rebuild-reentry', - reentering_clearance_status='rererestoring-clearance-rebuild-reentry', - recovering_confirmation_text='Fresh confirmation-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but it has not yet re-re-restored stronger rerestored posture ({score:.2f}).', - recovering_clearance_text='Fresh clearance-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but it has not yet re-re-restored stronger rerestored posture ({score:.2f}).', - reentering_confirmation_text='Confirmation-side rerestored rebuilt re-entry for {label} is recovering strongly enough that stronger rerestored posture may be re-re-restored soon ({score:.2f}).', - reentering_clearance_text='Clearance-side rerestored rebuilt re-entry for {label} is recovering strongly enough that stronger rerestored posture may be re-re-restored soon ({score:.2f}).', - reversing_text='The post-reset rerestored rebuilt re-entry recovery attempt for {label} is changing direction, so stronger posture stays blocked ({score:.2f}).', - blocked_reason_default='Local target instability is still preventing positive confirmation-side rerestored rebuilt re-entry re-re-restore for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side rerestored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-re-restoring stronger rerestored confirmation posture.', - recovering_clearance_hotspot_text='Clearance-side rerestored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-re-restoring stronger rerestored clearance posture.', - default_text='No rerestored rebuilt re-entry recovery attempt is active enough yet to re-re-restore stronger posture.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", + score_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_score", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason", + recovering_confirmation_status="recovering-confirmation-rebuild-reentry-rerestore-reset", + recovering_clearance_status="recovering-clearance-rebuild-reentry-rerestore-reset", + reentering_confirmation_status="rererestoring-confirmation-rebuild-reentry", + reentering_clearance_status="rererestoring-clearance-rebuild-reentry", + recovering_confirmation_text="Fresh confirmation-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but it has not yet re-re-restored stronger rerestored posture ({score:.2f}).", + recovering_clearance_text="Fresh clearance-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but it has not yet re-re-restored stronger rerestored posture ({score:.2f}).", + reentering_confirmation_text="Confirmation-side rerestored rebuilt re-entry for {label} is recovering strongly enough that stronger rerestored posture may be re-re-restored soon ({score:.2f}).", + reentering_clearance_text="Clearance-side rerestored rebuilt re-entry for {label} is recovering strongly enough that stronger rerestored posture may be re-re-restored soon ({score:.2f}).", + reversing_text="The post-reset rerestored rebuilt re-entry recovery attempt for {label} is changing direction, so stronger posture stays blocked ({score:.2f}).", + blocked_reason_default="Local target instability is still preventing positive confirmation-side rerestored rebuilt re-entry re-re-restore for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side rerestored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-re-restoring stronger rerestored confirmation posture.", + recovering_clearance_hotspot_text="Clearance-side rerestored rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to re-re-restoring stronger rerestored clearance posture.", + default_text="No rerestored rebuilt re-entry recovery attempt is active enough yet to re-re-restore stronger posture.", ) @@ -7435,54 +6715,54 @@ def _tier_summary_base( _REBUILD_REENTRY_SUMMARY_SPEC = _TierSummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_status', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_reason', - pending_confirmation_status='pending-confirmation-rebuild-reentry', - pending_clearance_status='pending-clearance-rebuild-reentry', - reentered_confirmation_status='reentered-confirmation-rebuild', - reentered_clearance_status='reentered-clearance-rebuild', - pending_confirmation_text='Fresh confirmation-side evidence is returning after rebuilt posture softened or reset for {label}, but stronger rebuilt posture still needs more fresh follow-through before it is re-earned.', - pending_clearance_text='Fresh clearance-side evidence is returning after rebuilt posture softened or reset for {label}, but stronger rebuilt posture still needs more fresh follow-through before it is re-earned.', - reentered_confirmation_text='Fresh confirmation-side follow-through for {label} has re-earned stronger rebuilt confirmation posture.', - reentered_clearance_text='Fresh clearance-side pressure for {label} has re-earned stronger rebuilt clearance posture.', - blocked_reason_default='Local target instability is still preventing positive confirmation-side rebuilt re-entry for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side rebuilt re-entry is closest around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.', - recovering_clearance_hotspot_text='Clearance-side rebuilt re-entry is closest around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.', - default_text='No rebuilt re-entry control is changing the current restored closure-forecast posture right now.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_status", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_reason", + pending_confirmation_status="pending-confirmation-rebuild-reentry", + pending_clearance_status="pending-clearance-rebuild-reentry", + reentered_confirmation_status="reentered-confirmation-rebuild", + reentered_clearance_status="reentered-clearance-rebuild", + pending_confirmation_text="Fresh confirmation-side evidence is returning after rebuilt posture softened or reset for {label}, but stronger rebuilt posture still needs more fresh follow-through before it is re-earned.", + pending_clearance_text="Fresh clearance-side evidence is returning after rebuilt posture softened or reset for {label}, but stronger rebuilt posture still needs more fresh follow-through before it is re-earned.", + reentered_confirmation_text="Fresh confirmation-side follow-through for {label} has re-earned stronger rebuilt confirmation posture.", + reentered_clearance_text="Fresh clearance-side pressure for {label} has re-earned stronger rebuilt clearance posture.", + blocked_reason_default="Local target instability is still preventing positive confirmation-side rebuilt re-entry for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side rebuilt re-entry is closest around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.", + recovering_clearance_hotspot_text="Clearance-side rebuilt re-entry is closest around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.", + default_text="No rebuilt re-entry control is changing the current restored closure-forecast posture right now.", ) _RERESTORE_SUMMARY_SPEC = _TierSummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason', - pending_confirmation_status='pending-confirmation-rebuild-reentry-rerestore', - pending_clearance_status='pending-clearance-rebuild-reentry-rerestore', - reentered_confirmation_status='rerestored-confirmation-rebuild-reentry', - reentered_clearance_status='rerestored-clearance-rebuild-reentry', - pending_confirmation_text='Fresh confirmation-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but stronger restored posture still needs more fresh follow-through before it is re-restored.', - pending_clearance_text='Fresh clearance-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but stronger restored posture still needs more fresh follow-through before it is re-restored.', - reentered_confirmation_text='Fresh confirmation-side follow-through for {label} has re-restored stronger restored rebuilt re-entry posture.', - reentered_clearance_text='Fresh clearance-side pressure for {label} has re-restored stronger restored rebuilt re-entry posture.', - blocked_reason_default='Local target instability is still preventing positive confirmation-side restored rebuilt re-entry re-restore for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side restored rebuilt re-entry is closest to being re-restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.', - recovering_clearance_hotspot_text='Clearance-side restored rebuilt re-entry is closest to being re-restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.', - default_text='No restored rebuilt re-entry re-restore control is changing the current closure-forecast posture right now.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason", + pending_confirmation_status="pending-confirmation-rebuild-reentry-rerestore", + pending_clearance_status="pending-clearance-rebuild-reentry-rerestore", + reentered_confirmation_status="rerestored-confirmation-rebuild-reentry", + reentered_clearance_status="rerestored-clearance-rebuild-reentry", + pending_confirmation_text="Fresh confirmation-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but stronger restored posture still needs more fresh follow-through before it is re-restored.", + pending_clearance_text="Fresh clearance-side evidence is returning after restored rebuilt re-entry softened or reset for {label}, but stronger restored posture still needs more fresh follow-through before it is re-restored.", + reentered_confirmation_text="Fresh confirmation-side follow-through for {label} has re-restored stronger restored rebuilt re-entry posture.", + reentered_clearance_text="Fresh clearance-side pressure for {label} has re-restored stronger restored rebuilt re-entry posture.", + blocked_reason_default="Local target instability is still preventing positive confirmation-side restored rebuilt re-entry re-restore for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side restored rebuilt re-entry is closest to being re-restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.", + recovering_clearance_hotspot_text="Clearance-side restored rebuilt re-entry is closest to being re-restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.", + default_text="No restored rebuilt re-entry re-restore control is changing the current closure-forecast posture right now.", ) _RERERESTORE_SUMMARY_SPEC = _TierSummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason', - pending_confirmation_status='pending-confirmation-rebuild-reentry-rererestore', - pending_clearance_status='pending-clearance-rebuild-reentry-rererestore', - reentered_confirmation_status='rererestored-confirmation-rebuild-reentry', - reentered_clearance_status='rererestored-clearance-rebuild-reentry', - pending_confirmation_text='Fresh confirmation-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but stronger rerestored posture still needs more fresh follow-through before it is re-re-restored.', - pending_clearance_text='Fresh clearance-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but stronger rerestored posture still needs more fresh follow-through before it is re-re-restored.', - reentered_confirmation_text='Fresh confirmation-side follow-through for {label} has re-re-restored stronger rerestored rebuilt re-entry posture.', - reentered_clearance_text='Fresh clearance-side pressure for {label} has re-re-restored stronger rerestored rebuilt re-entry posture.', - blocked_reason_default='Local target instability is still preventing positive confirmation-side rerestored rebuilt re-entry re-re-restore for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side rerestored rebuilt re-entry is closest to being re-re-restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.', - recovering_clearance_hotspot_text='Clearance-side rerestored rebuilt re-entry is closest to being re-re-restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.', - default_text='No rerestored rebuilt re-entry re-re-restore control is changing the current closure-forecast posture right now.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason", + pending_confirmation_status="pending-confirmation-rebuild-reentry-rererestore", + pending_clearance_status="pending-clearance-rebuild-reentry-rererestore", + reentered_confirmation_status="rererestored-confirmation-rebuild-reentry", + reentered_clearance_status="rererestored-clearance-rebuild-reentry", + pending_confirmation_text="Fresh confirmation-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but stronger rerestored posture still needs more fresh follow-through before it is re-re-restored.", + pending_clearance_text="Fresh clearance-side evidence is returning after rerestored rebuilt re-entry softened or reset for {label}, but stronger rerestored posture still needs more fresh follow-through before it is re-re-restored.", + reentered_confirmation_text="Fresh confirmation-side follow-through for {label} has re-re-restored stronger rerestored rebuilt re-entry posture.", + reentered_clearance_text="Fresh clearance-side pressure for {label} has re-re-restored stronger rerestored rebuilt re-entry posture.", + blocked_reason_default="Local target instability is still preventing positive confirmation-side rerestored rebuilt re-entry re-re-restore for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side rerestored rebuilt re-entry is closest to being re-re-restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.", + recovering_clearance_hotspot_text="Clearance-side rerestored rebuilt re-entry is closest to being re-re-restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.", + default_text="No rerestored rebuilt re-entry re-re-restore control is changing the current closure-forecast posture right now.", ) @@ -7540,15 +6820,21 @@ def _apply_reset_reentry_rebuild_refresh_recovery_and_reentry( reentry_reason = "" refresh_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") resolution_status = target.get("class_transition_resolution_status", "none") resolution_reason = target.get("class_transition_resolution_reason", "") - rebuild_status = target.get("closure_forecast_reset_reentry_rebuild_status", "none") + rebuild_status = target.get( + "closure_forecast_reset_reentry_rebuild_status", "none" + ) rebuild_reason = target.get("closure_forecast_reset_reentry_rebuild_reason", "") - persistence_age_runs = target.get("closure_forecast_reset_reentry_rebuild_age_runs", 0) + persistence_age_runs = target.get( + "closure_forecast_reset_reentry_rebuild_age_runs", 0 + ) persistence_score = target.get( "closure_forecast_reset_reentry_rebuild_persistence_score", 0.0, @@ -7567,10 +6853,12 @@ def _apply_reset_reentry_rebuild_refresh_recovery_and_reentry( target, transition_events, ) - refresh_meta = _closure_forecast_reset_reentry_rebuild_refresh_recovery_for_target( - target, - closure_forecast_events, - transition_history_meta, + refresh_meta = ( + _closure_forecast_reset_reentry_rebuild_refresh_recovery_for_target( + target, + closure_forecast_events, + transition_history_meta, + ) ) refresh_recovery_score = refresh_meta[ "closure_forecast_reset_reentry_rebuild_refresh_recovery_score" @@ -7578,8 +6866,12 @@ def _apply_reset_reentry_rebuild_refresh_recovery_and_reentry( refresh_recovery_status = refresh_meta[ "closure_forecast_reset_reentry_rebuild_refresh_recovery_status" ] - reentry_status = refresh_meta["closure_forecast_reset_reentry_rebuild_reentry_status"] - reentry_reason = refresh_meta["closure_forecast_reset_reentry_rebuild_reentry_reason"] + reentry_status = refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_status" + ] + reentry_reason = refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_reason" + ] refresh_path = refresh_meta["recent_reset_reentry_rebuild_refresh_path"] control_updates = _apply_reset_reentry_rebuild_refresh_reentry_control( target, @@ -7599,15 +6891,25 @@ def _apply_reset_reentry_rebuild_refresh_recovery_and_reentry( persistence_status=persistence_status, persistence_reason=persistence_reason, ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] resolution_reason = control_updates["class_transition_resolution_reason"] - rebuild_status = control_updates["closure_forecast_reset_reentry_rebuild_status"] - rebuild_reason = control_updates["closure_forecast_reset_reentry_rebuild_reason"] + rebuild_status = control_updates[ + "closure_forecast_reset_reentry_rebuild_status" + ] + rebuild_reason = control_updates[ + "closure_forecast_reset_reentry_rebuild_reason" + ] persistence_age_runs = control_updates[ "closure_forecast_reset_reentry_rebuild_age_runs" ] @@ -7647,13 +6949,17 @@ def _apply_reset_reentry_rebuild_refresh_recovery_and_reentry( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - recovering_confirmation_hotspots = _closure_forecast_reset_reentry_rebuild_refresh_hotspots( - resolution_targets, - mode="confirmation", + recovering_confirmation_hotspots = ( + _closure_forecast_reset_reentry_rebuild_refresh_hotspots( + resolution_targets, + mode="confirmation", + ) ) - recovering_clearance_hotspots = _closure_forecast_reset_reentry_rebuild_refresh_hotspots( - resolution_targets, - mode="clearance", + recovering_clearance_hotspots = ( + _closure_forecast_reset_reentry_rebuild_refresh_hotspots( + resolution_targets, + mode="clearance", + ) ) return { "primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_score": primary_target.get( @@ -7731,12 +7037,14 @@ def _closure_forecast_reset_reentry_rebuild_reentry_path_label(event: dict) -> s if persistence_status != "none": return persistence_status churn_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none") or "none" + event.get("closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none") + or "none" ) if churn_status != "none": return churn_status reentry_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") or "none" + event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") + or "none" ) if reentry_status != "none": return reentry_status @@ -7750,7 +7058,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_path_label(event: dict) -> s if refresh_status != "none": return refresh_status reset_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") or "none" + event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + or "none" ) if reset_status != "none": return reset_status @@ -7772,16 +7081,21 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( relevant_events = [ event for event in matching_events - if _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) != "none" + if _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) + != "none" ] current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(matching_events[0]) + _closure_forecast_reset_reentry_rebuild_reentry_side_from_event( + matching_events[0] + ) if matching_events else "none" ) persistence_age_runs = 0 for event in matching_events: - event_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) + event_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_event( + event + ) if event_side != current_side or event_side == "none": break persistence_age_runs += 1 @@ -7795,11 +7109,17 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( weight = (1.0, 0.8, 0.6, 0.4)[ min(index, CLASS_RESET_REENTRY_REBUILD_REENTRY_WINDOW_RUNS - 1) ] - event_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) + event_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_event( + event + ) sign = 1.0 if event_side == "confirmation" else -1.0 - directions.append("supporting-confirmation" if sign > 0 else "supporting-clearance") + directions.append( + "supporting-confirmation" if sign > 0 else "supporting-clearance" + ) magnitude = 0.0 - if event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") in { + if event.get( + "closure_forecast_reset_reentry_rebuild_reentry_status", "none" + ) in { "reentered-confirmation-rebuild", "reentered-clearance-rebuild", }: @@ -7816,9 +7136,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( "closure_forecast_momentum_status", "insufficient-data", ) - if (event_side == "confirmation" and momentum_status == "sustained-confirmation") or ( - event_side == "clearance" and momentum_status == "sustained-clearance" - ): + if ( + event_side == "confirmation" and momentum_status == "sustained-confirmation" + ) or (event_side == "clearance" and momentum_status == "sustained-clearance"): magnitude += 0.10 stability_status = event.get("closure_forecast_stability_status", "watch") if stability_status == "stable": @@ -7835,7 +7155,10 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( magnitude = max(0.0, magnitude - 0.15) if stability_status == "oscillating": magnitude = max(0.0, magnitude - 0.15) - if event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") != "none": + if ( + event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + != "none" + ): magnitude = max(0.0, magnitude - 0.15) weighted_total += sign * magnitude * weight weight_sum += weight @@ -7876,7 +7199,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( elif ( _closure_forecast_direction_reversing(current_direction, earlier_majority) or current_momentum_status in {"reversing", "unstable"} - or target.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") != "none" + or target.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + != "none" ): persistence_status = "reversing" elif ( @@ -7895,17 +7219,23 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( and current_stability_status != "oscillating" ): persistence_status = "sustained-clearance-rebuild-reentry" - elif current_side == "confirmation" and persistence_age_runs >= 2 and persistence_score > 0: + elif ( + current_side == "confirmation" + and persistence_age_runs >= 2 + and persistence_score > 0 + ): persistence_status = "holding-confirmation-rebuild-reentry" - elif current_side == "clearance" and persistence_age_runs >= 2 and persistence_score < 0: + elif ( + current_side == "clearance" + and persistence_age_runs >= 2 + and persistence_score < 0 + ): persistence_status = "holding-clearance-rebuild-reentry" else: persistence_status = "none" if persistence_status == "just-reentered": - persistence_reason = ( - "Stronger rebuilt posture has been re-earned, but it has not yet proved it can hold." - ) + persistence_reason = "Stronger rebuilt posture has been re-earned, but it has not yet proved it can hold." elif persistence_status == "holding-confirmation-rebuild-reentry": persistence_reason = "Confirmation-side rebuilt re-entry has stayed aligned long enough to keep the restored forecast in place." elif persistence_status == "holding-clearance-rebuild-reentry": @@ -7915,9 +7245,7 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_for_target( elif persistence_status == "sustained-clearance-rebuild-reentry": persistence_reason = "Clearance-side rebuilt re-entry is now holding with enough follow-through to trust the restored caution more." elif persistence_status == "reversing": - persistence_reason = ( - "The re-earned rebuilt posture is already weakening, so it is being softened again." - ) + persistence_reason = "The re-earned rebuilt posture is already weakening, so it is being softened again." elif persistence_status == "insufficient-data": persistence_reason = "Rebuilt re-entry is still too lightly exercised to say whether the restored forecast can hold." else: @@ -7948,7 +7276,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_churn_for_target( relevant_events = [ event for event in matching_events - if _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) != "none" + if _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) + != "none" ] side_path = [ _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) @@ -7963,13 +7292,17 @@ def _closure_forecast_reset_reentry_rebuild_reentry_churn_for_target( else: flip_count = _class_direction_flip_count( [ - "supporting-confirmation" if side == "confirmation" else "supporting-clearance" + "supporting-confirmation" + if side == "confirmation" + else "supporting-clearance" for side in side_path ] ) churn_score = float(flip_count) * 0.20 stability_status = target.get("closure_forecast_stability_status", "watch") - momentum_status = target.get("closure_forecast_momentum_status", "insufficient-data") + momentum_status = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) if stability_status == "oscillating": churn_score += 0.15 if momentum_status == "reversing": @@ -7984,12 +7317,14 @@ def _closure_forecast_reset_reentry_rebuild_reentry_churn_for_target( for event in relevant_events ] if any( - previous == "fresh" and current in {"mixed-age", "stale", "insufficient-data"} + previous == "fresh" + and current in {"mixed-age", "stale", "insufficient-data"} for previous, current in zip(freshness_path, freshness_path[1:]) ): churn_score += 0.10 if any( - event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") != "none" + event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + != "none" for event in relevant_events ): churn_score += 0.10 @@ -8017,7 +7352,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_churn_for_target( churn_reason = "Rebuilt re-entry is flipping enough that restored posture should be softened quickly." elif churn_score >= 0.20: churn_status = "watch" - churn_reason = "Rebuilt re-entry is wobbling and may lose its restored strength soon." + churn_reason = ( + "Rebuilt re-entry is wobbling and may lose its restored strength soon." + ) else: churn_status = "none" churn_reason = "" @@ -8078,10 +7415,12 @@ def _apply_reset_reentry_rebuild_reentry_persistence_and_churn_control( current_reentry_status ) if current_side == "none": - current_side = _closure_forecast_reset_reentry_rebuild_side_from_refresh_recovery_status( - target.get( - "closure_forecast_reset_reentry_rebuild_refresh_recovery_status", - "none", + current_side = ( + _closure_forecast_reset_reentry_rebuild_side_from_refresh_recovery_status( + target.get( + "closure_forecast_reset_reentry_rebuild_refresh_recovery_status", + "none", + ) ) ) if ( @@ -8104,7 +7443,9 @@ def _apply_reset_reentry_rebuild_reentry_persistence_and_churn_control( closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": closure_hysteresis_status = "pending-confirmation" - closure_hysteresis_reason = churn_reason or persistence_reason or closure_hysteresis_reason + closure_hysteresis_reason = ( + churn_reason or persistence_reason or closure_hysteresis_reason + ) return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -8286,7 +7627,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_persistence_summary( f"Rebuilt re-entry is holding most cleanly around {hotspot.get('label', 'recent hotspots')}, " "so those classes are closest to keeping re-earned rebuilt strength safely." ) - return "No rebuilt re-entry posture is active enough yet to judge whether it can hold." + return ( + "No rebuilt re-entry posture is active enough yet to judge whether it can hold." + ) def _closure_forecast_reset_reentry_rebuild_reentry_churn_summary( @@ -8369,7 +7712,9 @@ def _apply_reset_reentry_rebuild_reentry_persistence_and_churn( churn_reason = "" churn_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -8388,10 +7733,12 @@ def _apply_reset_reentry_rebuild_reentry_persistence_and_churn( transition_history_meta, ) ) - churn_meta = _closure_forecast_reset_reentry_rebuild_reentry_churn_for_target( - target, - closure_forecast_events, - transition_history_meta, + churn_meta = ( + _closure_forecast_reset_reentry_rebuild_reentry_churn_for_target( + target, + closure_forecast_events, + transition_history_meta, + ) ) persistence_age_runs = persistence_meta[ "closure_forecast_reset_reentry_rebuild_reentry_age_runs" @@ -8408,26 +7755,40 @@ def _apply_reset_reentry_rebuild_reentry_persistence_and_churn( persistence_path = persistence_meta[ "recent_reset_reentry_rebuild_reentry_persistence_path" ] - churn_score = churn_meta["closure_forecast_reset_reentry_rebuild_reentry_churn_score"] - churn_status = churn_meta["closure_forecast_reset_reentry_rebuild_reentry_churn_status"] - churn_reason = churn_meta["closure_forecast_reset_reentry_rebuild_reentry_churn_reason"] + churn_score = churn_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_churn_score" + ] + churn_status = churn_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_churn_status" + ] + churn_reason = churn_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_churn_reason" + ] churn_path = churn_meta["recent_reset_reentry_rebuild_reentry_churn_path"] - control_updates = _apply_reset_reentry_rebuild_reentry_persistence_and_churn_control( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, + control_updates = ( + _apply_reset_reentry_rebuild_reentry_persistence_and_churn_control( + target, + persistence_meta=persistence_meta, + churn_meta=churn_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + ) ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -8457,9 +7818,11 @@ def _apply_reset_reentry_rebuild_reentry_persistence_and_churn( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - just_reentered_rebuild_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_hotspots( - resolution_targets, - mode="just-reentered", + just_reentered_rebuild_hotspots = ( + _closure_forecast_reset_reentry_rebuild_reentry_hotspots( + resolution_targets, + mode="just-reentered", + ) ) holding_reset_reentry_rebuild_reentry_hotspots = ( _closure_forecast_reset_reentry_rebuild_reentry_hotspots( @@ -8558,7 +7921,8 @@ def _reset_reentry_rebuild_reentry_event_is_clearance_like(event: dict) -> bool: } or event.get("closure_forecast_hysteresis_status", "none") in {"pending-clearance", "confirmed-clearance"} - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} ) @@ -8566,7 +7930,9 @@ def _reset_reentry_rebuild_reentry_event_has_evidence(event: dict) -> bool: return ( _reset_reentry_rebuild_reentry_event_is_confirmation_like(event) or _reset_reentry_rebuild_reentry_event_is_clearance_like(event) - or event.get("closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none") + or event.get( + "closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none" + ) in {"watch", "churn", "blocked"} ) @@ -8625,7 +7991,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_freshness_for_target( ) -> dict: class_key = _target_class_key(target) class_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key + event + for event in closure_forecast_events + if event.get("class_key") == class_key ] relevant_events: list[dict] = [] for event in class_events: @@ -8639,10 +8007,12 @@ def _closure_forecast_reset_reentry_rebuild_reentry_freshness_for_target( weighted_confirmation_like = 0.0 weighted_clearance_like = 0.0 recent_reentry_weight = 0.0 - current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_persistence_status( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", - "none", + current_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_side_from_persistence_status( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", + "none", + ) ) ) if current_side == "none": @@ -8653,7 +8023,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_freshness_for_target( for index, event in enumerate(relevant_events): weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_reentry_evidence_count += weight - event_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) + event_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_event( + event + ) if ( index < CLASS_RESET_REENTRY_REBUILD_REENTRY_FRESHNESS_WINDOW_RUNS and event_side == current_side @@ -8708,7 +8080,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_freshness_for_target( recent_window_weight_share, ), "has_fresh_aligned_recent_evidence": any( - _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) == current_side + _closure_forecast_reset_reentry_rebuild_reentry_side_from_event(event) + == current_side and _reset_reentry_rebuild_reentry_event_signal_label(event) != "neutral" for event in relevant_events[:2] ), @@ -8745,8 +8118,10 @@ def _apply_reset_reentry_rebuild_reentry_freshness_reset_control( "closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none", ) - current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_persistence_status( - persistence_status + current_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_side_from_persistence_status( + persistence_status + ) ) if current_side == "none": current_side = _closure_forecast_reset_reentry_rebuild_side_from_reentry_status( @@ -8782,9 +8157,7 @@ def _restore_weaker_pending_posture( ) if local_noise and current_side != "none": - blocked_reason = ( - "Local target instability still overrides healthy rebuilt re-entry freshness." - ) + blocked_reason = "Local target instability still overrides healthy rebuilt re-entry freshness." if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" elif closure_likely_outcome == "expire-risk": @@ -8840,7 +8213,10 @@ def _restore_weaker_pending_posture( "closure_forecast_reset_reentry_rebuild_reentry_persistence_status": "holding-confirmation-rebuild-reentry", "closure_forecast_reset_reentry_rebuild_reentry_persistence_reason": softened_reason, } - if persistence_status == "holding-confirmation-rebuild-reentry" and churn_status == "churn": + if ( + persistence_status == "holding-confirmation-rebuild-reentry" + and churn_status == "churn" + ): freshness_status = "stale" if current_side == "clearance" and freshness_status == "mixed-age": @@ -8865,7 +8241,10 @@ def _restore_weaker_pending_posture( "closure_forecast_reset_reentry_rebuild_reentry_persistence_status": "holding-clearance-rebuild-reentry", "closure_forecast_reset_reentry_rebuild_reentry_persistence_reason": softened_reason, } - if persistence_status == "holding-clearance-rebuild-reentry" and churn_status == "churn": + if ( + persistence_status == "holding-clearance-rebuild-reentry" + and churn_status == "churn" + ): freshness_status = "stale" needs_reset = ( @@ -9079,21 +8458,21 @@ def _freshness_hotspots_base( _REBUILD_REENTRY_FRESHNESS_HOTSPOTS_SPEC = _FreshnessHotspotsSpec( - freshness_status_key='closure_forecast_reset_reentry_rebuild_reentry_freshness_status', - confirmation_rate_key='decayed_reentered_rebuild_confirmation_rate', - clearance_rate_key='decayed_reentered_rebuild_clearance_rate', - signal_mix_key='recent_reset_reentry_rebuild_reentry_signal_mix', - event_count_out_key='reentry_event_count', - age_runs_key='closure_forecast_reset_reentry_rebuild_reentry_age_runs', + freshness_status_key="closure_forecast_reset_reentry_rebuild_reentry_freshness_status", + confirmation_rate_key="decayed_reentered_rebuild_confirmation_rate", + clearance_rate_key="decayed_reentered_rebuild_clearance_rate", + signal_mix_key="recent_reset_reentry_rebuild_reentry_signal_mix", + event_count_out_key="reentry_event_count", + age_runs_key="closure_forecast_reset_reentry_rebuild_reentry_age_runs", ) _RESTORE_FRESHNESS_HOTSPOTS_SPEC = _FreshnessHotspotsSpec( - freshness_status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status', - confirmation_rate_key='decayed_restored_rebuild_reentry_confirmation_rate', - clearance_rate_key='decayed_restored_rebuild_reentry_clearance_rate', - signal_mix_key='recent_reset_reentry_rebuild_reentry_restore_signal_mix', - event_count_out_key='restore_event_count', - age_runs_key='closure_forecast_reset_reentry_rebuild_reentry_restore_age_runs', + freshness_status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", + confirmation_rate_key="decayed_restored_rebuild_reentry_confirmation_rate", + clearance_rate_key="decayed_restored_rebuild_reentry_clearance_rate", + signal_mix_key="recent_reset_reentry_rebuild_reentry_restore_signal_mix", + event_count_out_key="restore_event_count", + age_runs_key="closure_forecast_reset_reentry_rebuild_reentry_restore_age_runs", ) @@ -9240,7 +8619,9 @@ def _apply_reset_reentry_rebuild_reentry_freshness_and_reset( reset_status = "none" reset_reason = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -9276,9 +8657,11 @@ def _apply_reset_reentry_rebuild_reentry_freshness_and_reset( target, transition_events, ) - freshness_meta = _closure_forecast_reset_reentry_rebuild_reentry_freshness_for_target( - target, - closure_forecast_events, + freshness_meta = ( + _closure_forecast_reset_reentry_rebuild_reentry_freshness_for_target( + target, + closure_forecast_events, + ) ) freshness_status = freshness_meta[ "closure_forecast_reset_reentry_rebuild_reentry_freshness_status" @@ -9292,25 +8675,31 @@ def _apply_reset_reentry_rebuild_reentry_freshness_and_reset( decayed_confirmation_rate = freshness_meta[ "decayed_reentered_rebuild_confirmation_rate" ] - decayed_clearance_rate = freshness_meta["decayed_reentered_rebuild_clearance_rate"] - signal_mix = freshness_meta["recent_reset_reentry_rebuild_reentry_signal_mix"] - control_updates = _apply_reset_reentry_rebuild_reentry_freshness_reset_control( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, + decayed_clearance_rate = freshness_meta[ + "decayed_reentered_rebuild_clearance_rate" + ] + signal_mix = freshness_meta[ + "recent_reset_reentry_rebuild_reentry_signal_mix" + ] + control_updates = ( + _apply_reset_reentry_rebuild_reentry_freshness_reset_control( + target, + freshness_meta=freshness_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + persistence_age_runs=persistence_age_runs, + persistence_score=persistence_score, + persistence_status=persistence_status, + persistence_reason=persistence_reason, + ) ) reset_status = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_reset_status" @@ -9318,9 +8707,15 @@ def _apply_reset_reentry_rebuild_reentry_freshness_and_reset( reset_reason = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_reset_reason" ] - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -9448,9 +8843,58 @@ def _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistenc ) -def _closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label(event: dict) -> str: +def _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event: dict, +) -> str: + side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + "none", + ) + ) + if side != "none": + return side + side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) + ) + if side != "none": + return side + return _closure_forecast_reset_reentry_rebuild_reentry_side_from_refresh_recovery_status( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + "none", + ) + ) + + +def _closure_forecast_reset_reentry_rebuild_reentry_restore_path_label( + event: dict, +) -> str: + persistence_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + "none", + ) + or "none" + ) + if persistence_status != "none": + return persistence_status + churn_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", + "none", + ) + or "none" + ) + if churn_status != "none": + return churn_status restore_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") or "none" + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) + or "none" ) if restore_status != "none": return restore_status @@ -9464,260 +8908,51 @@ def _closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label(event: di if refresh_status != "none": return refresh_status reset_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") or "none" + event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") + or "none" ) if reset_status != "none": return reset_status - score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) - direction = _normalized_closure_forecast_direction( - event.get("closure_forecast_reweight_direction", "neutral"), - score, - ) - freshness = event.get( - "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", - "insufficient-data", - ) - if direction == "supporting-confirmation": - return f"{freshness} confirmation" - if direction == "supporting-clearance": - return f"{freshness} clearance" likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" if likely_outcome != "none": return likely_outcome return "hold" -def _closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_for_target( +def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_target( target: dict, closure_forecast_events: list[dict], transition_history_meta: dict, ) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_for_target_helper( + matching_events = _ordered_reset_reentry_events_for_target( target, closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=_closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label=( - _closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label - ), - class_reset_reentry_rebuild_reentry_refresh_restore_window_runs=( - CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS - ), - ) - - -def _apply_reset_reentry_rebuild_reentry_refresh_restore_control( - target: dict, - *, - refresh_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reentry_status: str, - reentry_reason: str, - persistence_age_runs: int, - persistence_score: float, - persistence_status: str, - persistence_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_refresh_restore_control_helper( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, + )[:CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_WINDOW_RUNS] + relevant_events = [ + event + for event in matching_events + if _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) + != "none" + ] + current_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + matching_events[0] + ) + if matching_events + else "none" ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore_helper( - resolution_targets, - history, - current_generated_at=current_generated_at, - confidence_calibration=confidence_calibration, - recommendation_bucket=_recommendation_bucket, - class_closure_forecast_events=_class_closure_forecast_events, - class_transition_events=_class_transition_events, - target_class_transition_history=_target_class_transition_history, - target_class_key=_target_class_key, - target_label=_target_label, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=_closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label=( - _closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label - ), - class_reset_reentry_rebuild_reentry_refresh_restore_window_runs=( - CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS - ), - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( - event: dict, -) -> str: - side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", - "none", - ) - ) - if side != "none": - return side - side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( - event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") - ) - if side != "none": - return side - return _closure_forecast_reset_reentry_rebuild_reentry_side_from_refresh_recovery_status( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", - "none", - ) - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_path_label( - event: dict, -) -> str: - persistence_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", - "none", - ) - or "none" - ) - if persistence_status != "none": - return persistence_status - churn_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", - "none", - ) - or "none" - ) - if churn_status != "none": - return churn_status - restore_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") or "none" - ) - if restore_status != "none": - return restore_status - refresh_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", - "none", - ) - or "none" - ) - if refresh_status != "none": - return refresh_status - reset_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") or "none" - ) - if reset_status != "none": - return reset_status - likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" - if likely_outcome != "none": - return likely_outcome - return "hold" - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - matching_events = _ordered_reset_reentry_events_for_target( - target, - closure_forecast_events, - )[:CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_WINDOW_RUNS] - relevant_events = [ - event - for event in matching_events - if _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) != "none" - ] - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(matching_events[0]) - if matching_events - else "none" - ) - persistence_age_runs = 0 - for event in matching_events: - event_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) - if event_side != current_side or event_side == "none": - break - persistence_age_runs += 1 + persistence_age_runs = 0 + for event in matching_events: + event_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) + ) + if event_side != current_side or event_side == "none": + break + persistence_age_runs += 1 weighted_total = 0.0 weight_sum = 0.0 @@ -9728,11 +8963,19 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_targ weight = (1.0, 0.8, 0.6, 0.4)[ min(index, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_WINDOW_RUNS - 1) ] - event_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) + event_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) + ) sign = 1.0 if event_side == "confirmation" else -1.0 - directions.append("supporting-confirmation" if sign > 0 else "supporting-clearance") + directions.append( + "supporting-confirmation" if sign > 0 else "supporting-clearance" + ) magnitude = 0.0 - if event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") in { + if event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) in { "restored-confirmation-rebuild-reentry", "restored-clearance-rebuild-reentry", }: @@ -9749,9 +8992,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_targ "closure_forecast_momentum_status", "insufficient-data", ) - if (event_side == "confirmation" and momentum_status == "sustained-confirmation") or ( - event_side == "clearance" and momentum_status == "sustained-clearance" - ): + if ( + event_side == "confirmation" and momentum_status == "sustained-confirmation" + ) or (event_side == "clearance" and momentum_status == "sustained-clearance"): magnitude += 0.10 stability_status = event.get("closure_forecast_stability_status", "watch") if stability_status == "stable": @@ -9769,7 +9012,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_targ if stability_status == "oscillating": magnitude = max(0.0, magnitude - 0.15) if ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none" + ) != "none" ): magnitude = max(0.0, magnitude - 0.15) @@ -9802,7 +9047,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_targ if current_side == "none" and not relevant_events: persistence_status = "none" elif ( - target.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) in { "restored-confirmation-rebuild-reentry", "restored-clearance-rebuild-reentry", @@ -9815,7 +9062,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_targ elif ( _closure_forecast_direction_reversing(current_direction, earlier_majority) or current_momentum_status in {"reversing", "unstable"} - or target.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") + or target.get( + "closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none" + ) != "none" ): persistence_status = "reversing" @@ -9835,9 +9084,17 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_targ and current_stability_status != "oscillating" ): persistence_status = "sustained-clearance-rebuild-reentry-restore" - elif current_side == "confirmation" and persistence_age_runs >= 2 and persistence_score > 0: + elif ( + current_side == "confirmation" + and persistence_age_runs >= 2 + and persistence_score > 0 + ): persistence_status = "holding-confirmation-rebuild-reentry-restore" - elif current_side == "clearance" and persistence_age_runs >= 2 and persistence_score < 0: + elif ( + current_side == "clearance" + and persistence_age_runs >= 2 + and persistence_score < 0 + ): persistence_status = "holding-clearance-rebuild-reentry-restore" else: persistence_status = "none" @@ -9884,7 +9141,10 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_churn_for_target( relevant_events = [ event for event in matching_events - if _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) != "none" + if _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) + != "none" ] side_path = [ _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) @@ -9899,13 +9159,17 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_churn_for_target( else: flip_count = _class_direction_flip_count( [ - "supporting-confirmation" if side == "confirmation" else "supporting-clearance" + "supporting-confirmation" + if side == "confirmation" + else "supporting-clearance" for side in side_path ] ) churn_score = float(flip_count) * 0.20 stability_status = target.get("closure_forecast_stability_status", "watch") - momentum_status = target.get("closure_forecast_momentum_status", "insufficient-data") + momentum_status = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) if stability_status == "oscillating": churn_score += 0.15 if momentum_status == "reversing": @@ -9920,12 +9184,15 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_churn_for_target( for event in relevant_events ] if any( - previous == "fresh" and current in {"mixed-age", "stale", "insufficient-data"} + previous == "fresh" + and current in {"mixed-age", "stale", "insufficient-data"} for previous, current in zip(freshness_path, freshness_path[1:]) ): churn_score += 0.10 if any( - event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none" + ) != "none" for event in relevant_events ): @@ -9954,9 +9221,7 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_churn_for_target( churn_reason = "Restored rebuilt re-entry is flipping enough that restored posture should be softened quickly." elif churn_score >= 0.20: churn_status = "watch" - churn_reason = ( - "Restored rebuilt re-entry is wobbling and may lose its restored strength soon." - ) + churn_reason = "Restored rebuilt re-entry is wobbling and may lose its restored strength soon." else: churn_status = "none" churn_reason = "" @@ -10021,14 +9286,14 @@ def _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn_control( ) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) recent_pending_status = transition_history_meta.get("recent_pending_status", "none") - current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( - current_restore_status + current_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( + current_restore_status + ) ) if current_side == "none": - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_side_from_refresh_recovery_status( - current_refresh_status - ) + current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_refresh_recovery_status( + current_refresh_status ) if ( current_side == "none" @@ -10055,7 +9320,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn_control( closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": closure_hysteresis_status = "pending-confirmation" - closure_hysteresis_reason = churn_reason or persistence_reason or closure_hysteresis_reason + closure_hysteresis_reason = ( + churn_reason or persistence_reason or closure_hysteresis_reason + ) return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -10361,7 +9628,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn( churn_reason = "" churn_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -10381,12 +9650,10 @@ def _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn( target, transition_events, ) - persistence_meta = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + persistence_meta = _closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_for_target( + target, + closure_forecast_events, + transition_history_meta, ) churn_meta = _closure_forecast_reset_reentry_rebuild_reentry_restore_churn_for_target( target, @@ -10417,25 +9684,31 @@ def _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn( churn_reason = churn_meta[ "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_reason" ] - churn_path = churn_meta["recent_reset_reentry_rebuild_reentry_restore_churn_path"] - control_updates = ( - _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn_control( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - ) + churn_path = churn_meta[ + "recent_reset_reentry_rebuild_reentry_restore_churn_path" + ] + control_updates = _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn_control( + target, + persistence_meta=persistence_meta, + churn_meta=churn_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -10536,7 +9809,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_persistence_and_churn( } -def _reset_reentry_rebuild_reentry_restore_event_is_confirmation_like(event: dict) -> bool: +def _reset_reentry_rebuild_reentry_restore_event_is_confirmation_like( + event: dict, +) -> bool: return ( event.get( "closure_forecast_reset_reentry_rebuild_reentry_restore_status", @@ -10582,7 +9857,8 @@ def _reset_reentry_rebuild_reentry_restore_event_is_clearance_like(event: dict) } or event.get("closure_forecast_hysteresis_status", "none") in {"pending-clearance", "confirmed-clearance"} - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} ) @@ -10644,7 +9920,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_for_target ) -> dict: class_key = _target_class_key(target) class_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key + event + for event in closure_forecast_events + if event.get("class_key") == class_key ] relevant_events: list[dict] = [] for event in class_events: @@ -10658,26 +9936,30 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_for_target weighted_confirmation_like = 0.0 weighted_clearance_like = 0.0 recent_restore_weight = 0.0 - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", - "none", - ) + current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + "none", ) ) if current_side == "none": - current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_status", - "none", + current_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", + "none", + ) ) ) for index, event in enumerate(relevant_events): weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_restore_evidence_count += weight - event_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) + event_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) + ) if ( index < CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_FRESHNESS_WINDOW_RUNS and event_side == current_side @@ -10732,9 +10014,13 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_for_target recent_window_weight_share, ), "has_fresh_aligned_recent_evidence": any( - _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) + _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) == current_side - and _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) + and _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) != "none" for event in relevant_events[:2] ), @@ -10767,20 +10053,21 @@ def _apply_reset_reentry_rebuild_reentry_restore_freshness_reset_control( "insufficient-data", ) decayed_clearance_rate = float( - freshness_meta.get("decayed_restored_rebuild_reentry_clearance_rate", 0.0) or 0.0 + freshness_meta.get("decayed_restored_rebuild_reentry_clearance_rate", 0.0) + or 0.0 ) churn_status = target.get( "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", "none", ) - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status( - persistence_status - ) + current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status( + persistence_status ) if current_side == "none": - current_side = _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( - restore_status + current_side = ( + _closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status( + restore_status + ) ) local_noise = _target_specific_normalization_noise(target, transition_history_meta) recent_pending_status = transition_history_meta.get("recent_pending_status", "none") @@ -10812,9 +10099,7 @@ def _restore_weaker_pending_posture( ) if local_noise and current_side != "none": - blocked_reason = ( - "Local target instability still overrides healthy restored rebuilt re-entry freshness." - ) + blocked_reason = "Local target instability still overrides healthy restored rebuilt re-entry freshness." if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" elif closure_likely_outcome == "expire-risk": @@ -11197,7 +10482,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_freshness_and_reset( reset_status = "none" reset_reason = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -11241,11 +10528,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_freshness_and_reset( target, transition_events, ) - freshness_meta = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_for_target( - target, - closure_forecast_events, - ) + freshness_meta = _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_for_target( + target, + closure_forecast_events, ) freshness_status = freshness_meta[ "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status" @@ -11262,26 +10547,30 @@ def _apply_reset_reentry_rebuild_reentry_restore_freshness_and_reset( decayed_clearance_rate = freshness_meta[ "decayed_restored_rebuild_reentry_clearance_rate" ] - signal_mix = freshness_meta["recent_reset_reentry_rebuild_reentry_restore_signal_mix"] - control_updates = _apply_reset_reentry_rebuild_reentry_restore_freshness_reset_control( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, + signal_mix = freshness_meta[ + "recent_reset_reentry_rebuild_reentry_restore_signal_mix" + ] + control_updates = ( + _apply_reset_reentry_rebuild_reentry_restore_freshness_reset_control( + target, + freshness_meta=freshness_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + persistence_age_runs=persistence_age_runs, + persistence_score=persistence_score, + persistence_status=persistence_status, + persistence_reason=persistence_reason, + ) ) reset_status = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status" @@ -11289,9 +10578,15 @@ def _apply_reset_reentry_rebuild_reentry_restore_freshness_and_reset( reset_reason = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_reason" ] - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -11352,13 +10647,17 @@ def _apply_reset_reentry_rebuild_reentry_restore_freshness_and_reset( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - stale_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_hotspots( - resolution_targets, - mode="stale", + stale_hotspots = ( + _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_hotspots( + resolution_targets, + mode="stale", + ) ) - fresh_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_hotspots( - resolution_targets, - mode="fresh", + fresh_hotspots = ( + _closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_hotspots( + resolution_targets, + mode="fresh", + ) ) return { "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status": primary_target.get( @@ -11424,7 +10723,10 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_path_label( if reset_status != "none": return reset_status restore_status = ( - event.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") or "none" + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) + or "none" ) if restore_status != "none": return restore_status @@ -11481,7 +10783,10 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_for continue relevant_events.append(event) directions.append(direction) - if len(relevant_events) > CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_REFRESH_WINDOW_RUNS: + if ( + len(relevant_events) + > CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_REFRESH_WINDOW_RUNS + ): break if direction == "neutral": signal_strength = 0.0 @@ -11536,9 +10841,11 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_for earlier_majority, ) opposes_reset = ( - recent_restore_reset_side == "confirmation" and current_direction == "supporting-clearance" + recent_restore_reset_side == "confirmation" + and current_direction == "supporting-clearance" ) or ( - recent_restore_reset_side == "clearance" and current_direction == "supporting-confirmation" + recent_restore_reset_side == "clearance" + and current_direction == "supporting-confirmation" ) aligned_fresh_runs_after_reset = 0 if latest_reset_index is not None and latest_reset_index > 0: @@ -11573,7 +10880,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_for ) current_event_already_counted = any( event.get("generated_at", "") == "" - and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) == current_score + and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + == current_score and event.get("closure_forecast_reweight_direction", "neutral") == target.get("closure_forecast_reweight_direction", "neutral") for event in matching_events[: latest_reset_index or 0] @@ -11672,7 +10980,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_for "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status": rerestore_status, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason": rerestore_reason, "recent_reset_reentry_rebuild_reentry_restore_refresh_path": " -> ".join( - _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_path_label(event) + _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_path_label( + event + ) for event in matching_events if event ), @@ -11825,7 +11135,10 @@ def _reset_restore_follow_through() -> dict: "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": rerestore_reason, **_reset_restore_follow_through(), } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -11866,7 +11179,10 @@ def _reset_restore_follow_through() -> dict: "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": rerestore_reason, **_reset_restore_follow_through(), } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -11989,7 +11305,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_refresh_recovery_and_rerestore( rerestore_reason = "" refresh_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -12045,12 +11363,10 @@ def _apply_reset_reentry_rebuild_reentry_restore_refresh_recovery_and_rerestore( target, transition_events, ) - refresh_meta = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + refresh_meta = _closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_for_target( + target, + closure_forecast_events, + transition_history_meta, ) refresh_recovery_score = refresh_meta[ "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_score" @@ -12064,7 +11380,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_refresh_recovery_and_rerestore( rerestore_reason = refresh_meta[ "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason" ] - refresh_path = refresh_meta["recent_reset_reentry_rebuild_reentry_restore_refresh_path"] + refresh_path = refresh_meta[ + "recent_reset_reentry_rebuild_reentry_restore_refresh_path" + ] control_updates = ( _apply_reset_reentry_rebuild_reentry_restore_refresh_rerestore_control( target, @@ -12090,9 +11408,15 @@ def _apply_reset_reentry_rebuild_reentry_restore_refresh_recovery_and_rerestore( restore_churn_reason=restore_churn_reason, ) ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -12246,7 +11570,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_ ) if side != "none": return side - return _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event(event) + return _closure_forecast_reset_reentry_rebuild_reentry_restore_side_from_event( + event + ) def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_path_label( @@ -12294,7 +11620,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc relevant_events = [ event for event in matching_events - if _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + if _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event + ) != "none" ] current_side = ( @@ -12306,8 +11634,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc ) persistence_age_runs = 0 for event in matching_events: - event_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + event_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event ) if event_side != current_side or event_side == "none": break @@ -12317,16 +11645,23 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc weight_sum = 0.0 directions: list[str] = [] for index, event in enumerate( - relevant_events[:CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_WINDOW_RUNS] + relevant_events[ + :CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_WINDOW_RUNS + ] ): weight = (1.0, 0.8, 0.6, 0.4)[ - min(index, CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_WINDOW_RUNS - 1) + min( + index, + CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_WINDOW_RUNS - 1, + ) ] - event_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + event_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event ) sign = 1.0 if event_side == "confirmation" else -1.0 - directions.append("supporting-confirmation" if sign > 0 else "supporting-clearance") + directions.append( + "supporting-confirmation" if sign > 0 else "supporting-clearance" + ) magnitude = 0.0 if event.get( "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", @@ -12344,10 +11679,12 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc "rerestoring-clearance-rebuild-reentry", }: magnitude += 0.10 - momentum_status = event.get("closure_forecast_momentum_status", "insufficient-data") - if (event_side == "confirmation" and momentum_status == "sustained-confirmation") or ( - event_side == "clearance" and momentum_status == "sustained-clearance" - ): + momentum_status = event.get( + "closure_forecast_momentum_status", "insufficient-data" + ) + if ( + event_side == "confirmation" and momentum_status == "sustained-confirmation" + ) or (event_side == "clearance" and momentum_status == "sustained-clearance"): magnitude += 0.10 stability_status = event.get("closure_forecast_stability_status", "watch") if stability_status == "stable": @@ -12380,7 +11717,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc lower=-0.95, upper=0.95, ) - current_momentum_status = target.get("closure_forecast_momentum_status", "insufficient-data") + current_momentum_status = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) current_stability_status = target.get("closure_forecast_stability_status", "watch") current_freshness_status = target.get( "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", @@ -12437,9 +11776,17 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc and current_stability_status != "oscillating" ): persistence_status = "sustained-clearance-rebuild-reentry-rerestore" - elif current_side == "confirmation" and persistence_age_runs >= 2 and persistence_score > 0: + elif ( + current_side == "confirmation" + and persistence_age_runs >= 2 + and persistence_score > 0 + ): persistence_status = "holding-confirmation-rebuild-reentry-rerestore" - elif current_side == "clearance" and persistence_age_runs >= 2 and persistence_score < 0: + elif ( + current_side == "clearance" + and persistence_age_runs >= 2 + and persistence_score < 0 + ): persistence_status = "holding-clearance-rebuild-reentry-rerestore" else: persistence_status = "none" @@ -12467,7 +11814,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_status": persistence_status, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistence_reason": persistence_reason, "recent_reset_reentry_rebuild_reentry_restore_rerestore_persistence_path": " -> ".join( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_path_label(event) + _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_path_label( + event + ) for event in matching_events if event ), @@ -12486,11 +11835,15 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_ relevant_events = [ event for event in matching_events - if _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + if _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event + ) != "none" ] side_path = [ - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event + ) for event in relevant_events ] current_side = side_path[0] if side_path else "none" @@ -12502,13 +11855,17 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_ else: flip_count = _class_direction_flip_count( [ - "supporting-confirmation" if side == "confirmation" else "supporting-clearance" + "supporting-confirmation" + if side == "confirmation" + else "supporting-clearance" for side in side_path ] ) churn_score = float(flip_count) * 0.20 stability_status = target.get("closure_forecast_stability_status", "watch") - momentum_status = target.get("closure_forecast_momentum_status", "insufficient-data") + momentum_status = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) if stability_status == "oscillating": churn_score += 0.15 if momentum_status == "reversing": @@ -12523,7 +11880,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_ for event in relevant_events ] if any( - previous == "fresh" and current in {"mixed-age", "stale", "insufficient-data"} + previous == "fresh" + and current in {"mixed-age", "stale", "insufficient-data"} for previous, current in zip(freshness_path, freshness_path[1:]) ): churn_score += 0.10 @@ -12560,9 +11918,7 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_ churn_reason = "Re-restored rebuilt re-entry is flipping enough that stronger posture should be softened quickly." elif churn_score >= 0.20: churn_status = "watch" - churn_reason = ( - "Re-restored rebuilt re-entry is wobbling and may lose its stronger posture soon." - ) + churn_reason = "Re-restored rebuilt re-entry is wobbling and may lose its stronger posture soon." else: churn_status = "none" churn_reason = "" @@ -12572,7 +11928,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_ "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status": churn_status, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_reason": churn_reason, "recent_reset_reentry_rebuild_reentry_restore_rerestore_churn_path": " -> ".join( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_path_label(event) + _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_path_label( + event + ) for event in matching_events if event ), @@ -12621,10 +11979,8 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_persistence_and_churn ) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) recent_pending_status = transition_history_meta.get("recent_pending_status", "none") - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status( - rerestore_status - ) + current_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status( + rerestore_status ) if current_side == "none": current_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_persistence_status( @@ -12882,9 +12238,7 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_persistenc f"Re-restored posture is holding most cleanly around {hotspot.get('label', 'recent hotspots')}, " "so those classes are closest to keeping the stronger restored posture safely." ) - return ( - "No re-restored rebuilt re-entry posture is active enough yet to judge whether it can hold." - ) + return "No re-restored rebuilt re-entry posture is active enough yet to judge whether it can hold." def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_summary( @@ -12977,7 +12331,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_persistence_and_churn "", ) closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -13010,12 +12366,10 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_persistence_and_churn closure_forecast_events, transition_history_meta, ) - churn_meta = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + churn_meta = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_for_target( + target, + closure_forecast_events, + transition_history_meta, ) persistence_age_runs = persistence_meta[ "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_age_runs" @@ -13063,9 +12417,15 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_persistence_and_churn rerestore_status=rerestore_status, rerestore_reason=rerestore_reason, ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -13240,7 +12600,8 @@ def _reset_reentry_rebuild_reentry_restore_rerestore_event_is_clearance_like( } or event.get("closure_forecast_hysteresis_status", "none") in {"pending-clearance", "confirmed-clearance"} - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} ) @@ -13248,8 +12609,12 @@ def _reset_reentry_rebuild_reentry_restore_rerestore_event_has_evidence( event: dict, ) -> bool: return ( - _reset_reentry_rebuild_reentry_restore_rerestore_event_is_confirmation_like(event) - or _reset_reentry_rebuild_reentry_restore_rerestore_event_is_clearance_like(event) + _reset_reentry_rebuild_reentry_restore_rerestore_event_is_confirmation_like( + event + ) + or _reset_reentry_rebuild_reentry_restore_rerestore_event_is_clearance_like( + event + ) or event.get( "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_churn_status", "none", @@ -13304,11 +12669,15 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_ ) -> dict: class_key = _target_class_key(target) class_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key + event + for event in closure_forecast_events + if event.get("class_key") == class_key ] relevant_events: list[dict] = [] for event in class_events: - if not _reset_reentry_rebuild_reentry_restore_rerestore_event_has_evidence(event): + if not _reset_reentry_rebuild_reentry_restore_rerestore_event_has_evidence( + event + ): continue relevant_events.append(event) if len(relevant_events) >= HISTORY_WINDOW_RUNS: @@ -13325,29 +12694,32 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_ ) ) if current_side == "none": - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", - "none", - ) + current_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", + "none", ) ) for index, event in enumerate(relevant_events): weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_rerestore_evidence_count += weight - event_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + event_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event ) if ( - index < CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_FRESHNESS_WINDOW_RUNS + index + < CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_FRESHNESS_WINDOW_RUNS and event_side == current_side ): recent_rerestore_weight += weight - if _reset_reentry_rebuild_reentry_restore_rerestore_event_is_confirmation_like(event): + if _reset_reentry_rebuild_reentry_restore_rerestore_event_is_confirmation_like( + event + ): weighted_confirmation_like += weight - if _reset_reentry_rebuild_reentry_restore_rerestore_event_is_clearance_like(event): + if _reset_reentry_rebuild_reentry_restore_rerestore_event_is_clearance_like( + event + ): weighted_clearance_like += weight recent_window_weight_share = recent_rerestore_weight / max( @@ -13394,7 +12766,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_ recent_window_weight_share, ), "has_fresh_aligned_recent_evidence": any( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event(event) + _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( + event + ) == current_side and _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_event( event @@ -13452,10 +12826,8 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_reset_contr persistence_status ) if current_side == "none": - current_side = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status( - rerestore_status - ) + current_side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status( + rerestore_status ) local_noise = _target_specific_normalization_noise(target, transition_history_meta) recent_pending_status = transition_history_meta.get("recent_pending_status", "none") @@ -13520,8 +12892,9 @@ def _restore_weaker_pending_posture( } if current_side == "confirmation" and freshness_status == "mixed-age": - if persistence_status == "sustained-confirmation-rebuild-reentry-rerestore" and ( - churn_status != "churn" or has_fresh_aligned_recent_evidence + if ( + persistence_status == "sustained-confirmation-rebuild-reentry-rerestore" + and (churn_status != "churn" or has_fresh_aligned_recent_evidence) ): softened_reason = "Rerestored confirmation-side rebuilt re-entry is still visible, but it is aging and has been stepped down from sustained strength." softened_outcome = closure_likely_outcome @@ -13842,7 +13215,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_ if freshness_status == "stale": return f"{label} is leaning on older rerestored rebuilt re-entry strength more than fresh runs, so stronger rerestored posture should not keep carrying forward on memory alone." if fresh_reset_reentry_rebuild_reentry_restore_rerestore_signal_hotspots: - hotspot = fresh_reset_reentry_rebuild_reentry_restore_rerestore_signal_hotspots[0] + hotspot = fresh_reset_reentry_rebuild_reentry_restore_rerestore_signal_hotspots[ + 0 + ] return ( f"Fresh rerestored rebuilt re-entry evidence is strongest around {hotspot.get('label', 'recent hotspots')}, " "so those classes can keep stronger rerestored posture more safely than older carry-forward." @@ -13904,7 +13279,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_summ "so those classes should reset rerestored carry-forward instead of relying on older follow-through." ) if fresh_reset_reentry_rebuild_reentry_restore_rerestore_signal_hotspots: - hotspot = fresh_reset_reentry_rebuild_reentry_restore_rerestore_signal_hotspots[0] + hotspot = fresh_reset_reentry_rebuild_reentry_restore_rerestore_signal_hotspots[ + 0 + ] return ( f"Fresh rerestored rebuilt re-entry follow-through is strongest around {hotspot.get('label', 'recent hotspots')}, " "so those classes can preserve rerestored posture longer than aging carry-forward elsewhere." @@ -13956,7 +13333,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_and_reset( reset_status = "none" reset_reason = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -14030,29 +13409,27 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_and_reset( signal_mix = freshness_meta[ "recent_reset_reentry_rebuild_reentry_restore_rerestore_signal_mix" ] - control_updates = ( - _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_reset_control( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - ) + control_updates = _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_reset_control( + target, + freshness_meta=freshness_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + persistence_age_runs=persistence_age_runs, + persistence_score=persistence_score, + persistence_status=persistence_status, + persistence_reason=persistence_reason, ) reset_status = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status" @@ -14060,9 +13437,15 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_and_reset( reset_reason = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_reason" ] - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] transition_status = control_updates["class_reweight_transition_status"] transition_reason = control_updates["class_reweight_transition_reason"] resolution_status = control_updates["class_transition_resolution_status"] @@ -14131,17 +13514,13 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_and_reset( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - stale_hotspots = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_hotspots( - resolution_targets, - mode="stale", - ) + stale_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_hotspots( + resolution_targets, + mode="stale", ) - fresh_hotspots = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_hotspots( - resolution_targets, - mode="fresh", - ) + fresh_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_hotspots( + resolution_targets, + mode="fresh", ) return { "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status": primary_target.get( @@ -14176,26 +13555,6 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_freshness_and_reset( } -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( - status: str, -) -> str: - return _resolve_side( - status, - "pending-confirmation-rebuild-reentry-rererestore", - "rererestored-confirmation-rebuild-reentry", - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status( - status: str, -) -> str: - return _resolve_side( - status, - "recovering-confirmation-rebuild-reentry-rerestore-reset", - "rererestoring-confirmation-rebuild-reentry", - ) - - def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_path_label( event: dict, ) -> str: @@ -14314,7 +13673,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_re weight = (1.0, 0.8, 0.6, 0.4)[ min( len(relevant_events) - 1, - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_REFRESH_WINDOW_RUNS - 1, + CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERESTORE_REFRESH_WINDOW_RUNS + - 1, ) ] weighted_total += sign * signal_strength * freshness_factor * weight @@ -14334,7 +13694,9 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_re "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status", "insufficient-data", ) - current_momentum = target.get("closure_forecast_momentum_status", "insufficient-data") + current_momentum = target.get( + "closure_forecast_momentum_status", "insufficient-data" + ) current_stability = target.get("closure_forecast_stability_status", "watch") earlier_majority = _closure_forecast_direction_majority(directions[1:]) local_noise = _target_specific_normalization_noise(target, transition_history_meta) @@ -14382,7 +13744,8 @@ def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_re ) current_event_already_counted = any( event.get("generated_at", "") == "" - and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) == current_score + and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + == current_score and event.get("closure_forecast_reweight_direction", "neutral") == target.get("closure_forecast_reweight_direction", "neutral") for event in matching_events[: latest_reset_index or 0] @@ -14530,7 +13893,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_rererestore_c "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reason", "", ) - recent_rerestore_reset_side = refresh_meta.get("recent_rerestore_reset_side", "none") + recent_rerestore_reset_side = refresh_meta.get( + "recent_rerestore_reset_side", "none" + ) current_freshness = target.get( "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status", "insufficient-data", @@ -14646,7 +14011,10 @@ def _reset_rerestore_follow_through() -> dict: "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason": rererestore_reason, **_reset_rerestore_follow_through(), } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -14691,7 +14059,10 @@ def _reset_rerestore_follow_through() -> dict: "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reason": rererestore_reason, **_reset_rerestore_follow_through(), } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -14818,7 +14189,9 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_and_ rererestore_reason = "" refresh_path = "" closure_likely_outcome = target.get("transition_closure_likely_outcome", "none") - closure_hysteresis_status = target.get("closure_forecast_hysteresis_status", "none") + closure_hysteresis_status = target.get( + "closure_forecast_hysteresis_status", "none" + ) closure_hysteresis_reason = target.get("closure_forecast_hysteresis_reason", "") transition_status = target.get("class_reweight_transition_status", "none") transition_reason = target.get("class_reweight_transition_reason", "") @@ -14902,39 +14275,43 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_and_ refresh_path = refresh_meta[ "recent_reset_reentry_rebuild_reentry_restore_rerestore_refresh_path" ] - control_updates = ( - _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_rererestore_control( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rerestore_age_runs=rerestore_age_runs, - rerestore_persistence_score=rerestore_persistence_score, - rerestore_persistence_status=rerestore_persistence_status, - rerestore_persistence_reason=rerestore_persistence_reason, - rerestore_churn_score=rerestore_churn_score, - rerestore_churn_status=rerestore_churn_status, - rerestore_churn_reason=rerestore_churn_reason, - ) - ) - closure_likely_outcome = control_updates["transition_closure_likely_outcome"] - closure_hysteresis_status = control_updates["closure_forecast_hysteresis_status"] - closure_hysteresis_reason = control_updates["closure_forecast_hysteresis_reason"] - transition_status = control_updates["class_reweight_transition_status"] - transition_reason = control_updates["class_reweight_transition_reason"] - resolution_status = control_updates["class_transition_resolution_status"] + control_updates = _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_rererestore_control( + target, + refresh_meta=refresh_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + rerestore_age_runs=rerestore_age_runs, + rerestore_persistence_score=rerestore_persistence_score, + rerestore_persistence_status=rerestore_persistence_status, + rerestore_persistence_reason=rerestore_persistence_reason, + rerestore_churn_score=rerestore_churn_score, + rerestore_churn_status=rerestore_churn_status, + rerestore_churn_reason=rerestore_churn_reason, + ) + closure_likely_outcome = control_updates[ + "transition_closure_likely_outcome" + ] + closure_hysteresis_status = control_updates[ + "closure_forecast_hysteresis_status" + ] + closure_hysteresis_reason = control_updates[ + "closure_forecast_hysteresis_reason" + ] + transition_status = control_updates["class_reweight_transition_status"] + transition_reason = control_updates["class_reweight_transition_reason"] + resolution_status = control_updates["class_transition_resolution_status"] resolution_reason = control_updates["class_transition_resolution_reason"] reentry_status = control_updates[ "closure_forecast_reset_reentry_rebuild_reentry_status" @@ -15009,17 +14386,13 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_and_ resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - recovering_confirmation_hotspots = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_hotspots( - resolution_targets, - mode="confirmation", - ) + recovering_confirmation_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_hotspots( + resolution_targets, + mode="confirmation", ) - recovering_clearance_hotspots = ( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_hotspots( - resolution_targets, - mode="clearance", - ) + recovering_clearance_hotspots = _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_hotspots( + resolution_targets, + mode="clearance", ) return { "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_score": primary_target.get( @@ -15054,1940 +14427,628 @@ def _apply_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_and_ } -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( - status: str, -) -> str: - return _resolve_side( - status, - "just-rererestored", - "holding-confirmation-rebuild-reentry-rererestore", - "sustained-confirmation-rebuild-reentry-rererestore", - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event( - event: dict, -) -> str: - side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", - "none", - ) - ) - if side != "none": - return side - side = _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", - "none", - ) - ) - if side != "none": - return side - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", - "none", - ) - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label( - event: dict, -) -> str: - persistence_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", - "none", - ) - or "none" - ) - if persistence_status != "none": - return persistence_status - churn_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status", - "none", - ) - or "none" - ) - if churn_status != "none": - return churn_status - rererestore_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", - "none", - ) - or "none" - ) - if rererestore_status != "none": - return rererestore_status - refresh_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", - "none", - ) - or "none" - ) - if refresh_status != "none": - return refresh_status - rerestore_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", - "none", - ) - or "none" - ) - if rerestore_status != "none": - return rerestore_status - rerestore_reset_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status", - "none", - ) - or "none" +def _class_closure_forecast_events( + history: list[dict], + *, + current_primary_target: dict, + current_generated_at: str, +) -> list[dict]: + return _class_closure_forecast_events_helper( + history, + current_primary_target=current_primary_target, + current_generated_at=current_generated_at, + queue_identity=_queue_identity, + target_class_key=_target_class_key, + target_label=_target_label, + history_window_runs=HISTORY_WINDOW_RUNS, ) - if rerestore_reset_status != "none": - return rerestore_reset_status - likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" - if likely_outcome != "none": - return likely_outcome - return "hold" -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, +def _target_closure_forecast_history( + target: dict, closure_forecast_events: list[dict] ) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target_helper( + return _target_closure_forecast_history_helper( target, closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label, + target_class_key=_target_class_key, + closure_forecast_signal_from_event=_closure_forecast_signal_from_event, + normalized_closure_forecast_direction=_normalized_closure_forecast_direction, + class_direction_flip_count=_class_direction_flip_count, closure_forecast_direction_majority=_closure_forecast_direction_majority, closure_forecast_direction_reversing=_closure_forecast_direction_reversing, clamp_round=_clamp_round, - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, + class_closure_forecast_transition_window_runs=CLASS_CLOSURE_FORECAST_TRANSITION_WINDOW_RUNS, ) -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label, - class_direction_flip_count=_class_direction_flip_count, - target_specific_normalization_noise=_target_specific_normalization_noise, - clamp_round=_clamp_round, - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, +def _closure_forecast_signal_from_event(event: dict) -> float: + score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + direction = _normalized_closure_forecast_direction( + event.get("closure_forecast_reweight_direction", "neutral"), + score, ) + if direction == "supporting-confirmation": + return abs(score) if abs(score) >= 0.05 else 0.05 + if direction == "supporting-clearance": + return -abs(score) if abs(score) >= 0.05 else -0.05 + return _clamp_round(score, lower=-0.19, upper=0.19) -def _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control( +def _apply_closure_forecast_hysteresis_control( target: dict, *, - persistence_meta: dict, - churn_meta: dict, + history_meta: dict, transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, + trust_policy: str, + trust_policy_reason: str, transition_status: str, transition_reason: str, resolution_status: str, resolution_reason: str, - reentry_status: str, - reentry_reason: str, - restore_status: str, - restore_reason: str, - rerestore_status: str, - rerestore_reason: str, - rererestore_status: str, - rererestore_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control_helper( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status - ), - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary( - primary_target: dict, - just_rererestored_rebuild_reentry_hotspots: list[dict], - holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary_helper( - primary_target, - just_rererestored_rebuild_reentry_hotspots, - holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary( - primary_target: dict, - reset_reentry_rebuild_reentry_restore_rererestore_churn_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary_helper( - primary_target, - reset_reentry_rebuild_reentry_restore_rererestore_churn_hotspots, - target_label=_target_label, + pending_debt_status: str, + pending_debt_reason: str, + policy_debt_status: str, + policy_debt_reason: str, + class_normalization_status: str, + class_normalization_reason: str, + closure_likely_outcome: str, +) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: + momentum_status = history_meta.get( + "closure_forecast_momentum_status", "insufficient-data" ) + stability_status = history_meta.get("closure_forecast_stability_status", "watch") + direction = target.get("closure_forecast_reweight_direction", "neutral") + freshness_status = target.get("pending_debt_freshness_status", "insufficient-data") + local_noise = _target_specific_normalization_noise(target, transition_history_meta) + transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) + recent_pending_status = transition_history_meta.get("recent_pending_status", "none") + reweight_effect = target.get("closure_forecast_reweight_effect", "none") + if local_noise and direction == "supporting-confirmation": + blocked_reason = ( + "Local target instability is preventing positive forecast strengthening." + ) + if closure_likely_outcome == "confirm-soon": + closure_likely_outcome = "hold" + return ( + "blocked", + blocked_reason, + closure_likely_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) -def _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_helper( - resolution_targets, - history, - current_generated_at=current_generated_at, - confidence_calibration=confidence_calibration, - recommendation_bucket=_recommendation_bucket, - class_closure_forecast_events=_class_closure_forecast_events, - class_transition_events=_class_transition_events, - target_class_transition_history=_target_class_transition_history, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target - ), - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control=( - _apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary - ), - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs=( - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS - ), - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target( - target: dict, - closure_forecast_events: list[dict], -) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target_helper( - target, - closure_forecast_events, - target_class_key=_target_class_key, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event - ), - closure_forecast_freshness_status=_closure_forecast_freshness_status, - class_memory_recency_weights=CLASS_MEMORY_RECENCY_WEIGHTS, - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs=( - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS - ), - history_window_runs=HISTORY_WINDOW_RUNS, - ) - - -def _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control( - target: dict, - *, - freshness_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reentry_status: str, - reentry_reason: str, - restore_status: str, - restore_reason: str, - rerestore_status: str, - rerestore_reason: str, - rererestore_status: str, - rererestore_reason: str, - persistence_age_runs: int, - persistence_score: float, - persistence_status: str, - persistence_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control_helper( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status=( - _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status - ), - target_specific_normalization_noise=_target_specific_normalization_noise, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary( - primary_target: dict, - stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[dict], - fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary_helper( - primary_target, - stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots, - fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary( - primary_target: dict, - stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[dict], - fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary_helper( - primary_target, - stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots, - fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots, - target_label=_target_label, - ) - - -def _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset_helper( - resolution_targets, - history, - current_generated_at=current_generated_at, - confidence_calibration=confidence_calibration, - recommendation_bucket=_recommendation_bucket, - class_closure_forecast_events=_class_closure_forecast_events, - class_transition_events=_class_transition_events, - target_class_transition_history=_target_class_transition_history, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target, - apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control=_apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary, - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs=( - CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS - ), - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label( - event: dict, -) -> str: - rerererestore_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status", - "none", - ) - or "none" - ) - if rerererestore_status != "none": - return rerererestore_status - refresh_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status", - "none", - ) - or "none" - ) - if refresh_status != "none": - return refresh_status - rererestore_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", - "none", - ) - or "none" - ) - if rererestore_status != "none": - return rererestore_status - rererestore_reset_status = ( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_status", - "none", - ) - or "none" - ) - if rererestore_reset_status != "none": - return rererestore_reset_status - likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" - if likely_outcome != "none": - return likely_outcome - return "hold" - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=_closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label, - class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, - ) - - -def _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( - target: dict, - *, - refresh_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reentry_status: str, - reentry_reason: str, - restore_status: str, - restore_reason: str, - rerestore_status: str, - rerestore_reason: str, - rererestore_status: str, - rererestore_reason: str, - rererestore_age_runs: int, - rererestore_persistence_score: float, - rererestore_persistence_status: str, - rererestore_persistence_reason: str, - rererestore_churn_score: float, - rererestore_churn_status: str, - rererestore_churn_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control_helper( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - rererestore_age_runs=rererestore_age_runs, - rererestore_persistence_score=rererestore_persistence_score, - rererestore_persistence_status=rererestore_persistence_status, - rererestore_persistence_reason=rererestore_persistence_reason, - rererestore_churn_score=rererestore_churn_score, - rererestore_churn_status=rererestore_churn_status, - rererestore_churn_reason=rererestore_churn_reason, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and_rerererestore( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and_rerererestore_helper( - resolution_targets, - history, - current_generated_at=current_generated_at, - confidence_calibration=confidence_calibration, - recommendation_bucket=_recommendation_bucket, - class_closure_forecast_events=_class_closure_forecast_events, - class_transition_events=_class_transition_events, - target_class_transition_history=_target_class_transition_history, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target, - apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control=_apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary, - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary=_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary, - class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_text( - text: str, -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_text_helper( - text - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target=_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target, - ) - - -def _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( - target: dict, - *, - persistence_meta: dict, - churn_meta: dict, - transition_history_meta: dict, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - reentry_status: str, - reentry_reason: str, - restore_status: str, - restore_reason: str, - rerestore_status: str, - rerestore_reason: str, - rererestore_status: str, - rererestore_reason: str, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control_helper( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control=_apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary( - primary_target: dict, - just_rerererestored_rebuild_reentry_hotspots: list[dict], - holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary_helper( - primary_target, - just_rerererestored_rebuild_reentry_hotspots, - holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary( - primary_target: dict, - reset_reentry_rebuild_reentry_restore_rerererestore_churn_hotspots: list[dict], -) -> str: - return _closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary_helper( - primary_target, - reset_reentry_rebuild_reentry_restore_rerererestore_churn_hotspots, - target_label=_target_label, - ) - - -def _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn( - resolution_targets: list[dict], - history: list[dict], - *, - current_generated_at: str, - confidence_calibration: dict, -) -> dict: - return _apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_helper( - resolution_targets, - history, - current_generated_at=current_generated_at, - confidence_calibration=confidence_calibration, - recommendation_bucket=_recommendation_bucket, - class_closure_forecast_events=_class_closure_forecast_events, - class_transition_events=_class_transition_events, - target_class_transition_history=_target_class_transition_history, - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target=_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target, - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target=_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target, - apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control=_apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control, - target_class_key=_target_class_key, - target_label=_target_label, - class_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERERESTORE_WINDOW_RUNS, - ) - - -def _class_closure_forecast_events( - history: list[dict], - *, - current_primary_target: dict, - current_generated_at: str, -) -> list[dict]: - return _class_closure_forecast_events_helper( - history, - current_primary_target=current_primary_target, - current_generated_at=current_generated_at, - queue_identity=_queue_identity, - target_class_key=_target_class_key, - target_label=_target_label, - history_window_runs=HISTORY_WINDOW_RUNS, - ) - - -def _target_closure_forecast_history(target: dict, closure_forecast_events: list[dict]) -> dict: - return _target_closure_forecast_history_helper( - target, - closure_forecast_events, - target_class_key=_target_class_key, - closure_forecast_signal_from_event=_closure_forecast_signal_from_event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - class_direction_flip_count=_class_direction_flip_count, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - clamp_round=_clamp_round, - class_closure_forecast_transition_window_runs=CLASS_CLOSURE_FORECAST_TRANSITION_WINDOW_RUNS, - ) - - -def _closure_forecast_freshness_for_target( - target: dict, closure_forecast_events: list[dict] -) -> dict: - return _closure_forecast_freshness_for_target_helper( - target, - closure_forecast_events, - target_class_key=_target_class_key, - closure_forecast_event_has_evidence=_closure_forecast_event_has_evidence, - closure_forecast_event_signal_label=_closure_forecast_event_signal_label, - closure_forecast_event_is_confirmation_like=_closure_forecast_event_is_confirmation_like, - closure_forecast_event_is_clearance_like=_closure_forecast_event_is_clearance_like, - class_memory_recency_weights=CLASS_MEMORY_RECENCY_WEIGHTS, - history_window_runs=HISTORY_WINDOW_RUNS, - class_closure_forecast_freshness_window_runs=CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS, - freshness_status=_closure_forecast_freshness_status, - freshness_reason=_closure_forecast_freshness_reason, - recent_signal_mix=_recent_closure_forecast_signal_mix, - ) - - -def _closure_forecast_event_has_evidence(event: dict) -> bool: - return _closure_forecast_event_has_evidence_helper( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ) - - -def _closure_forecast_event_is_confirmation_like(event: dict) -> bool: - return _closure_forecast_event_is_confirmation_like_helper( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ) - - -def _closure_forecast_event_is_clearance_like(event: dict) -> bool: - return _closure_forecast_event_is_clearance_like_helper( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ) - - -def _closure_forecast_event_signal_label(event: dict) -> str: - return _closure_forecast_event_signal_label_helper( - event, - closure_forecast_event_is_confirmation_like=_closure_forecast_event_is_confirmation_like, - closure_forecast_event_is_clearance_like=_closure_forecast_event_is_clearance_like, - ) - - -def _closure_forecast_reacquisition_freshness_for_target( - target: dict, - closure_forecast_events: list[dict], -) -> dict: - return _closure_forecast_reacquisition_freshness_for_target_helper( - target, - closure_forecast_events, - target_class_key=_target_class_key, - reacquisition_event_has_evidence=_reacquisition_event_has_evidence, - reacquisition_event_signal_label=_reacquisition_event_signal_label, - closure_forecast_reacquisition_side_from_status=_closure_forecast_reacquisition_side_from_status, - closure_forecast_reacquisition_side_from_event=_closure_forecast_reacquisition_side_from_event, - class_memory_recency_weights=CLASS_MEMORY_RECENCY_WEIGHTS, - history_window_runs=HISTORY_WINDOW_RUNS, - class_reacquisition_freshness_window_runs=CLASS_REACQUISITION_FRESHNESS_WINDOW_RUNS, - freshness_status=_closure_forecast_freshness_status, - freshness_reason=_closure_forecast_reacquisition_freshness_reason, - recent_signal_mix=_recent_reacquisition_signal_mix, - reacquisition_event_is_confirmation_like=_reacquisition_event_is_confirmation_like, - reacquisition_event_is_clearance_like=_reacquisition_event_is_clearance_like, - ) - - -def _reacquisition_event_has_evidence(event: dict) -> bool: - return _reacquisition_event_has_evidence_helper( - event, - reacquisition_event_is_confirmation_like=_reacquisition_event_is_confirmation_like, - reacquisition_event_is_clearance_like=_reacquisition_event_is_clearance_like, - ) - - -def _reacquisition_event_is_confirmation_like(event: dict) -> bool: - return _reacquisition_event_is_confirmation_like_helper(event) - - -def _reacquisition_event_is_clearance_like(event: dict) -> bool: - return _reacquisition_event_is_clearance_like_helper(event) - - -def _reacquisition_event_signal_label(event: dict) -> str: - return _reacquisition_event_signal_label_helper( - event, - reacquisition_event_is_confirmation_like=_reacquisition_event_is_confirmation_like, - reacquisition_event_is_clearance_like=_reacquisition_event_is_clearance_like, - ) - - -def _closure_forecast_reacquisition_freshness_reason( - freshness_status: str, - weighted_reacquisition_evidence_count: float, - recent_window_weight_share: float, - decayed_confirmation_rate: float, - decayed_clearance_rate: float, -) -> str: - return _closure_forecast_reacquisition_freshness_reason_helper( - freshness_status, - weighted_reacquisition_evidence_count, - recent_window_weight_share, - decayed_confirmation_rate, - decayed_clearance_rate, - class_reacquisition_freshness_window_runs=CLASS_REACQUISITION_FRESHNESS_WINDOW_RUNS, - ) - - -def _recent_reacquisition_signal_mix( - weighted_reacquisition_evidence_count: float, - weighted_confirmation_like: float, - weighted_clearance_like: float, - recent_window_weight_share: float, -) -> str: - return _recent_reacquisition_signal_mix_helper( - weighted_reacquisition_evidence_count, - weighted_confirmation_like, - weighted_clearance_like, - recent_window_weight_share, - ) - - -def _closure_forecast_freshness_status( - weighted_forecast_evidence_count: float, - recent_window_weight_share: float, -) -> str: - return _closure_forecast_freshness_status_helper( - weighted_forecast_evidence_count, - recent_window_weight_share, - ) - - -def _closure_forecast_freshness_reason( - freshness_status: str, - weighted_forecast_evidence_count: float, - recent_window_weight_share: float, - decayed_confirmation_rate: float, - decayed_clearance_rate: float, -) -> str: - return _closure_forecast_freshness_reason_helper( - freshness_status, - weighted_forecast_evidence_count, - recent_window_weight_share, - decayed_confirmation_rate, - decayed_clearance_rate, - class_closure_forecast_freshness_window_runs=CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS, - ) - - -def _recent_closure_forecast_signal_mix( - weighted_forecast_evidence_count: float, - weighted_confirmation_like: float, - weighted_clearance_like: float, - recent_window_weight_share: float, -) -> str: - return _recent_closure_forecast_signal_mix_helper( - weighted_forecast_evidence_count, - weighted_confirmation_like, - weighted_clearance_like, - recent_window_weight_share, - ) - - -def _closure_forecast_signal_from_event(event: dict) -> float: - score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) - direction = _normalized_closure_forecast_direction( - event.get("closure_forecast_reweight_direction", "neutral"), - score, - ) - if direction == "supporting-confirmation": - return abs(score) if abs(score) >= 0.05 else 0.05 - if direction == "supporting-clearance": - return -abs(score) if abs(score) >= 0.05 else -0.05 - return _clamp_round(score, lower=-0.19, upper=0.19) - - -def _normalized_closure_forecast_direction(direction: str, score: float) -> str: - if direction in {"supporting-confirmation", "supporting-clearance", "neutral"}: - return direction - if score >= 0.20: - return "supporting-confirmation" - if score <= -0.20: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_majority(directions: list[str]) -> str: - confirmation_count = sum( - 1 for direction in directions if direction == "supporting-confirmation" - ) - clearance_count = sum(1 for direction in directions if direction == "supporting-clearance") - if confirmation_count > clearance_count: - return "supporting-confirmation" - if clearance_count > confirmation_count: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_reversing(current_direction: str, earlier_majority: str) -> bool: - if current_direction == "neutral" or earlier_majority == "neutral": - return False - return current_direction != earlier_majority - - -def _apply_closure_forecast_hysteresis_control( - target: dict, - *, - history_meta: dict, - transition_history_meta: dict, - trust_policy: str, - trust_policy_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - pending_debt_status: str, - pending_debt_reason: str, - policy_debt_status: str, - policy_debt_reason: str, - class_normalization_status: str, - class_normalization_reason: str, - closure_likely_outcome: str, -) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: - momentum_status = history_meta.get("closure_forecast_momentum_status", "insufficient-data") - stability_status = history_meta.get("closure_forecast_stability_status", "watch") - direction = target.get("closure_forecast_reweight_direction", "neutral") - freshness_status = target.get("pending_debt_freshness_status", "insufficient-data") - local_noise = _target_specific_normalization_noise(target, transition_history_meta) - transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) - recent_pending_status = transition_history_meta.get("recent_pending_status", "none") - reweight_effect = target.get("closure_forecast_reweight_effect", "none") - - if local_noise and direction == "supporting-confirmation": - blocked_reason = "Local target instability is preventing positive forecast strengthening." - if closure_likely_outcome == "confirm-soon": - closure_likely_outcome = "hold" - return ( - "blocked", - blocked_reason, - closure_likely_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if ( - resolution_status == "cleared" - and reweight_effect == "clear-risk-strengthened" - and recent_pending_status in {"pending-support", "pending-caution"} - and (momentum_status != "sustained-clearance" or stability_status == "oscillating") - ): - pending_reason = "Clearance pressure is visible, but it has not stayed persistent enough to clear the pending state early." - return ( - "pending-clearance", - pending_reason, - "hold", - recent_pending_status, - pending_reason, - "none", - "", - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if resolution_status == "cleared" and reweight_effect == "clear-risk-strengthened": - confirmed_reason = "Fresh unresolved pending debt has stayed strong enough to keep the earlier clearance decision in place." - return ( - "confirmed-clearance", - confirmed_reason, - closure_likely_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if closure_likely_outcome == "confirm-soon": - if momentum_status == "sustained-confirmation" and stability_status != "oscillating": - return ( - "confirmed-confirmation", - "Fresh class follow-through has stayed strong enough to keep the stronger confirmation forecast in place.", - closure_likely_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - return ( - "pending-confirmation", - "The confirmation-leaning forecast is visible, but it has not stayed persistent enough to trust fully yet.", - "hold", - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if ( - closure_likely_outcome == "hold" - and direction == "supporting-confirmation" - and freshness_status == "fresh" - and momentum_status == "sustained-confirmation" - and stability_status == "stable" - and not local_noise - ): - return ( - "confirmed-confirmation", - "Fresh class follow-through has stayed strong enough to keep the stronger confirmation forecast in place.", - "confirm-soon", - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if closure_likely_outcome == "clear-risk": - if momentum_status == "sustained-clearance" and stability_status != "oscillating": - return ( - "confirmed-clearance", - "Fresh unresolved pending debt has stayed strong enough to keep the stronger clearance forecast in place.", - closure_likely_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - return ( - "pending-clearance", - "The clearance-leaning forecast is visible, but it has not stayed persistent enough to clear early yet.", - "hold", - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if closure_likely_outcome == "expire-risk": - if ( - momentum_status == "sustained-clearance" - and stability_status != "oscillating" - and transition_age_runs >= 3 - ): - return ( - "confirmed-clearance", - "Fresh unresolved pending debt has stayed strong long enough to keep expiry risk elevated.", - closure_likely_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - if momentum_status == "sustained-clearance" and stability_status != "oscillating": - return ( - "pending-clearance", - "Clearance pressure is visible, but expiry risk has not stayed stable enough to stay fully elevated yet.", - "clear-risk", - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - return ( - "pending-clearance", - "Expiry pressure is visible, but it has not stayed persistent enough to trust fully yet.", - "hold", - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - if momentum_status in {"reversing", "unstable"}: - softened_outcome = closure_likely_outcome - softened_reason = "Recent pending-resolution evidence is changing direction, so earlier forecast strength is being softened." - if closure_likely_outcome == "confirm-soon": - softened_outcome = "hold" - elif closure_likely_outcome == "expire-risk": - softened_outcome = "clear-risk" - elif closure_likely_outcome == "clear-risk": - softened_outcome = "hold" - return ( - "pending-confirmation" - if softened_outcome == "hold" and direction == "supporting-confirmation" - else "pending-clearance" - if softened_outcome in {"hold", "clear-risk"} and direction == "supporting-clearance" - else "none", - softened_reason, - softened_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - return ( - "none", - "", - closure_likely_outcome, - transition_status, - transition_reason, - resolution_status, - resolution_reason, - trust_policy, - trust_policy_reason, - pending_debt_status, - pending_debt_reason, - policy_debt_status, - policy_debt_reason, - class_normalization_status, - class_normalization_reason, - ) - - -def _apply_closure_forecast_decay_control( - target: dict, - *, - freshness_meta: dict, - transition_history_meta: dict, - trust_policy: str, - trust_policy_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - pending_debt_status: str, - pending_debt_reason: str, - policy_debt_status: str, - policy_debt_reason: str, - class_normalization_status: str, - class_normalization_reason: str, -) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: - return _apply_closure_forecast_decay_control_helper( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - trust_policy=trust_policy, - trust_policy_reason=trust_policy_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - pending_debt_status=pending_debt_status, - pending_debt_reason=pending_debt_reason, - policy_debt_status=policy_debt_status, - policy_debt_reason=policy_debt_reason, - class_normalization_status=class_normalization_status, - class_normalization_reason=class_normalization_reason, - target_specific_normalization_noise=_target_specific_normalization_noise, - ) - - -def _closure_forecast_refresh_recovery_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_refresh_recovery_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - target_class_key=_target_class_key, - closure_forecast_event_has_evidence=_closure_forecast_event_has_evidence, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - closure_forecast_refresh_signal_from_event=_closure_forecast_refresh_signal_from_event, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), - closure_forecast_direction_majority=_closure_forecast_direction_majority, - recent_closure_forecast_weakened_side=_recent_closure_forecast_weakened_side, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_refresh_path_label=_closure_forecast_refresh_path_label, - class_closure_forecast_refresh_window_runs=CLASS_CLOSURE_FORECAST_REFRESH_WINDOW_RUNS, - ) - - -def _closure_forecast_refresh_signal_from_event(event: dict) -> float: - return _closure_forecast_refresh_signal_from_event_helper( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ) - - -def _recent_closure_forecast_weakened_side(events: list[dict]) -> str: - return _recent_closure_forecast_weakened_side_helper(events) - - -def _closure_forecast_refresh_path_label(event: dict) -> str: - return _closure_forecast_refresh_path_label_helper( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ) - - -def _apply_closure_forecast_reacquisition_control( - target: dict, - *, - refresh_meta: dict, - transition_history_meta: dict, - trust_policy: str, - trust_policy_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - pending_debt_status: str, - pending_debt_reason: str, - policy_debt_status: str, - policy_debt_reason: str, - class_normalization_status: str, - class_normalization_reason: str, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, -) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: - return _apply_closure_forecast_reacquisition_control_helper( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - trust_policy=trust_policy, - trust_policy_reason=trust_policy_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - pending_debt_status=pending_debt_status, - pending_debt_reason=pending_debt_reason, - policy_debt_status=policy_debt_status, - policy_debt_reason=policy_debt_reason, - class_normalization_status=class_normalization_status, - class_normalization_reason=class_normalization_reason, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - ) - - -def _closure_forecast_momentum_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: - grouped: dict[str, dict] = {} - for target in resolution_targets: - class_key = _target_class_key(target) - if not class_key: - continue - current = { - "scope": "class", - "label": class_key, - "closure_forecast_momentum_score": target.get("closure_forecast_momentum_score", 0.0), - "closure_forecast_momentum_status": target.get( - "closure_forecast_momentum_status", "insufficient-data" - ), - "closure_forecast_stability_status": target.get( - "closure_forecast_stability_status", "watch" - ), - "recent_closure_forecast_path": target.get("recent_closure_forecast_path", ""), - } - existing = grouped.get(class_key) - if existing is None or abs(current["closure_forecast_momentum_score"]) > abs( - existing["closure_forecast_momentum_score"] - ): - grouped[class_key] = current - - hotspots = list(grouped.values()) - if mode == "confirmation": - hotspots = [ - item - for item in hotspots - if item.get("closure_forecast_momentum_status") == "sustained-confirmation" - ] - hotspots.sort( - key=lambda item: ( - -item.get("closure_forecast_momentum_score", 0.0), - item.get("label", ""), - ) - ) - elif mode == "clearance": - hotspots = [ - item - for item in hotspots - if item.get("closure_forecast_momentum_status") == "sustained-clearance" - ] - hotspots.sort( - key=lambda item: ( - item.get("closure_forecast_momentum_score", 0.0), - item.get("label", ""), - ) - ) - else: - hotspots = [ - item - for item in hotspots - if item.get("closure_forecast_stability_status") == "oscillating" - ] - hotspots.sort( - key=lambda item: ( - -abs(item.get("closure_forecast_momentum_score", 0.0)), - item.get("label", ""), - ) - ) - return hotspots[:5] - - -def _closure_forecast_momentum_summary( - primary_target: dict, - sustained_confirmation_hotspots: list[dict], - sustained_clearance_hotspots: list[dict], - oscillating_closure_forecast_hotspots: list[dict], -) -> str: - label = _target_label(primary_target) or "The current target" - status = primary_target.get("closure_forecast_momentum_status", "insufficient-data") - score = primary_target.get("closure_forecast_momentum_score", 0.0) - if status == "sustained-confirmation": - return f"Recent pending-resolution behavior around {label} has stayed strong long enough to keep the confirmation forecast credible ({score:.2f})." - if status == "sustained-clearance": - return f"Unresolved pending debt around {label} has stayed strong long enough to keep clearance or expiry risk elevated ({score:.2f})." - if status == "building": - return f"The closure forecast for {label} is trending in one direction, but it has not held long enough to lock in ({score:.2f})." - if status == "reversing": - return f"Recent pending-resolution evidence around {label} is changing direction, so earlier forecast strength is being softened ({score:.2f})." - if status == "unstable": - return f"Recent closure-forecast evidence around {label} is bouncing too much to strengthen safely right now ({score:.2f})." - if sustained_confirmation_hotspots: - hotspot = sustained_confirmation_hotspots[0] - return ( - f"Confirmation-leaning closure momentum is strongest around {hotspot.get('label', 'recent hotspots')}, " - "but the current target has not built enough persistence yet." - ) - if sustained_clearance_hotspots: - hotspot = sustained_clearance_hotspots[0] - return ( - f"Clearance-heavy closure momentum is strongest around {hotspot.get('label', 'recent hotspots')}, " - "so weaker pending states there should keep proving follow-through." - ) - if oscillating_closure_forecast_hotspots: - hotspot = oscillating_closure_forecast_hotspots[0] - return ( - f"Closure-forecast stability is weakest around {hotspot.get('label', 'recent hotspots')}, " - "so stronger forecast changes there should wait for persistence." + if ( + resolution_status == "cleared" + and reweight_effect == "clear-risk-strengthened" + and recent_pending_status in {"pending-support", "pending-caution"} + and ( + momentum_status != "sustained-clearance" + or stability_status == "oscillating" ) - return "Closure-forecast momentum is still too lightly exercised to say whether recent pending-resolution behavior is sustained or unstable." - - -def _closure_forecast_stability_summary( - primary_target: dict, - oscillating_closure_forecast_hotspots: list[dict], -) -> str: - label = _target_label(primary_target) or "The current target" - stability_status = primary_target.get("closure_forecast_stability_status", "watch") - recent_path = primary_target.get("recent_closure_forecast_path", "") - if stability_status == "oscillating": - return f"Closure forecasting for {label} is bouncing too much to strengthen safely right now: {recent_path or 'no stable path yet'}." - if stability_status == "watch": - return f"Closure forecasting for {label} is still settling and should be watched for one more stable stretch: {recent_path or 'signal is still building'}." - if recent_path: - return f"Closure forecasting for {label} is stable across the recent path: {recent_path}." - if oscillating_closure_forecast_hotspots: - hotspot = oscillating_closure_forecast_hotspots[0] + ): + pending_reason = "Clearance pressure is visible, but it has not stayed persistent enough to clear the pending state early." return ( - f"Closure-forecast stability is weakest around {hotspot.get('label', 'recent hotspots')}, " - "so stronger forecast shifts should wait there." + "pending-clearance", + pending_reason, + "hold", + recent_pending_status, + pending_reason, + "none", + "", + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, ) - return "Recent closure-forecast guidance is stable enough that no extra hysteresis warning is needed." - -def _closure_forecast_hysteresis_summary( - primary_target: dict, - sustained_confirmation_hotspots: list[dict], - sustained_clearance_hotspots: list[dict], -) -> str: - label = _target_label(primary_target) or "The current target" - status = primary_target.get("closure_forecast_hysteresis_status", "none") - reason = primary_target.get("closure_forecast_hysteresis_reason", "") - if status == "confirmed-confirmation": - return ( - reason - or f"Fresh class follow-through has stayed strong enough to keep the stronger confirmation forecast in place for {label}." - ) - if status == "confirmed-clearance": - return ( - reason - or f"Fresh unresolved pending debt has stayed strong enough to keep the stronger clearance forecast in place for {label}." - ) - if status == "pending-confirmation": - return ( - reason - or f"The confirmation-leaning forecast for {label} is visible but not yet persistent enough to trust fully." - ) - if status == "pending-clearance": - return ( - reason - or f"The clearance-leaning forecast for {label} is visible but not yet persistent enough to clear early." - ) - if status == "blocked": - return ( - reason - or f"Local target instability is preventing positive closure-forecast strengthening for {label}." - ) - if sustained_confirmation_hotspots: - hotspot = sustained_confirmation_hotspots[0] - return ( - f"Confirmation-side closure hysteresis is strongest around {hotspot.get('label', 'recent hotspots')}, " - "so those classes are closest to holding stronger confirmation forecasts safely." - ) - if sustained_clearance_hotspots: - hotspot = sustained_clearance_hotspots[0] + if resolution_status == "cleared" and reweight_effect == "clear-risk-strengthened": + confirmed_reason = "Fresh unresolved pending debt has stayed strong enough to keep the earlier clearance decision in place." return ( - f"Clearance-side closure hysteresis is strongest around {hotspot.get('label', 'recent hotspots')}, " - "so those classes can hold stronger clearance forecasts only when that pressure keeps persisting." + "confirmed-clearance", + confirmed_reason, + closure_likely_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, ) - return ( - "No closure-forecast hysteresis adjustment is changing the live pending forecast right now." - ) - - -def _closure_forecast_freshness_hotspots( - resolution_targets: list[dict], *, mode: str -) -> list[dict]: - return _closure_forecast_freshness_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - -def _closure_forecast_freshness_summary( - primary_target: dict, - stale_closure_forecast_hotspots: list[dict], - fresh_closure_forecast_signal_hotspots: list[dict], -) -> str: - label = _target_label(primary_target) or "The current target" - freshness_status = primary_target.get("closure_forecast_freshness_status", "insufficient-data") - if freshness_status == "fresh": - return ( - f"{label} still has recent closure-forecast evidence that is current enough to trust." - ) - if freshness_status == "mixed-age": - return f"{label} still has useful closure-forecast memory, but part of that signal is aging and should be weighted more cautiously." - if freshness_status == "stale": - return f"{label} is leaning on older closure-forecast momentum more than fresh runs, so stale class carry-forward should not dominate the current forecast." - if fresh_closure_forecast_signal_hotspots: - hotspot = fresh_closure_forecast_signal_hotspots[0] - return ( - f"Fresh closure-forecast evidence is strongest around {hotspot.get('label', 'recent hotspots')}, " - "so those classes deserve more trust than older forecast carry-forward." - ) - if stale_closure_forecast_hotspots: - hotspot = stale_closure_forecast_hotspots[0] + if closure_likely_outcome == "confirm-soon": + if ( + momentum_status == "sustained-confirmation" + and stability_status != "oscillating" + ): + return ( + "confirmed-confirmation", + "Fresh class follow-through has stayed strong enough to keep the stronger confirmation forecast in place.", + closure_likely_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) return ( - f"Older closure-forecast momentum is lingering most around {hotspot.get('label', 'recent hotspots')}, " - "so those classes should keep letting stale forecast strength decay." + "pending-confirmation", + "The confirmation-leaning forecast is visible, but it has not stayed persistent enough to trust fully yet.", + "hold", + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, ) - return "Closure-forecast memory is still too lightly exercised to say whether fresh or stale forecast evidence should lead the current posture." - -def _closure_forecast_decay_summary( - primary_target: dict, - fresh_closure_forecast_signal_hotspots: list[dict], - stale_closure_forecast_hotspots: list[dict], -) -> str: - label = _target_label(primary_target) or "The current target" - decay_status = primary_target.get("closure_forecast_decay_status", "none") - freshness_status = primary_target.get("closure_forecast_freshness_status", "insufficient-data") - confirmation_rate = primary_target.get("decayed_confirmation_forecast_rate", 0.0) - clearance_rate = primary_target.get("decayed_clearance_forecast_rate", 0.0) - if decay_status == "confirmation-decayed": - return f"Stronger confirmation wording for {label} was pulled back because the supporting closure-forecast memory is too old or too lightly refreshed." - if decay_status == "clearance-decayed": - return f"Stronger clearance wording for {label} was pulled back because fresh unresolved pending-debt support is no longer strong enough." - if decay_status == "blocked": - return f"Local target instability still overrides closure-forecast freshness for {label}, so forecast carry-forward should stay conservative." - if freshness_status == "fresh" and confirmation_rate >= clearance_rate: - return f"Fresh closure-forecast evidence for {label} is still reinforcing confirmation-side posture more than clearance pressure." - if freshness_status == "fresh": - return f"Fresh closure-forecast evidence for {label} is still reinforcing clearance pressure more than confirmation-side carry-forward." - if freshness_status == "stale": - return f"Older closure-forecast momentum is being down-weighted for {label}, so stale forecast strength should keep decaying instead of carrying forward indefinitely." - if fresh_closure_forecast_signal_hotspots: - hotspot = fresh_closure_forecast_signal_hotspots[0] + if ( + closure_likely_outcome == "hold" + and direction == "supporting-confirmation" + and freshness_status == "fresh" + and momentum_status == "sustained-confirmation" + and stability_status == "stable" + and not local_noise + ): return ( - f"Fresh closure-forecast reinforcement is strongest around {hotspot.get('label', 'recent hotspots')}, " - "so those classes are earning stronger live forecasting than older carry-forward." + "confirmed-confirmation", + "Fresh class follow-through has stayed strong enough to keep the stronger confirmation forecast in place.", + "confirm-soon", + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, ) - if stale_closure_forecast_hotspots: - hotspot = stale_closure_forecast_hotspots[0] + + if closure_likely_outcome == "clear-risk": + if ( + momentum_status == "sustained-clearance" + and stability_status != "oscillating" + ): + return ( + "confirmed-clearance", + "Fresh unresolved pending debt has stayed strong enough to keep the stronger clearance forecast in place.", + closure_likely_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) return ( - f"Stale closure-forecast carry-forward is strongest around {hotspot.get('label', 'recent hotspots')}, " - "so those older forecast patterns should keep decaying." + "pending-clearance", + "The clearance-leaning forecast is visible, but it has not stayed persistent enough to clear early yet.", + "hold", + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, ) - return ( - "No strong closure-forecast freshness trend is dominating the live hysteresis posture yet." - ) - - -def _closure_forecast_refresh_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: - return _closure_forecast_refresh_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) - - -def _closure_forecast_refresh_recovery_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_refresh_recovery_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reacquisition_summary( - primary_target: dict, - recovering_confirmation_hotspots: list[dict], - recovering_clearance_hotspots: list[dict], -) -> str: - return _closure_forecast_reacquisition_summary_helper( - primary_target, - recovering_confirmation_hotspots, - recovering_clearance_hotspots, - target_label=_target_label, - ) - - -def _closure_forecast_reacquisition_side_from_event(event: dict) -> str: - return _closure_forecast_reacquisition_side_from_event_helper(event) - - -def _closure_forecast_reacquisition_side_from_status(status: str) -> str: - return _closure_forecast_reacquisition_side_from_status_helper(status) - - -def _closure_forecast_reacquisition_path_label(event: dict) -> str: - return _closure_forecast_reacquisition_path_label_helper(event) - - -def _closure_forecast_reacquisition_persistence_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_reacquisition_persistence_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - target_class_key=_target_class_key, - closure_forecast_reacquisition_side_from_event=_closure_forecast_reacquisition_side_from_event, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), - closure_forecast_direction_majority=_closure_forecast_direction_majority, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reacquisition_path_label=_closure_forecast_reacquisition_path_label, - class_reacquisition_persistence_window_runs=CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS, - ) - - -def _closure_forecast_recovery_churn_for_target( - target: dict, - closure_forecast_events: list[dict], - transition_history_meta: dict, -) -> dict: - return _closure_forecast_recovery_churn_for_target_helper( - target, - closure_forecast_events, - transition_history_meta, - target_class_key=_target_class_key, - closure_forecast_reacquisition_side_from_event=_closure_forecast_reacquisition_side_from_event, - class_direction_flip_count=_class_direction_flip_count, - clamp_round=lambda value, lower, upper: _clamp_round(value, lower=lower, upper=upper), - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_reacquisition_path_label=_closure_forecast_reacquisition_path_label, - class_reacquisition_persistence_window_runs=CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS, - ) + if closure_likely_outcome == "expire-risk": + if ( + momentum_status == "sustained-clearance" + and stability_status != "oscillating" + and transition_age_runs >= 3 + ): + return ( + "confirmed-clearance", + "Fresh unresolved pending debt has stayed strong long enough to keep expiry risk elevated.", + closure_likely_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) + if ( + momentum_status == "sustained-clearance" + and stability_status != "oscillating" + ): + return ( + "pending-clearance", + "Clearance pressure is visible, but expiry risk has not stayed stable enough to stay fully elevated yet.", + "clear-risk", + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) + return ( + "pending-clearance", + "Expiry pressure is visible, but it has not stayed persistent enough to trust fully yet.", + "hold", + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) -def _apply_reacquisition_persistence_and_churn_control( - target: dict, - *, - persistence_meta: dict, - churn_meta: dict, - transition_history_meta: dict, - trust_policy: str, - trust_policy_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - pending_debt_status: str, - pending_debt_reason: str, - policy_debt_status: str, - policy_debt_reason: str, - class_normalization_status: str, - class_normalization_reason: str, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, -) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: - return _apply_reacquisition_persistence_and_churn_control_helper( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - trust_policy=trust_policy, - trust_policy_reason=trust_policy_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - pending_debt_status=pending_debt_status, - pending_debt_reason=pending_debt_reason, - policy_debt_status=policy_debt_status, - policy_debt_reason=policy_debt_reason, - class_normalization_status=class_normalization_status, - class_normalization_reason=class_normalization_reason, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - ) - + if momentum_status in {"reversing", "unstable"}: + softened_outcome = closure_likely_outcome + softened_reason = "Recent pending-resolution evidence is changing direction, so earlier forecast strength is being softened." + if closure_likely_outcome == "confirm-soon": + softened_outcome = "hold" + elif closure_likely_outcome == "expire-risk": + softened_outcome = "clear-risk" + elif closure_likely_outcome == "clear-risk": + softened_outcome = "hold" + return ( + "pending-confirmation" + if softened_outcome == "hold" and direction == "supporting-confirmation" + else "pending-clearance" + if softened_outcome in {"hold", "clear-risk"} + and direction == "supporting-clearance" + else "none", + softened_reason, + softened_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, + ) -def _apply_reacquisition_freshness_reset_control( - target: dict, - *, - freshness_meta: dict, - transition_history_meta: dict, - trust_policy: str, - trust_policy_reason: str, - transition_status: str, - transition_reason: str, - resolution_status: str, - resolution_reason: str, - pending_debt_status: str, - pending_debt_reason: str, - policy_debt_status: str, - policy_debt_reason: str, - class_normalization_status: str, - class_normalization_reason: str, - closure_likely_outcome: str, - closure_hysteresis_status: str, - closure_hysteresis_reason: str, - reacquisition_status: str, - reacquisition_reason: str, - persistence_age_runs: int, - persistence_score: float, - persistence_status: str, - persistence_reason: str, -) -> dict: - return _apply_reacquisition_freshness_reset_control_helper( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - trust_policy=trust_policy, - trust_policy_reason=trust_policy_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - pending_debt_status=pending_debt_status, - pending_debt_reason=pending_debt_reason, - policy_debt_status=policy_debt_status, - policy_debt_reason=policy_debt_reason, - class_normalization_status=class_normalization_status, - class_normalization_reason=class_normalization_reason, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - reacquisition_status=reacquisition_status, - reacquisition_reason=reacquisition_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - closure_forecast_reacquisition_side_from_status=_closure_forecast_reacquisition_side_from_status, - closure_forecast_reacquisition_side_from_event=_closure_forecast_reacquisition_side_from_event, - target_specific_normalization_noise=_target_specific_normalization_noise, + return ( + "none", + "", + closure_likely_outcome, + transition_status, + transition_reason, + resolution_status, + resolution_reason, + trust_policy, + trust_policy_reason, + pending_debt_status, + pending_debt_reason, + policy_debt_status, + policy_debt_reason, + class_normalization_status, + class_normalization_reason, ) -def _closure_forecast_reacquisition_hotspots( +def _closure_forecast_momentum_hotspots( resolution_targets: list[dict], *, mode: str ) -> list[dict]: - return _closure_forecast_reacquisition_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) + grouped: dict[str, dict] = {} + for target in resolution_targets: + class_key = _target_class_key(target) + if not class_key: + continue + current = { + "scope": "class", + "label": class_key, + "closure_forecast_momentum_score": target.get( + "closure_forecast_momentum_score", 0.0 + ), + "closure_forecast_momentum_status": target.get( + "closure_forecast_momentum_status", "insufficient-data" + ), + "closure_forecast_stability_status": target.get( + "closure_forecast_stability_status", "watch" + ), + "recent_closure_forecast_path": target.get( + "recent_closure_forecast_path", "" + ), + } + existing = grouped.get(class_key) + if existing is None or abs(current["closure_forecast_momentum_score"]) > abs( + existing["closure_forecast_momentum_score"] + ): + grouped[class_key] = current + + hotspots = list(grouped.values()) + if mode == "confirmation": + hotspots = [ + item + for item in hotspots + if item.get("closure_forecast_momentum_status") == "sustained-confirmation" + ] + hotspots.sort( + key=lambda item: ( + -item.get("closure_forecast_momentum_score", 0.0), + item.get("label", ""), + ) + ) + elif mode == "clearance": + hotspots = [ + item + for item in hotspots + if item.get("closure_forecast_momentum_status") == "sustained-clearance" + ] + hotspots.sort( + key=lambda item: ( + item.get("closure_forecast_momentum_score", 0.0), + item.get("label", ""), + ) + ) + else: + hotspots = [ + item + for item in hotspots + if item.get("closure_forecast_stability_status") == "oscillating" + ] + hotspots.sort( + key=lambda item: ( + -abs(item.get("closure_forecast_momentum_score", 0.0)), + item.get("label", ""), + ) + ) + return hotspots[:5] -def _closure_forecast_reacquisition_freshness_hotspots( - resolution_targets: list[dict], - *, - mode: str, -) -> list[dict]: - return _closure_forecast_reacquisition_freshness_hotspots_helper( - resolution_targets, - mode=mode, - target_class_key=_target_class_key, - ) +def _closure_forecast_momentum_summary( + primary_target: dict, + sustained_confirmation_hotspots: list[dict], + sustained_clearance_hotspots: list[dict], + oscillating_closure_forecast_hotspots: list[dict], +) -> str: + label = _target_label(primary_target) or "The current target" + status = primary_target.get("closure_forecast_momentum_status", "insufficient-data") + score = primary_target.get("closure_forecast_momentum_score", 0.0) + if status == "sustained-confirmation": + return f"Recent pending-resolution behavior around {label} has stayed strong long enough to keep the confirmation forecast credible ({score:.2f})." + if status == "sustained-clearance": + return f"Unresolved pending debt around {label} has stayed strong long enough to keep clearance or expiry risk elevated ({score:.2f})." + if status == "building": + return f"The closure forecast for {label} is trending in one direction, but it has not held long enough to lock in ({score:.2f})." + if status == "reversing": + return f"Recent pending-resolution evidence around {label} is changing direction, so earlier forecast strength is being softened ({score:.2f})." + if status == "unstable": + return f"Recent closure-forecast evidence around {label} is bouncing too much to strengthen safely right now ({score:.2f})." + if sustained_confirmation_hotspots: + hotspot = sustained_confirmation_hotspots[0] + return ( + f"Confirmation-leaning closure momentum is strongest around {hotspot.get('label', 'recent hotspots')}, " + "but the current target has not built enough persistence yet." + ) + if sustained_clearance_hotspots: + hotspot = sustained_clearance_hotspots[0] + return ( + f"Clearance-heavy closure momentum is strongest around {hotspot.get('label', 'recent hotspots')}, " + "so weaker pending states there should keep proving follow-through." + ) + if oscillating_closure_forecast_hotspots: + hotspot = oscillating_closure_forecast_hotspots[0] + return ( + f"Closure-forecast stability is weakest around {hotspot.get('label', 'recent hotspots')}, " + "so stronger forecast changes there should wait for persistence." + ) + return "Closure-forecast momentum is still too lightly exercised to say whether recent pending-resolution behavior is sustained or unstable." -def _closure_forecast_reacquisition_freshness_summary( +def _closure_forecast_stability_summary( primary_target: dict, - stale_reacquisition_hotspots: list[dict], - fresh_reacquisition_signal_hotspots: list[dict], + oscillating_closure_forecast_hotspots: list[dict], ) -> str: - return _closure_forecast_reacquisition_freshness_summary_helper( - primary_target, - stale_reacquisition_hotspots, - fresh_reacquisition_signal_hotspots, - target_label=_target_label, - ) + label = _target_label(primary_target) or "The current target" + stability_status = primary_target.get("closure_forecast_stability_status", "watch") + recent_path = primary_target.get("recent_closure_forecast_path", "") + if stability_status == "oscillating": + return f"Closure forecasting for {label} is bouncing too much to strengthen safely right now: {recent_path or 'no stable path yet'}." + if stability_status == "watch": + return f"Closure forecasting for {label} is still settling and should be watched for one more stable stretch: {recent_path or 'signal is still building'}." + if recent_path: + return f"Closure forecasting for {label} is stable across the recent path: {recent_path}." + if oscillating_closure_forecast_hotspots: + hotspot = oscillating_closure_forecast_hotspots[0] + return ( + f"Closure-forecast stability is weakest around {hotspot.get('label', 'recent hotspots')}, " + "so stronger forecast shifts should wait there." + ) + return "Recent closure-forecast guidance is stable enough that no extra hysteresis warning is needed." -def _closure_forecast_persistence_reset_summary( +def _closure_forecast_hysteresis_summary( primary_target: dict, - stale_reacquisition_hotspots: list[dict], - fresh_reacquisition_signal_hotspots: list[dict], + sustained_confirmation_hotspots: list[dict], + sustained_clearance_hotspots: list[dict], ) -> str: - return _closure_forecast_persistence_reset_summary_helper( - primary_target, - stale_reacquisition_hotspots, - fresh_reacquisition_signal_hotspots, - target_label=_target_label, - ) + label = _target_label(primary_target) or "The current target" + status = primary_target.get("closure_forecast_hysteresis_status", "none") + reason = primary_target.get("closure_forecast_hysteresis_reason", "") + if status == "confirmed-confirmation": + return ( + reason + or f"Fresh class follow-through has stayed strong enough to keep the stronger confirmation forecast in place for {label}." + ) + if status == "confirmed-clearance": + return ( + reason + or f"Fresh unresolved pending debt has stayed strong enough to keep the stronger clearance forecast in place for {label}." + ) + if status == "pending-confirmation": + return ( + reason + or f"The confirmation-leaning forecast for {label} is visible but not yet persistent enough to trust fully." + ) + if status == "pending-clearance": + return ( + reason + or f"The clearance-leaning forecast for {label} is visible but not yet persistent enough to clear early." + ) + if status == "blocked": + return ( + reason + or f"Local target instability is preventing positive closure-forecast strengthening for {label}." + ) + if sustained_confirmation_hotspots: + hotspot = sustained_confirmation_hotspots[0] + return ( + f"Confirmation-side closure hysteresis is strongest around {hotspot.get('label', 'recent hotspots')}, " + "so those classes are closest to holding stronger confirmation forecasts safely." + ) + if sustained_clearance_hotspots: + hotspot = sustained_clearance_hotspots[0] + return ( + f"Clearance-side closure hysteresis is strongest around {hotspot.get('label', 'recent hotspots')}, " + "so those classes can hold stronger clearance forecasts only when that pressure keeps persisting." + ) + return "No closure-forecast hysteresis adjustment is changing the live pending forecast right now." -def _closure_forecast_reacquisition_persistence_summary( +def _closure_forecast_freshness_summary( primary_target: dict, - just_reacquired_hotspots: list[dict], - holding_reacquisition_hotspots: list[dict], + stale_closure_forecast_hotspots: list[dict], + fresh_closure_forecast_signal_hotspots: list[dict], ) -> str: - return _closure_forecast_reacquisition_persistence_summary_helper( - primary_target, - just_reacquired_hotspots, - holding_reacquisition_hotspots, - target_label=_target_label, + label = _target_label(primary_target) or "The current target" + freshness_status = primary_target.get( + "closure_forecast_freshness_status", "insufficient-data" ) + if freshness_status == "fresh": + return f"{label} still has recent closure-forecast evidence that is current enough to trust." + if freshness_status == "mixed-age": + return f"{label} still has useful closure-forecast memory, but part of that signal is aging and should be weighted more cautiously." + if freshness_status == "stale": + return f"{label} is leaning on older closure-forecast momentum more than fresh runs, so stale class carry-forward should not dominate the current forecast." + if fresh_closure_forecast_signal_hotspots: + hotspot = fresh_closure_forecast_signal_hotspots[0] + return ( + f"Fresh closure-forecast evidence is strongest around {hotspot.get('label', 'recent hotspots')}, " + "so those classes deserve more trust than older forecast carry-forward." + ) + if stale_closure_forecast_hotspots: + hotspot = stale_closure_forecast_hotspots[0] + return ( + f"Older closure-forecast momentum is lingering most around {hotspot.get('label', 'recent hotspots')}, " + "so those classes should keep letting stale forecast strength decay." + ) + return "Closure-forecast memory is still too lightly exercised to say whether fresh or stale forecast evidence should lead the current posture." -def _closure_forecast_recovery_churn_summary( +def _closure_forecast_decay_summary( primary_target: dict, - recovery_churn_hotspots: list[dict], + fresh_closure_forecast_signal_hotspots: list[dict], + stale_closure_forecast_hotspots: list[dict], ) -> str: - return _closure_forecast_recovery_churn_summary_helper( - primary_target, - recovery_churn_hotspots, - target_label=_target_label, + label = _target_label(primary_target) or "The current target" + decay_status = primary_target.get("closure_forecast_decay_status", "none") + freshness_status = primary_target.get( + "closure_forecast_freshness_status", "insufficient-data" ) + confirmation_rate = primary_target.get("decayed_confirmation_forecast_rate", 0.0) + clearance_rate = primary_target.get("decayed_clearance_forecast_rate", 0.0) + if decay_status == "confirmation-decayed": + return f"Stronger confirmation wording for {label} was pulled back because the supporting closure-forecast memory is too old or too lightly refreshed." + if decay_status == "clearance-decayed": + return f"Stronger clearance wording for {label} was pulled back because fresh unresolved pending-debt support is no longer strong enough." + if decay_status == "blocked": + return f"Local target instability still overrides closure-forecast freshness for {label}, so forecast carry-forward should stay conservative." + if freshness_status == "fresh" and confirmation_rate >= clearance_rate: + return f"Fresh closure-forecast evidence for {label} is still reinforcing confirmation-side posture more than clearance pressure." + if freshness_status == "fresh": + return f"Fresh closure-forecast evidence for {label} is still reinforcing clearance pressure more than confirmation-side carry-forward." + if freshness_status == "stale": + return f"Older closure-forecast momentum is being down-weighted for {label}, so stale forecast strength should keep decaying instead of carrying forward indefinitely." + if fresh_closure_forecast_signal_hotspots: + hotspot = fresh_closure_forecast_signal_hotspots[0] + return ( + f"Fresh closure-forecast reinforcement is strongest around {hotspot.get('label', 'recent hotspots')}, " + "so those classes are earning stronger live forecasting than older carry-forward." + ) + if stale_closure_forecast_hotspots: + hotspot = stale_closure_forecast_hotspots[0] + return ( + f"Stale closure-forecast carry-forward is strongest around {hotspot.get('label', 'recent hotspots')}, " + "so those older forecast patterns should keep decaying." + ) + return "No strong closure-forecast freshness trend is dominating the live hysteresis posture yet." def _target_class_reweight_history(target: dict, reweight_events: list[dict]) -> dict: class_key = _target_class_key(target) - matching_events = [event for event in reweight_events if event.get("class_key") == class_key][ - :CLASS_TRANSITION_WINDOW_RUNS - ] + matching_events = [ + event for event in reweight_events if event.get("class_key") == class_key + ][:CLASS_TRANSITION_WINDOW_RUNS] signals = [_class_signal_from_reweight_event(event) for event in matching_events] relevant_signals = [signal for signal in signals if abs(signal) >= 0.05] weighted_total = 0.0 @@ -17029,7 +15090,11 @@ def _target_class_reweight_history(target: dict, reweight_events: list[dict]) -> if flip_count >= 2: stability_status = "oscillating" - elif flip_count == 1 or momentum_status in {"building", "insufficient-data", "reversing"}: + elif flip_count == 1 or momentum_status in { + "building", + "insufficient-data", + "reversing", + }: stability_status = "watch" else: stability_status = "stable" @@ -17066,16 +15131,13 @@ def _normalized_class_reweight_direction(direction: str, score: float) -> str: return "neutral" -def _class_direction_flip_count(directions: list[str]) -> int: - non_neutral = [direction for direction in directions if direction != "neutral"] - if len(non_neutral) < 2: - return 0 - return sum(1 for previous, current in zip(non_neutral, non_neutral[1:]) if current != previous) - - def _class_direction_majority(directions: list[str]) -> str: - support_count = sum(1 for direction in directions if direction == "supporting-normalization") - caution_count = sum(1 for direction in directions if direction == "supporting-caution") + support_count = sum( + 1 for direction in directions if direction == "supporting-normalization" + ) + caution_count = sum( + 1 for direction in directions if direction == "supporting-caution" + ) if support_count > caution_count: return "supporting-normalization" if caution_count > support_count: @@ -17101,7 +15163,9 @@ def _class_trust_momentum_for_target( class_normalization_status: str, class_normalization_reason: str, ) -> tuple[str, str, str, str, str, str, str, str]: - momentum_status = history_meta.get("class_trust_momentum_status", "insufficient-data") + momentum_status = history_meta.get( + "class_trust_momentum_status", "insufficient-data" + ) stability_status = history_meta.get("class_reweight_stability_status", "watch") local_noise = _target_specific_normalization_noise(target, history_meta) calibration_status = confidence_calibration.get( @@ -17114,7 +15178,9 @@ def _class_trust_momentum_for_target( and target.get("class_trust_reweight_direction") == "supporting-normalization" and target.get("class_trust_reweight_score", 0.0) >= 0.20 ): - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) reverted_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason ) @@ -17124,7 +15190,9 @@ def _class_trust_momentum_for_target( "blocked", blocked_reason, reverted_policy, - blocked_reason if reverted_policy == "verify-first" else reverted_reason, + blocked_reason + if reverted_policy == "verify-first" + else reverted_reason, policy_debt_status, policy_debt_reason, "candidate", @@ -17155,7 +15223,9 @@ def _class_trust_momentum_for_target( confirmed_reason, ) pending_reason = "The class signal is visible, but it has not stayed strong long enough to confirm broader normalization yet." - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) reverted_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason ) @@ -17195,9 +15265,14 @@ def _class_trust_momentum_for_target( class_normalization_reason, ) - if class_normalization_status == "applied" and momentum_status in {"reversing", "unstable"}: + if class_normalization_status == "applied" and momentum_status in { + "reversing", + "unstable", + }: softened_reason = "Recent class evidence is changing direction, so earlier class normalization is being softened back to candidate." - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) if trust_policy == "act-with-review" and reverted_policy == "verify-first": trust_policy = reverted_policy trust_policy_reason = softened_reason @@ -17214,7 +15289,10 @@ def _class_trust_momentum_for_target( softened_reason, ) - if policy_debt_status == "class-debt" and momentum_status in {"reversing", "unstable"}: + if policy_debt_status == "class-debt" and momentum_status in { + "reversing", + "unstable", + }: softened_reason = "Recent class evidence is changing direction, so sticky class caution is being softened back to watch." return ( "none", @@ -17229,7 +15307,9 @@ def _class_trust_momentum_for_target( if calibration_status != "healthy" and reweight_effect == "normalization-boosted": blocked_reason = "Positive class strengthening remains visible, but calibration is not healthy enough to confirm it." - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) reverted_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason ) @@ -17270,12 +15350,16 @@ def _class_transition_resolution_for_target( class_normalization_status: str, class_normalization_reason: str, ) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str]: - current_transition_status = history_meta.get("current_transition_status", transition_status) + current_transition_status = history_meta.get( + "current_transition_status", transition_status + ) transition_age_runs = history_meta.get("class_transition_age_runs", 0) current_strengthening = history_meta.get("current_transition_strengthening", False) current_neutral = history_meta.get("current_transition_neutral", False) current_reversed = history_meta.get("current_transition_reversed", False) - current_lost_pending_support = history_meta.get("current_lost_pending_support", False) + current_lost_pending_support = history_meta.get( + "current_lost_pending_support", False + ) recent_pending_status = history_meta.get("recent_pending_status", "none") recent_pending_age_runs = history_meta.get("recent_pending_age_runs", 0) if current_transition_status == "blocked": @@ -17416,7 +15500,9 @@ def _class_transition_resolution_for_target( ) -def _class_momentum_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: +def _class_momentum_hotspots( + resolution_targets: list[dict], *, mode: str +) -> list[dict]: grouped: dict[str, dict] = {} for target in resolution_targets: class_key = _target_class_key(target) @@ -17427,11 +15513,15 @@ def _class_momentum_hotspots(resolution_targets: list[dict], *, mode: str) -> li "scope": "class", "label": class_key, "momentum_score": target.get("class_trust_momentum_score", 0.0), - "momentum_status": target.get("class_trust_momentum_status", "insufficient-data"), + "momentum_status": target.get( + "class_trust_momentum_status", "insufficient-data" + ), "stability_status": target.get("class_reweight_stability_status", "watch"), "recent_class_reweight_path": target.get("recent_class_reweight_path", ""), } - if existing is None or abs(current["momentum_score"]) > abs(existing["momentum_score"]): + if existing is None or abs(current["momentum_score"]) > abs( + existing["momentum_score"] + ): grouped[class_key] = current hotspots = list(grouped.values()) if mode == "sustained": @@ -17447,7 +15537,9 @@ def _class_momentum_hotspots(resolution_targets: list[dict], *, mode: str) -> li ) ) else: - hotspots = [item for item in hotspots if item.get("stability_status") == "oscillating"] + hotspots = [ + item for item in hotspots if item.get("stability_status") == "oscillating" + ] hotspots.sort( key=lambda item: ( -abs(item.get("momentum_score", 0.0)), @@ -17457,7 +15549,9 @@ def _class_momentum_hotspots(resolution_targets: list[dict], *, mode: str) -> li return hotspots[:5] -def _class_transition_hotspots(resolution_targets: list[dict], *, mode: str) -> list[dict]: +def _class_transition_hotspots( + resolution_targets: list[dict], *, mode: str +) -> list[dict]: grouped: dict[str, dict] = {} for target in resolution_targets: class_key = _target_class_key(target) @@ -17469,16 +15563,23 @@ def _class_transition_hotspots(resolution_targets: list[dict], *, mode: str) -> "label": class_key, "transition_age_runs": target.get("class_transition_age_runs", 0), "health_status": target.get("class_transition_health_status", "none"), - "resolution_status": target.get("class_transition_resolution_status", "none"), + "resolution_status": target.get( + "class_transition_resolution_status", "none" + ), "recent_transition_path": target.get("recent_transition_path", ""), } - if existing is None or current["transition_age_runs"] > existing["transition_age_runs"]: + if ( + existing is None + or current["transition_age_runs"] > existing["transition_age_runs"] + ): grouped[class_key] = current hotspots = list(grouped.values()) if mode == "stalled": hotspots = [ - item for item in hotspots if item.get("health_status") in {"stalled", "expired"} + item + for item in hotspots + if item.get("health_status") in {"stalled", "expired"} ] else: hotspots = [ @@ -17623,13 +15724,7 @@ def _class_transition_resolution_summary( f"Pending class transitions are stalling most around {hotspot.get('label', 'recent hotspots')}, " "so those pending states should not linger indefinitely." ) - return ( - "No pending class transition has just confirmed, cleared, or expired in the recent window." - ) - - -def _clamp_round(value: float, *, lower: float, upper: float) -> float: - return round(max(lower, min(upper, value)), 2) + return "No pending class transition has just confirmed, cleared, or expired in the recent window." def _retirement_policy_events( @@ -17649,7 +15744,9 @@ def _retirement_policy_events( "generated_at": current_generated_at or "", "lane": current_primary_target.get("lane", ""), "kind": current_primary_target.get("kind", ""), - "decision_memory_status": current_primary_target.get("decision_memory_status", ""), + "decision_memory_status": current_primary_target.get( + "decision_memory_status", "" + ), "last_outcome": current_primary_target.get("last_outcome", ""), "trust_exception_status": current_primary_target.get( "trust_exception_status", "none" @@ -17676,7 +15773,9 @@ def _retirement_policy_events( "kind": primary_target.get("kind", ""), "decision_memory_status": summary.get("decision_memory_status", ""), "last_outcome": summary.get("primary_target_last_outcome", ""), - "trust_exception_status": summary.get("primary_target_exception_status", "none"), + "trust_exception_status": summary.get( + "primary_target_exception_status", "none" + ), "trust_recovery_status": summary.get( "primary_target_trust_recovery_status", "none" ), @@ -17702,9 +15801,13 @@ def _target_retirement_history( key = _queue_identity(target) class_key = _target_class_key(target) target_events = [event for event in retirement_events if event.get("key") == key] - class_events = [event for event in retirement_events if event.get("class_key") == class_key] + class_events = [ + event for event in retirement_events if event.get("class_key") == class_key + ] target_cases = [case for case in historical_cases if case.get("key") == key] - class_cases = [case for case in historical_cases if case.get("class_key") == class_key] + class_cases = [ + case for case in historical_cases if case.get("class_key") == class_key + ] target_policies = [ event.get("trust_policy", "monitor") for event in target_events[:EXCEPTION_RETIREMENT_WINDOW_RUNS] @@ -17714,11 +15817,14 @@ def _target_retirement_history( for event in class_events[:EXCEPTION_RETIREMENT_WINDOW_RUNS] ] target_lanes = [ - event.get("lane", "") for event in target_events[:EXCEPTION_RETIREMENT_WINDOW_RUNS] + event.get("lane", "") + for event in target_events[:EXCEPTION_RETIREMENT_WINDOW_RUNS] ] return { "stable_after_exception_runs": _stable_policy_run_count(target_policies), - "recent_retirement_path": " -> ".join(target_policies[:EXCEPTION_RETIREMENT_WINDOW_RUNS]) + "recent_retirement_path": " -> ".join( + target_policies[:EXCEPTION_RETIREMENT_WINDOW_RUNS] + ) or " -> ".join(class_policies[:EXCEPTION_RETIREMENT_WINDOW_RUNS]), "recent_policy_flip_count": _policy_flip_count(target_policies), "same_or_lower_pressure_path": _same_or_lower_pressure_path(target_lanes), @@ -17749,10 +15855,14 @@ def _recovery_confidence_for_target( if calibration_status == "healthy": score += 0.20 - calibration_reason = "Healthy calibration supports relaxing the earlier soft caution." + calibration_reason = ( + "Healthy calibration supports relaxing the earlier soft caution." + ) elif calibration_status == "noisy": score -= 0.10 - calibration_reason = "Noisy calibration still argues for keeping caution in place." + calibration_reason = ( + "Noisy calibration still argues for keeping caution in place." + ) blockers.append( ( -0.10, @@ -17761,9 +15871,7 @@ def _recovery_confidence_for_target( ) elif calibration_status == "insufficient-data": score -= 0.05 - calibration_reason = ( - "Calibration is still lightly exercised, so retirement confidence stays softer." - ) + calibration_reason = "Calibration is still lightly exercised, so retirement confidence stays softer." blockers.append( ( -0.05, @@ -17771,7 +15879,9 @@ def _recovery_confidence_for_target( ) ) else: - calibration_reason = "Mixed calibration keeps retirement confidence in the middle for now." + calibration_reason = ( + "Mixed calibration keeps retirement confidence in the middle for now." + ) recent_reopened = history_meta.get("recent_reopened", False) recent_policy_flip_count = history_meta.get("recent_policy_flip_count", 0) @@ -17809,13 +15919,13 @@ def _recovery_confidence_for_target( "Recent runs stayed stable after the exception without new pressure spikes." ) elif stable_after_exception_runs >= 2 or same_or_lower_pressure_path: - stability_reason = "Recent runs are stabilizing, but the retirement window is still short." + stability_reason = ( + "Recent runs are stabilizing, but the retirement window is still short." + ) if latest_case_outcome == "overcautious": score += 0.10 - exception_reason = ( - "Recent exception history looks overcautious, so relaxing the softer posture is safer." - ) + exception_reason = "Recent exception history looks overcautious, so relaxing the softer posture is safer." elif latest_case_outcome == "useful-caution": score -= 0.15 exception_reason = "Recent exception history still shows useful caution, so the softer posture remains justified." @@ -17826,16 +15936,16 @@ def _recovery_confidence_for_target( ) ) elif latest_case_outcome == "insufficient-data": - exception_reason = ( - "Recent exception history is still too light to prove the softer posture can retire." - ) + exception_reason = "Recent exception history is still too light to prove the softer posture can retire." if target.get("trust_recovery_status") == "earned": score += 0.05 score = max(0.05, min(0.95, round(score, 2))) reasons = [ - reason for reason in (calibration_reason, stability_reason, exception_reason) if reason + reason + for reason in (calibration_reason, stability_reason, exception_reason) + if reason ] if blockers: strongest_blocker = sorted(blockers, key=lambda item: item[0])[0][1] @@ -17880,9 +15990,7 @@ def _exception_retirement_for_target( elif recent_policy_flip_count > 0: reason = "Exception retirement is blocked because trust policy is still flipping inside the retirement window." else: - reason = ( - "Exception retirement is blocked because calibration is not healthy enough yet." - ) + reason = "Exception retirement is blocked because calibration is not healthy enough yet." return "blocked", reason, trust_policy, trust_policy_reason if ( @@ -17922,7 +16030,9 @@ def _is_exception_affected_target(target: dict) -> bool: def _restore_retired_trust_policy(target: dict) -> tuple[str, str]: - restored_policy = target.get("base_trust_policy", target.get("trust_policy", "monitor")) + restored_policy = target.get( + "base_trust_policy", target.get("trust_policy", "monitor") + ) if ( target.get("lane") == "blocked" and target.get("kind") == "setup" @@ -18083,7 +16193,9 @@ def _retirement_hotspots( hotspots: list[dict] = [] target_outcomes = ( - {"overcautious", "retired"} if mode == "retired" else {"useful-caution", "blocked"} + {"overcautious", "retired"} + if mode == "retired" + else {"useful-caution", "blocked"} ) count_key = "retired_count" if mode == "retired" else "sticky_count" for label, outcomes in grouped.items(): @@ -18125,7 +16237,9 @@ def _class_normalization_events( "generated_at": current_generated_at or "", "lane": current_primary_target.get("lane", ""), "kind": current_primary_target.get("kind", ""), - "decision_memory_status": current_primary_target.get("decision_memory_status", ""), + "decision_memory_status": current_primary_target.get( + "decision_memory_status", "" + ), "last_outcome": current_primary_target.get("last_outcome", ""), "trust_exception_status": current_primary_target.get( "trust_exception_status", "none" @@ -18142,7 +16256,9 @@ def _class_normalization_events( "exception_pattern_status": current_primary_target.get( "exception_pattern_status", "none" ), - "policy_debt_status": current_primary_target.get("policy_debt_status", "none"), + "policy_debt_status": current_primary_target.get( + "policy_debt_status", "none" + ), "class_normalization_status": current_primary_target.get( "class_normalization_status", "none" ), @@ -18166,18 +16282,24 @@ def _class_normalization_events( "kind": primary_target.get("kind", ""), "decision_memory_status": summary.get("decision_memory_status", ""), "last_outcome": summary.get("primary_target_last_outcome", ""), - "trust_exception_status": summary.get("primary_target_exception_status", "none"), + "trust_exception_status": summary.get( + "primary_target_exception_status", "none" + ), "trust_recovery_status": summary.get( "primary_target_trust_recovery_status", "none" ), "exception_retirement_status": summary.get( "primary_target_exception_retirement_status", "none" ), - "confidence_validation_status": summary.get("confidence_validation_status", ""), + "confidence_validation_status": summary.get( + "confidence_validation_status", "" + ), "exception_pattern_status": summary.get( "primary_target_exception_pattern_status", "none" ), - "policy_debt_status": summary.get("primary_target_policy_debt_status", "none"), + "policy_debt_status": summary.get( + "primary_target_policy_debt_status", "none" + ), "class_normalization_status": summary.get( "primary_target_class_normalization_status", "none" ), @@ -18195,7 +16317,9 @@ def _target_class_normalization_history( key = _queue_identity(target) class_key = _target_class_key(target) target_events = [event for event in class_events if event.get("key") == key] - matching_class_events = [event for event in class_events if event.get("class_key") == class_key] + matching_class_events = [ + event for event in class_events if event.get("class_key") == class_key + ] target_policies = [ event.get("trust_policy", "monitor") for event in target_events[:CLASS_NORMALIZATION_WINDOW_RUNS] @@ -18205,7 +16329,8 @@ def _target_class_normalization_history( for event in matching_class_events[:CLASS_NORMALIZATION_WINDOW_RUNS] ] target_lanes = [ - event.get("lane", "") for event in target_events[:CLASS_NORMALIZATION_WINDOW_RUNS] + event.get("lane", "") + for event in target_events[:CLASS_NORMALIZATION_WINDOW_RUNS] ] class_exception_events = [ event @@ -18214,7 +16339,9 @@ def _target_class_normalization_history( or event.get("exception_retirement_status") not in {None, "", "none"} ] target_cases = [case for case in historical_cases if case.get("key") == key] - class_cases = [case for case in historical_cases if case.get("class_key") == class_key] + class_cases = [ + case for case in historical_cases if case.get("class_key") == class_key + ] exception_count = len(class_exception_events) retired_count = sum( 1 @@ -18233,7 +16360,9 @@ def _target_class_normalization_history( 1 for case in class_cases if case.get("case_outcome") == "useful-caution" ) verify_first_count = sum( - 1 for event in matching_class_events if event.get("trust_policy") == "verify-first" + 1 + for event in matching_class_events + if event.get("trust_policy") == "verify-first" ) if target.get("trust_exception_status") not in {None, "", "none"} or target.get( "exception_retirement_status" @@ -18271,9 +16400,15 @@ def _target_class_normalization_history( weighted_retired_like += weight if _is_sticky_like_class_event(event): weighted_sticky_like += weight - recent_window_weight_share = recent_exception_weight / max(weighted_exception_count, 1.0) - decayed_class_retirement_rate = weighted_retired_like / max(weighted_exception_count, 1.0) - decayed_class_sticky_rate = weighted_sticky_like / max(weighted_exception_count, 1.0) + recent_window_weight_share = recent_exception_weight / max( + weighted_exception_count, 1.0 + ) + decayed_class_retirement_rate = weighted_retired_like / max( + weighted_exception_count, 1.0 + ) + decayed_class_sticky_rate = weighted_sticky_like / max( + weighted_exception_count, 1.0 + ) freshness_status = _class_memory_freshness_status( weighted_exception_count, recent_window_weight_share ) @@ -18310,7 +16445,9 @@ def _target_class_normalization_history( "stable_after_exception_runs": target.get( "stable_after_exception_runs", _stable_policy_run_count(target_policies) ), - "recent_class_policy_path": " -> ".join(class_policies[:CLASS_NORMALIZATION_WINDOW_RUNS]), + "recent_class_policy_path": " -> ".join( + class_policies[:CLASS_NORMALIZATION_WINDOW_RUNS] + ), "recent_policy_flip_count": _policy_flip_count(target_policies), "recent_class_policy_flip_count": _policy_flip_count(class_policies), "same_or_lower_pressure_path": _same_or_lower_pressure_path(target_lanes), @@ -18413,27 +16550,21 @@ def _class_normalization_candidate(history_meta: dict) -> bool: ) -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return ( - history_meta.get("recent_reopened", False) - or history_meta.get("recent_policy_flip_count", 0) > 0 - or target.get("trust_recovery_status") == "blocked" - ) - - def _policy_debt_for_target(target: dict, history_meta: dict) -> tuple[str, str]: exception_count = history_meta.get("exception_count", 0) retired_count = history_meta.get("retired_count", 0) sticky_count = history_meta.get("sticky_count", 0) class_sticky_rate = history_meta.get("class_sticky_rate", 0.0) - if _class_normalization_friendly(history_meta) and _target_specific_normalization_noise( - target, history_meta - ): + if _class_normalization_friendly( + history_meta + ) and _target_specific_normalization_noise(target, history_meta): return ( "one-off-noise", "This class has been earning clean retirement more often, but this target still has local reopen, flip, or blocked-recovery noise keeping the softer posture target-specific.", ) - if exception_count >= 3 and (sticky_count >= retired_count + 2 or class_sticky_rate >= 0.60): + if exception_count >= 3 and ( + sticky_count >= retired_count + 2 or class_sticky_rate >= 0.60 + ): return ( "class-debt", "This class keeps carrying sticky caution across recent runs, so class-level normalization would be premature.", @@ -18553,7 +16684,10 @@ def _class_normalization_hotspots( group["useful_caution_count"] += 1 if mode == "policy-debt" and target.get("policy_debt_status") == "class-debt": group["sticky_count"] += 1 - if mode == "normalized" and target.get("class_normalization_status") == "applied": + if ( + mode == "normalized" + and target.get("class_normalization_status") == "applied" + ): group["retired_count"] += 1 hotspots: list[dict] = [] @@ -18598,8 +16732,12 @@ def _class_memory_decay_for_target( class_normalization_status: str, class_normalization_reason: str, ) -> tuple[str, str, str, str, str, str, str, str]: - freshness_status = history_meta.get("class_memory_freshness_status", "insufficient-data") - decayed_class_retirement_rate = history_meta.get("decayed_class_retirement_rate", 0.0) + freshness_status = history_meta.get( + "class_memory_freshness_status", "insufficient-data" + ) + decayed_class_retirement_rate = history_meta.get( + "decayed_class_retirement_rate", 0.0 + ) decayed_class_sticky_rate = history_meta.get("decayed_class_sticky_rate", 0.0) local_noise = _target_specific_normalization_noise(target, history_meta) calibration_status = confidence_calibration.get( @@ -18622,7 +16760,9 @@ def _class_memory_decay_for_target( "stale", "insufficient-data", }: - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) reverted_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason, @@ -18709,10 +16849,14 @@ def _class_memory_hotspots(resolution_targets: list[dict], *, mode: str) -> list grouped[class_key] = { "scope": "class", "label": class_key, - "freshness_status": target.get("class_memory_freshness_status", "insufficient-data"), + "freshness_status": target.get( + "class_memory_freshness_status", "insufficient-data" + ), "class_memory_weight": target.get("class_memory_weight", 0.0), "weighted_exception_count": target.get("class_memory_weight", 0.0), - "decayed_class_retirement_rate": target.get("decayed_class_retirement_rate", 0.0), + "decayed_class_retirement_rate": target.get( + "decayed_class_retirement_rate", 0.0 + ), "decayed_class_sticky_rate": target.get("decayed_class_sticky_rate", 0.0), "recent_class_signal_mix": target.get("recent_class_signal_mix", ""), } @@ -18731,7 +16875,9 @@ def _class_memory_hotspots(resolution_targets: list[dict], *, mode: str) -> list ) ) else: - hotspots = [item for item in hotspots if item.get("freshness_status") == "fresh"] + hotspots = [ + item for item in hotspots if item.get("freshness_status") == "fresh" + ] hotspots.sort( key=lambda item: ( -item.get("class_memory_weight", 0.0), @@ -18748,7 +16894,9 @@ def _class_memory_summary( stale_class_memory_hotspots: list[dict], ) -> str: label = _target_label(primary_target) or "The current target" - freshness_status = primary_target.get("class_memory_freshness_status", "insufficient-data") + freshness_status = primary_target.get( + "class_memory_freshness_status", "insufficient-data" + ) if freshness_status == "fresh": return f"{label} sits in class evidence that is still fresh enough to trust, so recent class behavior should carry more weight than older lessons." if freshness_status == "mixed-age": @@ -18877,10 +17025,15 @@ def _same_or_lower_pressure_path(lanes: list[str]) -> bool: if len(lanes) < 2: return True chronological = [_lane_pressure(lane or None) for lane in reversed(lanes)] - return all(current <= previous for previous, current in zip(chronological, chronological[1:])) + return all( + current <= previous + for previous, current in zip(chronological, chronological[1:]) + ) -def _latest_case_outcome(target_cases: list[dict], class_cases: list[dict]) -> str | None: +def _latest_case_outcome( + target_cases: list[dict], class_cases: list[dict] +) -> str | None: if target_cases: return target_cases[0].get("case_outcome") if class_cases: @@ -18914,7 +17067,9 @@ def _recovery_pattern_reason(recovery_status: str, recovery_reason: str) -> str: return _recovery_pattern_reason_helper(recovery_status, recovery_reason) -def _exception_pattern_summary(primary_target: dict, false_positive_hotspots: list[dict]) -> str: +def _exception_pattern_summary( + primary_target: dict, false_positive_hotspots: list[dict] +) -> str: return _exception_pattern_summary_helper( primary_target, false_positive_hotspots, @@ -19020,15 +17175,6 @@ def _soften_trust_policy(policy: str, *, floor: str) -> str: return _soften_trust_policy_helper(policy, floor=floor) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - repo = f"{item.get('repo')}: " if item.get("repo") else "" - return f"{repo}{item.get('title', '')}".strip(": ") - - def _recommendation_confidence(item: dict) -> tuple[float, str, list[str]]: score = 0.20 lane_reason = "" @@ -19040,7 +17186,9 @@ def _recommendation_confidence(item: dict) -> tuple[float, str, list[str]]: kind = item.get("kind", "") if lane == "blocked" and kind == "setup": score += 0.40 - lane_reason = "Blocked setup issue is directly stopping a trustworthy next step." + lane_reason = ( + "Blocked setup issue is directly stopping a trustworthy next step." + ) elif lane == "blocked": score += 0.30 lane_reason = "Blocked operator work outranks urgent and ready items." @@ -19049,15 +17197,21 @@ def _recommendation_confidence(item: dict) -> tuple[float, str, list[str]]: lane_reason = "Urgent drift or regression needs attention before ready work." elif lane == "ready": score += 0.05 - lane_reason = "Ready work is actionable, but lower pressure than blocked or urgent items." + lane_reason = ( + "Ready work is actionable, but lower pressure than blocked or urgent items." + ) decision_memory_status = item.get("decision_memory_status", "") if decision_memory_status == "reopened": score += 0.20 - decision_reason = "This item reopened after an earlier quiet or resolved period." + decision_reason = ( + "This item reopened after an earlier quiet or resolved period." + ) elif decision_memory_status == "persisting": score += 0.15 - decision_reason = "This item has persisted across multiple runs without clearing." + decision_reason = ( + "This item has persisted across multiple runs without clearing." + ) elif decision_memory_status == "attempted": score += 0.10 decision_reason = "A prior intervention happened, but the item is still open." @@ -19085,15 +17239,24 @@ def _recommendation_confidence(item: dict) -> tuple[float, str, list[str]]: if lane == "ready" and priority < 60: penalties.append( - (-0.15, "This is a lower-priority ready item, so the recommendation is less certain.") + ( + -0.15, + "This is a lower-priority ready item, so the recommendation is less certain.", + ) ) if not item.get("last_intervention") and not _has_recent_change_evidence(item): penalties.append( - (-0.10, "There is little recent change evidence behind this recommendation yet.") + ( + -0.10, + "There is little recent change evidence behind this recommendation yet.", + ) ) if _is_generic_recommendation(item.get("recommended_action", "")): penalties.append( - (-0.10, "The suggested next step is still generic rather than tightly item-specific.") + ( + -0.10, + "The suggested next step is still generic rather than tightly item-specific.", + ) ) for penalty, _reason in penalties: @@ -19101,7 +17264,9 @@ def _recommendation_confidence(item: dict) -> tuple[float, str, list[str]]: score = max(0.05, min(0.95, round(score, 2))) label = _confidence_label(score) - reasons = [reason for reason in (lane_reason, decision_reason, aging_reason) if reason] + reasons = [ + reason for reason in (lane_reason, decision_reason, aging_reason) if reason + ] if penalties: reasons.append(sorted(penalties, key=lambda item: item[0])[0][1]) return score, label, reasons[:4] @@ -19112,7 +17277,9 @@ def _apply_calibration_adjustment( score: float, confidence_calibration: dict, ) -> tuple[float, str, float, str]: - status = confidence_calibration.get("confidence_validation_status", "insufficient-data") + status = confidence_calibration.get( + "confidence_validation_status", "insufficient-data" + ) current_label = _confidence_label(score) adjustment = 0.0 reason = "Calibration is too lightly exercised to change the live score yet." @@ -19125,18 +17292,20 @@ def _apply_calibration_adjustment( elif status == "noisy": if current_label == "high": adjustment -= 0.10 - reason = "Noisy calibration softens a previously high-confidence recommendation." + reason = ( + "Noisy calibration softens a previously high-confidence recommendation." + ) elif current_label == "medium": adjustment -= 0.05 - reason = "Noisy calibration slightly softens a medium-confidence recommendation." + reason = ( + "Noisy calibration slightly softens a medium-confidence recommendation." + ) else: reason = "Noisy calibration leaves already low-confidence recommendations unchanged." if status == "noisy" and item.get("decision_memory_status") == "reopened": adjustment -= 0.05 - reason = ( - "Noisy calibration further softens reopened recommendations until they are re-verified." - ) + reason = "Noisy calibration further softens reopened recommendations until they are re-verified." tuned_score = max(0.05, min(0.95, round(score + adjustment, 2))) return tuned_score, _confidence_label(tuned_score), round(adjustment, 2), reason @@ -19158,7 +17327,8 @@ def _has_recent_change_evidence(item: dict) -> bool: item.get("reopened"), item.get("stale"), item.get("aging_status") in {"stale", "chronic"}, - item.get("decision_memory_status") in {"reopened", "attempted", "persisting"}, + item.get("decision_memory_status") + in {"reopened", "attempted", "persisting"}, ] ) @@ -19171,7 +17341,9 @@ def _is_generic_monitor_guidance(action: str) -> bool: return is_generic_monitor_guidance(action) -def _is_generic_baseline_guidance(action: str, watch_guidance: dict | None = None) -> bool: +def _is_generic_baseline_guidance( + action: str, watch_guidance: dict | None = None +) -> bool: return is_generic_baseline_guidance(action, watch_guidance) @@ -19184,7 +17356,9 @@ def _trust_policy_for_item( *, watch_guidance: dict | None = None, ) -> tuple[str, str]: - status = confidence_calibration.get("confidence_validation_status", "insufficient-data") + status = confidence_calibration.get( + "confidence_validation_status", "insufficient-data" + ) lane = item.get("lane", "") decision_memory_status = item.get("decision_memory_status", "") generic_baseline = _is_generic_baseline_guidance(action_text, watch_guidance) @@ -19236,24 +17410,9 @@ def _trust_policy_for_item( ) -def _recommendation_bucket(item: dict) -> int: - lane = item.get("lane", "") - if lane == "blocked" and item.get("kind") == "setup": - return 0 - if lane == "blocked": - return 1 - if lane == "urgent" and item.get("aging_status") in {"stale", "chronic"}: - return 2 - if lane == "urgent" and item.get("reopened"): - return 3 - if lane == "urgent": - return 4 - if lane == "ready": - return 5 - return 6 - - -def _decision_memory_map(recent_runs: list[dict], evidence_events: list[dict]) -> dict[str, dict]: +def _decision_memory_map( + recent_runs: list[dict], evidence_events: list[dict] +) -> dict[str, dict]: evidence_by_key: dict[str, list[dict]] = {} for event in evidence_events: key = event.get("item_id") or _queue_identity(event) @@ -19267,7 +17426,9 @@ def _decision_memory_map(recent_runs: list[dict], evidence_events: list[dict]) - for key, item in (snapshot.get("items") or {}).items() if item.get("lane") != "deferred" } - current_snapshot = recent_runs[0] if recent_runs else {"items": {}, "generated_at": ""} + current_snapshot = ( + recent_runs[0] if recent_runs else {"items": {}, "generated_at": ""} + ) current_snapshot_items = _snapshot_items(current_snapshot) current_items = { key: item @@ -19284,8 +17445,12 @@ def _decision_memory_map(recent_runs: list[dict], evidence_events: list[dict]) - latest_events = evidence_by_key.get(key) or [] latest_event = latest_events[0] if latest_events else None if current_item: - status = _current_decision_memory_status(key, current_item, recent_runs, latest_event) - previous_match = recent_runs[1]["items"].get(key) if len(recent_runs) > 1 else None + status = _current_decision_memory_status( + key, current_item, recent_runs, latest_event + ) + previous_match = ( + recent_runs[1]["items"].get(key) if len(recent_runs) > 1 else None + ) outcome = _current_item_last_outcome( current_item, previous_match, @@ -19310,7 +17475,9 @@ def _decision_memory_map(recent_runs: list[dict], evidence_events: list[dict]) - } continue - absent_info = _absent_decision_memory(key, attention_history, recent_runs, latest_event) + absent_info = _absent_decision_memory( + key, attention_history, recent_runs, latest_event + ) if absent_info["status"] == "quieted": recently_quieted_count += 1 elif absent_info["status"] == "confirmed_resolved": @@ -19327,7 +17494,8 @@ def _decision_memory_map(recent_runs: list[dict], evidence_events: list[dict]) - reopened_after_resolution_count = sum( 1 for item in current_items.values() - if memory.get(_queue_identity(item), {}).get("decision_memory_status") == "reopened" + if memory.get(_queue_identity(item), {}).get("decision_memory_status") + == "reopened" ) return { **{ @@ -19361,7 +17529,8 @@ def _current_decision_memory_status( prior_matches = [ snapshot["items"].get(key) for snapshot in recent_runs[1:] - if snapshot["items"].get(key) and snapshot["items"][key].get("lane") != "deferred" + if snapshot["items"].get(key) + and snapshot["items"][key].get("lane") != "deferred" ] if not prior_matches: return "new" @@ -19370,7 +17539,9 @@ def _current_decision_memory_status( return "persisting" -def _was_resolved_then_reopened(key: str, recent_runs: list[dict], current_item: dict) -> bool: +def _was_resolved_then_reopened( + key: str, recent_runs: list[dict], current_item: dict +) -> bool: if current_item.get("lane") not in ATTENTION_LANES: return False absent_streak = 0 @@ -19384,9 +17555,14 @@ def _was_resolved_then_reopened(key: str, recent_runs: list[dict], current_item: return absent_streak >= 1 and saw_earlier_attention -def _attach_portfolio_catalog_context(queue: list[dict], report_data: dict) -> list[dict]: +def _attach_portfolio_catalog_context( + queue: list[dict], report_data: dict +) -> list[dict]: from src.portfolio_catalog import build_catalog_line, evaluate_intent_alignment - from src.portfolio_pathing import build_operating_path_entry, build_operating_path_line + from src.portfolio_pathing import ( + build_operating_path_entry, + build_operating_path_line, + ) from src.report_enrichment import ( build_maturity_gap_summary, build_operator_focus, @@ -19418,16 +17594,18 @@ def _attach_portfolio_catalog_context(queue: list[dict], report_data: dict) -> l ) enriched_item = dict(item) enriched_item["portfolio_catalog"] = catalog_entry - enriched_item["catalog_line"] = catalog_entry.get("catalog_line") or build_catalog_line( - catalog_entry - ) + enriched_item["catalog_line"] = catalog_entry.get( + "catalog_line" + ) or build_catalog_line(catalog_entry) enriched_item["intent_alignment"] = intent_alignment enriched_item["intent_alignment_reason"] = intent_alignment_reason scorecard = dict(audit.get("scorecard") or {}) if scorecard: enriched_item["scorecard"] = scorecard enriched_item["scorecard_line"] = build_scorecard_line(enriched_item) - enriched_item["maturity_gap_summary"] = build_maturity_gap_summary(enriched_item) + enriched_item["maturity_gap_summary"] = build_maturity_gap_summary( + enriched_item + ) path_entry = build_operating_path_entry( catalog_entry, intent_alignment=intent_alignment, @@ -19509,35 +17687,42 @@ def _primary_target(resolution_targets: list[dict]) -> dict: def _primary_target_reason(primary_target: dict) -> str: if not primary_target: return "" - if primary_target.get("lane") == "blocked" and primary_target.get("kind") == "setup": + if ( + primary_target.get("lane") == "blocked" + and primary_target.get("kind") == "setup" + ): return "This is a setup blocker, so nothing trustworthy can proceed until the prerequisite is cleared." if primary_target.get("lane") == "blocked": return "This is the highest blocked item, so it outranks urgent and ready work." - if primary_target.get("lane") == "urgent" and primary_target.get("aging_status") == "chronic": + if ( + primary_target.get("lane") == "urgent" + and primary_target.get("aging_status") == "chronic" + ): return "This urgent item has survived multiple cycles, so follow-through debt now outweighs newer ready work." if primary_target.get("lane") == "urgent" and primary_target.get("newly_stale"): return "This urgent item has just crossed into follow-through debt, so it should be closed before it turns chronic." if primary_target.get("lane") == "urgent" and primary_target.get("stale"): - return ( - "This urgent item is already stale, so it outranks fresher urgent items and ready work." - ) + return "This urgent item is already stale, so it outranks fresher urgent items and ready work." if primary_target.get("lane") == "urgent" and primary_target.get("reopened"): return "This urgent item reappeared after disappearing, so it should be closed before it churns again." if primary_target.get("lane") == "urgent": return "This is the live urgent item with the highest current pressure, so it outranks ready work." if primary_target.get("lane") == "ready": - return ( - "Nothing is blocked or urgent, so this is the highest-value ready item to close next." - ) + return "Nothing is blocked or urgent, so this is the highest-value ready item to close next." return "This remains the highest-value target in the current queue." def _primary_target_done_criteria(primary_target: dict) -> str: if not primary_target: return "" - if primary_target.get("lane") == "blocked" and primary_target.get("kind") == "setup": + if ( + primary_target.get("lane") == "blocked" + and primary_target.get("kind") == "setup" + ): return "Clear the failing prerequisite, rerun the relevant command, and confirm the blocker no longer appears on the next run." - if primary_target.get("kind") in {"campaign", "governance"} and primary_target.get("lane") in { + if primary_target.get("kind") in {"campaign", "governance"} and primary_target.get( + "lane" + ) in { "blocked", "urgent", }: @@ -19546,9 +17731,7 @@ def _primary_target_done_criteria(primary_target: dict) -> str: return "Complete the recommended action and confirm the item exits the blocked or urgent queue on the next run." if primary_target.get("lane") == "ready": return "Make the manual decision and confirm the item either clears or moves into a lower-pressure lane on the next run." - return ( - "Confirm this item no longer requires blocked, urgent, or ready attention on the next run." - ) + return "Confirm this item no longer requires blocked, urgent, or ready attention on the next run." def _closure_guidance(primary_target: dict, done_criteria: str) -> str: @@ -19557,9 +17740,13 @@ def _closure_guidance(primary_target: dict, done_criteria: str) -> str: done_condition = done_criteria if done_condition.startswith("Make ") and " and confirm " in done_condition: decision, confirmation = done_condition[5:].split(" and confirm ", 1) - done_condition = f"{decision[0].lower()}{decision[1:]} is made and {confirmation}" + done_condition = ( + f"{decision[0].lower()}{decision[1:]} is made and {confirmation}" + ) elif done_condition.startswith("Make "): - done_condition = f"{done_condition[5:6].lower()}{done_condition[6:]} is complete" + done_condition = ( + f"{done_condition[5:6].lower()}{done_condition[6:]} is complete" + ) elif done_condition: done_condition = f"{done_condition[0].lower()}{done_condition[1:]}" action = primary_target.get("recommended_action", "") @@ -19574,18 +17761,24 @@ def _operator_confidence_summary( watch_guidance: dict, confidence_calibration: dict, ) -> dict: - primary_score = primary_target.get("confidence_score", 0.05) if primary_target else 0.05 + primary_score = ( + primary_target.get("confidence_score", 0.05) if primary_target else 0.05 + ) primary_label = ( primary_target.get("confidence_label", _confidence_label(primary_score)) if primary_target else "low" ) - primary_reasons = primary_target.get("confidence_reasons", []) if primary_target else [] + primary_reasons = ( + primary_target.get("confidence_reasons", []) if primary_target else [] + ) primary_trust_policy = ( primary_target.get("trust_policy", "monitor") if primary_target else "monitor" ) primary_trust_policy_reason = ( - primary_target.get("trust_policy_reason", "No trust-policy reason is recorded yet.") + primary_target.get( + "trust_policy_reason", "No trust-policy reason is recorded yet." + ) if primary_target else "No trust-policy reason is recorded yet." ) @@ -19630,7 +17823,9 @@ def _operator_confidence_summary( "next_action_trust_policy": next_trust_policy, "next_action_trust_policy_reason": next_trust_policy_reason, "adaptive_confidence_summary": _adaptive_confidence_summary( - confidence_calibration.get("confidence_validation_status", "insufficient-data"), + confidence_calibration.get( + "confidence_validation_status", "insufficient-data" + ), primary_target, primary_trust_policy, next_trust_policy, @@ -19641,7 +17836,9 @@ def _operator_confidence_summary( def _next_action_confidence( primary_target: dict, next_action: str, watch_guidance: dict ) -> tuple[float, str, list[str]]: - base_score = primary_target.get("confidence_score", 0.05) if primary_target else 0.05 + base_score = ( + primary_target.get("confidence_score", 0.05) if primary_target else 0.05 + ) action = (next_action or "").strip() reasons: list[str] = [] normalized = action.lower() @@ -19653,9 +17850,9 @@ def _next_action_confidence( reasons.append( "The next step is mostly watch-and-monitor guidance, so it is less decisive." ) - elif any(phrase in normalized for phrase in GENERIC_BASELINE_PHRASES) or watch_guidance.get( - "full_refresh_due" - ): + elif any( + phrase in normalized for phrase in GENERIC_BASELINE_PHRASES + ) or watch_guidance.get("full_refresh_due"): base_score -= 0.10 reasons.append( "The next step is baseline-refresh guidance rather than a direct closure action." @@ -19705,7 +17902,9 @@ def _is_item_specific_action(primary_target: dict, next_action: str) -> bool: return False -def _recommendation_quality_summary(label: str, reasons: list[str], trust_policy: str) -> str: +def _recommendation_quality_summary( + label: str, reasons: list[str], trust_policy: str +) -> str: reason = reasons[0] if reasons else "the current evidence is limited." if trust_policy == "verify-first": return ( @@ -19734,23 +17933,35 @@ def _adaptive_confidence_summary( exception_status = primary_target.get("trust_exception_status", "none") exception_pattern_status = primary_target.get("exception_pattern_status", "none") trust_recovery_status = primary_target.get("trust_recovery_status", "none") - exception_retirement_status = primary_target.get("exception_retirement_status", "none") + exception_retirement_status = primary_target.get( + "exception_retirement_status", "none" + ) policy_debt_status = primary_target.get("policy_debt_status", "none") - class_normalization_status = primary_target.get("class_normalization_status", "none") + class_normalization_status = primary_target.get( + "class_normalization_status", "none" + ) class_memory_freshness_status = primary_target.get( "class_memory_freshness_status", "insufficient-data" ) class_decay_status = primary_target.get("class_decay_status", "none") - class_trust_reweight_direction = primary_target.get("class_trust_reweight_direction", "neutral") - class_trust_reweight_effect = primary_target.get("class_trust_reweight_effect", "none") + class_trust_reweight_direction = primary_target.get( + "class_trust_reweight_direction", "neutral" + ) + class_trust_reweight_effect = primary_target.get( + "class_trust_reweight_effect", "none" + ) class_trust_momentum_status = primary_target.get( "class_trust_momentum_status", "insufficient-data" ) - class_reweight_stability_status = primary_target.get("class_reweight_stability_status", "watch") + class_reweight_stability_status = primary_target.get( + "class_reweight_stability_status", "watch" + ) class_reweight_transition_status = primary_target.get( "class_reweight_transition_status", "none" ) - class_transition_health_status = primary_target.get("class_transition_health_status", "none") + class_transition_health_status = primary_target.get( + "class_transition_health_status", "none" + ) class_transition_resolution_status = primary_target.get( "class_transition_resolution_status", "none" ) @@ -19777,9 +17988,7 @@ def _adaptive_confidence_summary( if transition_closure_likely_outcome == "expire-risk": return "The current pending class signal has lingered long enough that it is at risk of aging out." if transition_closure_likely_outcome == "blocked": - return ( - "Local target instability is still blocking this pending class signal from confirming." - ) + return "Local target instability is still blocking this pending class signal from confirming." if class_pending_debt_status == "active-debt": return "This class keeps accumulating unresolved pending states, so new pending signals there should be treated more cautiously." if class_pending_debt_status == "clearing": @@ -19791,9 +18000,7 @@ def _adaptive_confidence_summary( if class_transition_health_status == "building": return "The current pending class signal is still accumulating and may confirm if it stays consistent." if class_transition_health_status == "expired": - return ( - "An earlier pending class signal aged out, so the weaker class posture stays in place." - ) + return "An earlier pending class signal aged out, so the weaker class posture stays in place." if class_transition_health_status == "blocked": return "Local target instability is keeping a pending class strengthening attempt blocked." if class_reweight_transition_status == "confirmed-support": @@ -19809,13 +18016,9 @@ def _adaptive_confidence_summary( if class_reweight_stability_status == "oscillating": return "Class guidance is bouncing too much to strengthen safely right now, so keep the class signal visible but unconfirmed." if class_trust_momentum_status == "sustained-support": - return ( - "Fresh class evidence has stayed strong long enough to confirm broader normalization." - ) + return "Fresh class evidence has stayed strong long enough to confirm broader normalization." if class_trust_momentum_status == "sustained-caution": - return ( - "Caution-heavy class evidence has stayed strong long enough to confirm broader caution." - ) + return "Caution-heavy class evidence has stayed strong long enough to confirm broader caution." if class_trust_momentum_status == "building": return "Class evidence is trending in one direction, but it has not held long enough to lock in yet." if class_trust_momentum_status == "reversing": @@ -19833,9 +18036,7 @@ def _adaptive_confidence_summary( if class_trust_reweight_direction == "supporting-normalization": return "Fresh class evidence is consistently improving, but it is not yet strong enough to move the final posture by itself." if class_trust_reweight_direction == "supporting-caution": - return ( - "Recent class evidence is still caution-heavy enough to keep class trust conservative." - ) + return "Recent class evidence is still caution-heavy enough to keep class trust conservative." if class_decay_status == "normalization-decayed": return "Class normalization was pulled back because the class lesson is too old or too lightly refreshed to keep carrying the stronger posture." if class_decay_status == "policy-debt-decayed": @@ -19974,11 +18175,3 @@ def _trend_summary( f"{target_text}" ) return "The queue changed only lightly since the last run, with no clear worsening or recovery trend." - - -def _queue_identity(item: dict) -> str: - if item.get("item_id"): - return item["item_id"] - repo = item.get("repo", "") - title = item.get("title", "") - return f"{repo}:{title}" diff --git a/src/operator_trend_closure_forecast_freshness_controls.py b/src/operator_trend_closure_forecast_freshness_controls.py index 50e6c46..266292e 100644 --- a/src/operator_trend_closure_forecast_freshness_controls.py +++ b/src/operator_trend_closure_forecast_freshness_controls.py @@ -1,32 +1,33 @@ from __future__ import annotations -from typing import Any, Callable, Sequence +from typing import Any + +from src.operator_trend_support import ( + CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS, + CLASS_MEMORY_RECENCY_WEIGHTS, + HISTORY_WINDOW_RUNS, + normalized_closure_forecast_direction, + target_class_key, + target_specific_normalization_noise, +) def closure_forecast_freshness_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_event_has_evidence: Callable[[dict[str, Any]], bool], - closure_forecast_event_signal_label: Callable[[dict[str, Any]], str], - closure_forecast_event_is_confirmation_like: Callable[[dict[str, Any]], bool], - closure_forecast_event_is_clearance_like: Callable[[dict[str, Any]], bool], - class_memory_recency_weights: Sequence[float], - history_window_runs: int, - class_closure_forecast_freshness_window_runs: int, - freshness_status: Callable[[float, float], str], - freshness_reason: Callable[[str, float, float, float, float], str], - recent_signal_mix: Callable[[float, float, float, float], str], ) -> dict[str, Any]: class_key = target_class_key(target) - class_events = [event for event in closure_forecast_events if event.get("class_key") == class_key] + class_events = [ + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ] relevant_events: list[dict[str, Any]] = [] for event in class_events: if not closure_forecast_event_has_evidence(event): continue relevant_events.append(event) - if len(relevant_events) >= history_window_runs: + if len(relevant_events) >= HISTORY_WINDOW_RUNS: break weighted_forecast_evidence_count = 0.0 @@ -35,28 +36,34 @@ def closure_forecast_freshness_for_target( recent_forecast_weight = 0.0 recent_signals = [ closure_forecast_event_signal_label(event) - for event in relevant_events[:class_closure_forecast_freshness_window_runs] + for event in relevant_events[:CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS] ] for index, event in enumerate(relevant_events): - weight = class_memory_recency_weights[min(index, history_window_runs - 1)] + weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_forecast_evidence_count += weight - if index < class_closure_forecast_freshness_window_runs: + if index < CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS: recent_forecast_weight += weight if closure_forecast_event_is_confirmation_like(event): weighted_confirmation_like += weight if closure_forecast_event_is_clearance_like(event): weighted_clearance_like += weight - recent_window_weight_share = recent_forecast_weight / max(weighted_forecast_evidence_count, 1.0) - computed_freshness_status = freshness_status( + recent_window_weight_share = recent_forecast_weight / max( + weighted_forecast_evidence_count, 1.0 + ) + computed_freshness_status = closure_forecast_freshness_status( weighted_forecast_evidence_count, recent_window_weight_share, ) - decayed_confirmation_rate = weighted_confirmation_like / max(weighted_forecast_evidence_count, 1.0) - decayed_clearance_rate = weighted_clearance_like / max(weighted_forecast_evidence_count, 1.0) + decayed_confirmation_rate = weighted_confirmation_like / max( + weighted_forecast_evidence_count, 1.0 + ) + decayed_clearance_rate = weighted_clearance_like / max( + weighted_forecast_evidence_count, 1.0 + ) return { "closure_forecast_freshness_status": computed_freshness_status, - "closure_forecast_freshness_reason": freshness_reason( + "closure_forecast_freshness_reason": closure_forecast_freshness_reason( computed_freshness_status, weighted_forecast_evidence_count, recent_window_weight_share, @@ -66,7 +73,7 @@ def closure_forecast_freshness_for_target( "closure_forecast_memory_weight": round(recent_window_weight_share, 2), "decayed_confirmation_forecast_rate": round(decayed_confirmation_rate, 2), "decayed_clearance_forecast_rate": round(decayed_clearance_rate, 2), - "recent_closure_forecast_signal_mix": recent_signal_mix( + "recent_closure_forecast_signal_mix": recent_closure_forecast_signal_mix( weighted_forecast_evidence_count, weighted_confirmation_like, weighted_clearance_like, @@ -76,18 +83,16 @@ def closure_forecast_freshness_for_target( } -def closure_forecast_event_has_evidence( - event: dict[str, Any], - *, - normalized_closure_forecast_direction: Callable[[str, float], str], -) -> bool: +def closure_forecast_event_has_evidence(event: dict[str, Any]) -> bool: score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) direction = normalized_closure_forecast_direction( str(event.get("closure_forecast_reweight_direction", "neutral")), score, ) likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" - hysteresis_status = event.get("closure_forecast_hysteresis_status", "none") or "none" + hysteresis_status = ( + event.get("closure_forecast_hysteresis_status", "none") or "none" + ) return ( abs(score) >= 0.05 or direction in {"supporting-confirmation", "supporting-clearance"} @@ -102,11 +107,7 @@ def closure_forecast_event_has_evidence( ) -def closure_forecast_event_is_confirmation_like( - event: dict[str, Any], - *, - normalized_closure_forecast_direction: Callable[[str, float], str], -) -> bool: +def closure_forecast_event_is_confirmation_like(event: dict[str, Any]) -> bool: score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) direction = normalized_closure_forecast_direction( str(event.get("closure_forecast_reweight_direction", "neutral")), @@ -120,11 +121,7 @@ def closure_forecast_event_is_confirmation_like( ) -def closure_forecast_event_is_clearance_like( - event: dict[str, Any], - *, - normalized_closure_forecast_direction: Callable[[str, float], str], -) -> bool: +def closure_forecast_event_is_clearance_like(event: dict[str, Any]) -> bool: score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) direction = normalized_closure_forecast_direction( str(event.get("closure_forecast_reweight_direction", "neutral")), @@ -132,18 +129,14 @@ def closure_forecast_event_is_clearance_like( ) return ( direction == "supporting-clearance" - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} or event.get("closure_forecast_hysteresis_status", "none") in {"pending-clearance", "confirmed-clearance"} ) -def closure_forecast_event_signal_label( - event: dict[str, Any], - *, - closure_forecast_event_is_confirmation_like: Callable[[dict[str, Any]], bool], - closure_forecast_event_is_clearance_like: Callable[[dict[str, Any]], bool], -) -> str: +def closure_forecast_event_signal_label(event: dict[str, Any]) -> str: if closure_forecast_event_is_confirmation_like(event): return "confirmation-like" if closure_forecast_event_is_clearance_like(event): @@ -170,13 +163,11 @@ def closure_forecast_freshness_reason( recent_window_weight_share: float, decayed_confirmation_rate: float, decayed_clearance_rate: float, - *, - class_closure_forecast_freshness_window_runs: int, ) -> str: if freshness_status == "fresh": return ( "Recent closure-forecast evidence is still current enough to trust, with " - f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest {class_closure_forecast_freshness_window_runs} runs." + f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest {CLASS_CLOSURE_FORECAST_FRESHNESS_WINDOW_RUNS} runs." ) if freshness_status == "mixed-age": return ( @@ -225,9 +216,12 @@ def apply_closure_forecast_decay_control( policy_debt_reason: str, class_normalization_status: str, class_normalization_reason: str, - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], -) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: - freshness_status = freshness_meta.get("closure_forecast_freshness_status", "insufficient-data") +) -> tuple[ + str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str, str +]: + freshness_status = freshness_meta.get( + "closure_forecast_freshness_status", "insufficient-data" + ) decayed_clearance_rate = float( freshness_meta.get("decayed_clearance_forecast_rate", 0.0) or 0.0 ) @@ -238,9 +232,12 @@ def apply_closure_forecast_decay_control( if local_noise and ( direction == "supporting-confirmation" - or closure_hysteresis_status in {"pending-confirmation", "confirmed-confirmation"} + or closure_hysteresis_status + in {"pending-confirmation", "confirmed-confirmation"} ): - blocked_reason = "Local target instability still overrides closure-forecast freshness." + blocked_reason = ( + "Local target instability still overrides closure-forecast freshness." + ) if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": @@ -269,7 +266,10 @@ def apply_closure_forecast_decay_control( if ( resolution_status == "cleared" and reweight_effect == "clear-risk-strengthened" - and (freshness_status not in {"fresh", "mixed-age"} or decayed_clearance_rate < 0.50) + and ( + freshness_status not in {"fresh", "mixed-age"} + or decayed_clearance_rate < 0.50 + ) and recent_pending_status in {"pending-support", "pending-caution"} ): decay_reason = "The earlier forecast-driven clearance posture was pulled back because fresh unresolved pending-debt support is no longer strong enough." @@ -281,7 +281,9 @@ def apply_closure_forecast_decay_control( closure_hysteresis_status = "none" closure_hysteresis_reason = decay_reason if recent_pending_status == "pending-support": - trust_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + trust_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) trust_policy_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason ) @@ -357,7 +359,9 @@ def apply_closure_forecast_decay_control( if closure_hysteresis_status == "confirmed-clearance": decay_reason = "Stronger clearance wording was pulled back because fresh unresolved pending-debt support is no longer strong enough." - softened_outcome = "clear-risk" if closure_likely_outcome == "expire-risk" else "hold" + softened_outcome = ( + "clear-risk" if closure_likely_outcome == "expire-risk" else "hold" + ) return ( "clearance-decayed", decay_reason, @@ -402,7 +406,9 @@ def apply_closure_forecast_decay_control( if closure_hysteresis_status == "pending-clearance": decay_reason = "Older clearance-leaning forecast memory is no longer fresh enough to keep stronger carry-forward in place." - softened_outcome = "clear-risk" if closure_likely_outcome == "expire-risk" else "hold" + softened_outcome = ( + "clear-risk" if closure_likely_outcome == "expire-risk" else "hold" + ) return ( "clearance-decayed", decay_reason, @@ -448,7 +454,6 @@ def closure_forecast_freshness_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -464,11 +469,15 @@ def closure_forecast_freshness_hotspots( "decayed_confirmation_forecast_rate": target.get( "decayed_confirmation_forecast_rate", 0.0 ), - "decayed_clearance_forecast_rate": target.get("decayed_clearance_forecast_rate", 0.0), + "decayed_clearance_forecast_rate": target.get( + "decayed_clearance_forecast_rate", 0.0 + ), "recent_closure_forecast_signal_mix": target.get( "recent_closure_forecast_signal_mix", "" ), - "recent_closure_forecast_path": target.get("recent_closure_forecast_path", ""), + "recent_closure_forecast_path": target.get( + "recent_closure_forecast_path", "" + ), "dominant_count": max( float(target.get("decayed_confirmation_forecast_rate", 0.0) or 0.0), float(target.get("decayed_clearance_forecast_rate", 0.0) or 0.0), @@ -476,7 +485,9 @@ def closure_forecast_freshness_hotspots( "forecast_event_count": len( [ part - for part in (target.get("recent_closure_forecast_path", "") or "").split(" -> ") + for part in ( + target.get("recent_closure_forecast_path", "") or "" + ).split(" -> ") if part ] ), diff --git a/src/operator_trend_closure_forecast_reacquisition_controls.py b/src/operator_trend_closure_forecast_reacquisition_controls.py index a4b4dac..0454d92 100644 --- a/src/operator_trend_closure_forecast_reacquisition_controls.py +++ b/src/operator_trend_closure_forecast_reacquisition_controls.py @@ -1,12 +1,30 @@ from __future__ import annotations -from typing import Any, Callable, Sequence +from typing import Any + +from src.operator_trend_closure_forecast_freshness_controls import ( + closure_forecast_event_has_evidence, + closure_forecast_freshness_status, +) +from src.operator_trend_support import ( + CLASS_CLOSURE_FORECAST_REFRESH_WINDOW_RUNS, + CLASS_MEMORY_RECENCY_WEIGHTS, + CLASS_REACQUISITION_FRESHNESS_WINDOW_RUNS, + CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS, + HISTORY_WINDOW_RUNS, + clamp_round, + class_direction_flip_count, + closure_forecast_direction_majority, + closure_forecast_direction_reversing, + normalized_closure_forecast_direction, + target_class_key, + target_label, + target_specific_normalization_noise, +) def closure_forecast_refresh_signal_from_event( event: dict[str, Any], - *, - normalized_closure_forecast_direction: Callable[[str, float], str], ) -> float: score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) direction = normalized_closure_forecast_direction( @@ -18,7 +36,9 @@ def closure_forecast_refresh_signal_from_event( "mixed-age": 0.60, "stale": 0.25, "insufficient-data": 0.10, - }.get(str(event.get("closure_forecast_freshness_status", "insufficient-data")), 0.10) + }.get( + str(event.get("closure_forecast_freshness_status", "insufficient-data")), 0.10 + ) signal_strength = max(abs(score), 0.05) if direction != "neutral" else 0.0 if direction == "supporting-confirmation": return signal_strength * freshness_factor @@ -34,7 +54,9 @@ def recent_closure_forecast_weakened_side(events: list[dict[str, Any]]) -> str: event.get("closure_forecast_freshness_status", "insufficient-data") or "insufficient-data" ) - hysteresis_status = str(event.get("closure_forecast_hysteresis_status", "none") or "none") + hysteresis_status = str( + event.get("closure_forecast_hysteresis_status", "none") or "none" + ) if decay_status == "confirmation-decayed" or ( freshness_status in {"stale", "insufficient-data"} and hysteresis_status in {"pending-confirmation", "confirmed-confirmation"} @@ -50,15 +72,14 @@ def recent_closure_forecast_weakened_side(events: list[dict[str, Any]]) -> str: def closure_forecast_refresh_path_label( event: dict[str, Any], - *, - normalized_closure_forecast_direction: Callable[[str, float], str], ) -> str: direction = normalized_closure_forecast_direction( str(event.get("closure_forecast_reweight_direction", "neutral")), float(event.get("closure_forecast_reweight_score", 0.0) or 0.0), ) freshness = str( - event.get("closure_forecast_freshness_status", "insufficient-data") or "insufficient-data" + event.get("closure_forecast_freshness_status", "insufficient-data") + or "insufficient-data" ) if direction == "supporting-confirmation": return f"{freshness} confirmation" @@ -71,23 +92,13 @@ def closure_forecast_refresh_recovery_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_event_has_evidence: Callable[[dict[str, Any]], bool], - normalized_closure_forecast_direction: Callable[[str, float], str], - closure_forecast_refresh_signal_from_event: Callable[[dict[str, Any]], float], - clamp_round: Callable[[float, float, float], float], - closure_forecast_direction_majority: Callable[[list[str]], str], - recent_closure_forecast_weakened_side: Callable[[list[dict[str, Any]]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_refresh_path_label: Callable[[dict[str, Any]], str], - class_closure_forecast_refresh_window_runs: int, ) -> dict[str, Any]: class_key = target_class_key(target) matching_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key - ][:class_closure_forecast_refresh_window_runs] + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ][:CLASS_CLOSURE_FORECAST_REFRESH_WINDOW_RUNS] relevant_events = [ event for event in matching_events if closure_forecast_event_has_evidence(event) ] @@ -101,19 +112,25 @@ def closure_forecast_refresh_recovery_for_target( weighted_total = 0.0 weight_sum = 0.0 for index, event in enumerate(matching_events): - weight = (1.0, 0.8, 0.6, 0.4)[min(index, class_closure_forecast_refresh_window_runs - 1)] + weight = (1.0, 0.8, 0.6, 0.4)[ + min(index, CLASS_CLOSURE_FORECAST_REFRESH_WINDOW_RUNS - 1) + ] weighted_total += closure_forecast_refresh_signal_from_event(event) * weight weight_sum += weight refresh_recovery_score = clamp_round( weighted_total / max(weight_sum, 1.0), - -0.95, - 0.95, + lower=-0.95, + upper=0.95, ) current_direction = directions[0] if directions else "neutral" earlier_majority = closure_forecast_direction_majority(directions[1:]) recent_weakened = recent_closure_forecast_weakened_side(matching_events) - freshness_status = str(target.get("closure_forecast_freshness_status", "insufficient-data")) - momentum_status = str(target.get("closure_forecast_momentum_status", "insufficient-data")) + freshness_status = str( + target.get("closure_forecast_freshness_status", "insufficient-data") + ) + momentum_status = str( + target.get("closure_forecast_momentum_status", "insufficient-data") + ) stability_status = str(target.get("closure_forecast_stability_status", "watch")) local_noise = target_specific_normalization_noise(target, transition_history_meta) @@ -122,8 +139,14 @@ def closure_forecast_refresh_recovery_for_target( elif local_noise and current_direction == "supporting-confirmation": refresh_recovery_status = "blocked" elif ( - (recent_weakened == "confirmation" and current_direction == "supporting-clearance") - or (recent_weakened == "clearance" and current_direction == "supporting-confirmation") + ( + recent_weakened == "confirmation" + and current_direction == "supporting-clearance" + ) + or ( + recent_weakened == "clearance" + and current_direction == "supporting-confirmation" + ) or closure_forecast_direction_reversing(current_direction, earlier_majority) ): refresh_recovery_status = "reversing" @@ -162,9 +185,7 @@ def closure_forecast_refresh_recovery_for_target( if local_noise and current_direction == "supporting-confirmation": reacquisition_status = "blocked" - reacquisition_reason = ( - "Local target instability is still preventing positive confirmation-side reacquisition." - ) + reacquisition_reason = "Local target instability is still preventing positive confirmation-side reacquisition." elif ( refresh_recovery_status == "reacquiring-confirmation" and freshness_status == "fresh" @@ -188,7 +209,10 @@ def closure_forecast_refresh_recovery_for_target( "Fresh clearance-side pressure has stayed strong enough to earn back stronger " "clearance forecasting." ) - elif refresh_recovery_status in {"recovering-confirmation", "reacquiring-confirmation"}: + elif refresh_recovery_status in { + "recovering-confirmation", + "reacquiring-confirmation", + }: reacquisition_status = "pending-confirmation-reacquisition" reacquisition_reason = ( "Fresh confirmation-side forecast evidence is returning, but it has not fully " @@ -216,7 +240,9 @@ def closure_forecast_refresh_recovery_for_target( "closure_forecast_reacquisition_status": reacquisition_status, "closure_forecast_reacquisition_reason": reacquisition_reason, "recent_closure_forecast_refresh_path": " -> ".join( - closure_forecast_refresh_path_label(event) for event in matching_events if event + closure_forecast_refresh_path_label(event) + for event in matching_events + if event ), "recent_weakened_side": recent_weakened, } @@ -243,13 +269,23 @@ def apply_closure_forecast_reacquisition_control( closure_hysteresis_status: str, closure_hysteresis_reason: str, ) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: - refresh_status = str(refresh_meta.get("closure_forecast_refresh_recovery_status", "none")) - reacquisition_status = str(refresh_meta.get("closure_forecast_reacquisition_status", "none")) - reacquisition_reason = str(refresh_meta.get("closure_forecast_reacquisition_reason", "")) + refresh_status = str( + refresh_meta.get("closure_forecast_refresh_recovery_status", "none") + ) + reacquisition_status = str( + refresh_meta.get("closure_forecast_reacquisition_status", "none") + ) + reacquisition_reason = str( + refresh_meta.get("closure_forecast_reacquisition_reason", "") + ) recent_weakened_side = str(refresh_meta.get("recent_weakened_side", "none")) - freshness_status = str(target.get("closure_forecast_freshness_status", "insufficient-data")) + freshness_status = str( + target.get("closure_forecast_freshness_status", "insufficient-data") + ) stability_status = str(target.get("closure_forecast_stability_status", "watch")) - decayed_clearance_rate = float(target.get("decayed_clearance_forecast_rate", 0.0) or 0.0) + decayed_clearance_rate = float( + target.get("decayed_clearance_forecast_rate", 0.0) or 0.0 + ) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) if reacquisition_status == "reacquired-confirmation": @@ -282,14 +318,18 @@ def apply_closure_forecast_reacquisition_control( transition_status = "none" transition_reason = clear_reason if target.get("class_reweight_transition_status") == "pending-support": - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) reverted_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason, ) trust_policy = str(reverted_policy) trust_policy_reason = ( - clear_reason if reverted_policy == "verify-first" else str(reverted_reason) + clear_reason + if reverted_policy == "verify-first" + else str(reverted_reason) ) class_normalization_status = "candidate" class_normalization_reason = clear_reason @@ -307,9 +347,10 @@ def apply_closure_forecast_reacquisition_control( elif refresh_status == "reversing": closure_hysteresis_reason = reacquisition_reason or closure_hysteresis_reason - if freshness_status in {"stale", "insufficient-data"} and reacquisition_status.startswith( - "reacquired" - ): + if freshness_status in { + "stale", + "insufficient-data", + } and reacquisition_status.startswith("reacquired"): if reacquisition_status == "reacquired-confirmation": closure_likely_outcome = "hold" closure_hysteresis_status = "pending-confirmation" @@ -342,7 +383,6 @@ def closure_forecast_refresh_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -413,12 +453,12 @@ def closure_forecast_refresh_recovery_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str(primary_target.get("closure_forecast_refresh_recovery_status", "none")) - score = float(primary_target.get("closure_forecast_refresh_recovery_score", 0.0) or 0.0) + score = float( + primary_target.get("closure_forecast_refresh_recovery_score", 0.0) or 0.0 + ) if status == "recovering-confirmation": return ( f"Fresh confirmation-side forecast evidence is returning for {label}, but it has " @@ -470,8 +510,6 @@ def closure_forecast_reacquisition_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str(primary_target.get("closure_forecast_reacquisition_status", "none")) @@ -524,7 +562,9 @@ def closure_forecast_reacquisition_summary( def closure_forecast_reacquisition_side_from_event(event: dict[str, Any]) -> str: - reacquisition_status = str(event.get("closure_forecast_reacquisition_status", "none") or "none") + reacquisition_status = str( + event.get("closure_forecast_reacquisition_status", "none") or "none" + ) if reacquisition_status in { "pending-confirmation-reacquisition", "reacquired-confirmation", @@ -535,7 +575,9 @@ def closure_forecast_reacquisition_side_from_event(event: dict[str, Any]) -> str "reacquired-clearance", }: return "clearance" - refresh_status = str(event.get("closure_forecast_refresh_recovery_status", "none") or "none") + refresh_status = str( + event.get("closure_forecast_refresh_recovery_status", "none") or "none" + ) if refresh_status in {"recovering-confirmation", "reacquiring-confirmation"}: return "confirmation" if refresh_status in {"recovering-clearance", "reacquiring-clearance"}: @@ -565,7 +607,9 @@ def closure_forecast_reacquisition_path_label(event: dict[str, Any]) -> str: status = str(event.get("closure_forecast_reacquisition_status", "none") or "none") if status != "none": return status - likely_outcome = str(event.get("transition_closure_likely_outcome", "none") or "none") + likely_outcome = str( + event.get("transition_closure_likely_outcome", "none") or "none" + ) if likely_outcome != "none": return likely_outcome return "hold" @@ -575,20 +619,14 @@ def closure_forecast_reacquisition_persistence_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_reacquisition_side_from_event: Callable[[dict[str, Any]], str], - clamp_round: Callable[[float, float, float], float], - closure_forecast_direction_majority: Callable[[list[str]], str], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_reacquisition_path_label: Callable[[dict[str, Any]], str], - class_reacquisition_persistence_window_runs: int, ) -> dict[str, Any]: del transition_history_meta class_key = target_class_key(target) matching_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key - ][:class_reacquisition_persistence_window_runs] + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ][:CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS] relevant_events = [ event for event in matching_events @@ -609,9 +647,11 @@ def closure_forecast_reacquisition_persistence_for_target( weighted_total = 0.0 weight_sum = 0.0 sides: list[str] = [] - for index, event in enumerate(relevant_events[:class_reacquisition_persistence_window_runs]): + for index, event in enumerate( + relevant_events[:CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS] + ): weight = (1.0, 0.8, 0.6, 0.4)[ - min(index, class_reacquisition_persistence_window_runs - 1) + min(index, CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS - 1) ] event_side = closure_forecast_reacquisition_side_from_event(event) sign = 1.0 if event_side == "confirmation" else -1.0 @@ -622,15 +662,19 @@ def closure_forecast_reacquisition_persistence_for_target( "reacquired-clearance", }: magnitude += 0.15 - momentum_status = str(event.get("closure_forecast_momentum_status", "insufficient-data")) - if (event_side == "confirmation" and momentum_status == "sustained-confirmation") or ( - event_side == "clearance" and momentum_status == "sustained-clearance" - ): + momentum_status = str( + event.get("closure_forecast_momentum_status", "insufficient-data") + ) + if ( + event_side == "confirmation" and momentum_status == "sustained-confirmation" + ) or (event_side == "clearance" and momentum_status == "sustained-clearance"): magnitude += 0.10 stability_status = str(event.get("closure_forecast_stability_status", "watch")) if stability_status == "stable": magnitude += 0.10 - freshness_status = str(event.get("closure_forecast_freshness_status", "insufficient-data")) + freshness_status = str( + event.get("closure_forecast_freshness_status", "insufficient-data") + ) if freshness_status == "fresh": magnitude += 0.10 elif freshness_status == "mixed-age": @@ -644,10 +688,18 @@ def closure_forecast_reacquisition_persistence_for_target( weighted_total += sign * magnitude * weight weight_sum += weight - persistence_score = clamp_round(weighted_total / max(weight_sum, 1.0), -0.95, 0.95) - current_momentum_status = str(target.get("closure_forecast_momentum_status", "insufficient-data")) - current_stability_status = str(target.get("closure_forecast_stability_status", "watch")) - current_freshness_status = str(target.get("closure_forecast_freshness_status", "insufficient-data")) + persistence_score = clamp_round( + weighted_total / max(weight_sum, 1.0), lower=-0.95, upper=0.95 + ) + current_momentum_status = str( + target.get("closure_forecast_momentum_status", "insufficient-data") + ) + current_stability_status = str( + target.get("closure_forecast_stability_status", "watch") + ) + current_freshness_status = str( + target.get("closure_forecast_freshness_status", "insufficient-data") + ) earlier_majority = closure_forecast_direction_majority(sides[1:]) current_direction = ( "supporting-confirmation" @@ -689,17 +741,23 @@ def closure_forecast_reacquisition_persistence_for_target( and current_stability_status != "oscillating" ): persistence_status = "sustained-clearance" - elif current_side == "confirmation" and persistence_age_runs >= 2 and persistence_score > 0: + elif ( + current_side == "confirmation" + and persistence_age_runs >= 2 + and persistence_score > 0 + ): persistence_status = "holding-confirmation" - elif current_side == "clearance" and persistence_age_runs >= 2 and persistence_score < 0: + elif ( + current_side == "clearance" + and persistence_age_runs >= 2 + and persistence_score < 0 + ): persistence_status = "holding-clearance" else: persistence_status = "none" if persistence_status == "just-reacquired": - persistence_reason = ( - "Stronger closure-forecast posture has returned, but it has not yet proved it can hold." - ) + persistence_reason = "Stronger closure-forecast posture has returned, but it has not yet proved it can hold." elif persistence_status == "holding-confirmation": persistence_reason = ( "Confirmation-side recovery has stayed aligned long enough to keep the restored " @@ -721,9 +779,7 @@ def closure_forecast_reacquisition_persistence_for_target( "the restored caution more." ) elif persistence_status == "reversing": - persistence_reason = ( - "The restored forecast posture is already weakening, so it is being softened again." - ) + persistence_reason = "The restored forecast posture is already weakening, so it is being softened again." elif persistence_status == "insufficient-data": persistence_reason = ( "Reacquisition is still too lightly exercised to say whether the restored forecast " @@ -738,7 +794,9 @@ def closure_forecast_reacquisition_persistence_for_target( "closure_forecast_reacquisition_persistence_status": persistence_status, "closure_forecast_reacquisition_persistence_reason": persistence_reason, "recent_reacquisition_persistence_path": " -> ".join( - closure_forecast_reacquisition_path_label(event) for event in matching_events if event + closure_forecast_reacquisition_path_label(event) + for event in matching_events + if event ), } @@ -747,19 +805,13 @@ def closure_forecast_recovery_churn_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_reacquisition_side_from_event: Callable[[dict[str, Any]], str], - class_direction_flip_count: Callable[[list[str]], int], - clamp_round: Callable[[float, float, float], float], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_reacquisition_path_label: Callable[[dict[str, Any]], str], - class_reacquisition_persistence_window_runs: int, ) -> dict[str, Any]: class_key = target_class_key(target) matching_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key - ][:class_reacquisition_persistence_window_runs] + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ][:CLASS_REACQUISITION_PERSISTENCE_WINDOW_RUNS] side_path = [ closure_forecast_reacquisition_side_from_event(event) for event in matching_events @@ -774,13 +826,17 @@ def closure_forecast_recovery_churn_for_target( else: flip_count = class_direction_flip_count( [ - "supporting-confirmation" if side == "confirmation" else "supporting-clearance" + "supporting-confirmation" + if side == "confirmation" + else "supporting-clearance" for side in side_path ] ) churn_score = float(flip_count) * 0.20 stability_status = str(target.get("closure_forecast_stability_status", "watch")) - momentum_status = str(target.get("closure_forecast_momentum_status", "insufficient-data")) + momentum_status = str( + target.get("closure_forecast_momentum_status", "insufficient-data") + ) if stability_status == "oscillating": churn_score += 0.15 if momentum_status == "reversing": @@ -792,7 +848,8 @@ def closure_forecast_recovery_churn_for_target( for event in matching_events ] if any( - previous == "fresh" and current in {"mixed-age", "stale", "insufficient-data"} + previous == "fresh" + and current in {"mixed-age", "stale", "insufficient-data"} for previous, current in zip(freshness_path, freshness_path[1:]) ): churn_score += 0.10 @@ -801,18 +858,20 @@ def closure_forecast_recovery_churn_for_target( if ( len(side_path) >= 2 and side_path[0] == side_path[1] - and matching_events[0].get("closure_forecast_freshness_status", "insufficient-data") + and matching_events[0].get( + "closure_forecast_freshness_status", "insufficient-data" + ) == "fresh" - and matching_events[1].get("closure_forecast_freshness_status", "insufficient-data") + and matching_events[1].get( + "closure_forecast_freshness_status", "insufficient-data" + ) == "fresh" ): churn_score -= 0.10 - churn_score = clamp_round(churn_score, 0.0, 0.95) + churn_score = clamp_round(churn_score, lower=0.0, upper=0.95) if local_noise and current_side == "confirmation": churn_status = "blocked" - churn_reason = ( - "Local target instability is preventing positive confirmation-side persistence." - ) + churn_reason = "Local target instability is preventing positive confirmation-side persistence." elif churn_score >= 0.45 or flip_count >= 2: churn_status = "churn" churn_reason = ( @@ -821,7 +880,9 @@ def closure_forecast_recovery_churn_for_target( ) elif churn_score >= 0.20: churn_status = "watch" - churn_reason = "Recovery is wobbling and may lose its restored strength soon." + churn_reason = ( + "Recovery is wobbling and may lose its restored strength soon." + ) else: churn_status = "none" churn_reason = "" @@ -830,7 +891,9 @@ def closure_forecast_recovery_churn_for_target( "closure_forecast_recovery_churn_status": churn_status, "closure_forecast_recovery_churn_reason": churn_reason, "recent_recovery_churn_path": " -> ".join( - closure_forecast_reacquisition_path_label(event) for event in matching_events if event + closure_forecast_reacquisition_path_label(event) + for event in matching_events + if event ), } @@ -858,17 +921,25 @@ def apply_reacquisition_persistence_and_churn_control( closure_hysteresis_reason: str, ) -> tuple[str, str, str, str, str, str, str, str, str, str, str, str, str, str, str]: persistence_status = str( - persistence_meta.get("closure_forecast_reacquisition_persistence_status", "none") + persistence_meta.get( + "closure_forecast_reacquisition_persistence_status", "none" + ) ) persistence_reason = str( persistence_meta.get("closure_forecast_reacquisition_persistence_reason", "") ) churn_status = str(churn_meta.get("closure_forecast_recovery_churn_status", "none")) churn_reason = str(churn_meta.get("closure_forecast_recovery_churn_reason", "")) - current_reacquisition_status = str(target.get("closure_forecast_reacquisition_status", "none")) - current_freshness_status = str(target.get("closure_forecast_freshness_status", "insufficient-data")) + current_reacquisition_status = str( + target.get("closure_forecast_reacquisition_status", "none") + ) + current_freshness_status = str( + target.get("closure_forecast_freshness_status", "insufficient-data") + ) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) if churn_status == "blocked": closure_likely_outcome = "hold" @@ -1006,7 +1077,9 @@ def apply_reacquisition_persistence_and_churn_control( ) trust_policy = str(reverted_policy) trust_policy_reason = ( - restore_reason if reverted_policy == "verify-first" else str(reverted_reason) + restore_reason + if reverted_policy == "verify-first" + else str(reverted_reason) ) class_normalization_status = "candidate" class_normalization_reason = restore_reason @@ -1039,7 +1112,6 @@ def closure_forecast_reacquisition_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -1078,7 +1150,9 @@ def closure_forecast_reacquisition_hotspots( existing = grouped.get(class_key) if existing is None or abs( float(current["closure_forecast_reacquisition_persistence_score"] or 0.0) - ) > abs(float(existing["closure_forecast_reacquisition_persistence_score"] or 0.0)): + ) > abs( + float(existing["closure_forecast_reacquisition_persistence_score"] or 0.0) + ): grouped[class_key] = current hotspots = list(grouped.values()) @@ -1086,12 +1160,20 @@ def closure_forecast_reacquisition_hotspots( hotspots = [ item for item in hotspots - if item.get("closure_forecast_reacquisition_persistence_status") == "just-reacquired" + if item.get("closure_forecast_reacquisition_persistence_status") + == "just-reacquired" ] hotspots.sort( key=lambda item: ( -int(item.get("closure_forecast_reacquisition_age_runs", 0) or 0), - -abs(float(item.get("closure_forecast_reacquisition_persistence_score", 0.0) or 0.0)), + -abs( + float( + item.get( + "closure_forecast_reacquisition_persistence_score", 0.0 + ) + or 0.0 + ) + ), str(item.get("label", "")), ) ) @@ -1110,7 +1192,14 @@ def closure_forecast_reacquisition_hotspots( hotspots.sort( key=lambda item: ( -int(item.get("closure_forecast_reacquisition_age_runs", 0) or 0), - -abs(float(item.get("closure_forecast_reacquisition_persistence_score", 0.0) or 0.0)), + -abs( + float( + item.get( + "closure_forecast_reacquisition_persistence_score", 0.0 + ) + or 0.0 + ) + ), str(item.get("label", "")), ) ) @@ -1118,7 +1207,8 @@ def closure_forecast_reacquisition_hotspots( hotspots = [ item for item in hotspots - if item.get("closure_forecast_recovery_churn_status") in {"watch", "churn", "blocked"} + if item.get("closure_forecast_recovery_churn_status") + in {"watch", "churn", "blocked"} ] hotspots.sort( key=lambda item: ( @@ -1134,13 +1224,18 @@ def closure_forecast_reacquisition_persistence_summary( primary_target: dict[str, Any], just_reacquired_hotspots: list[dict[str, Any]], holding_reacquisition_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" - status = str(primary_target.get("closure_forecast_reacquisition_persistence_status", "none")) - age_runs = int(primary_target.get("closure_forecast_reacquisition_age_runs", 0) or 0) - score = float(primary_target.get("closure_forecast_reacquisition_persistence_score", 0.0) or 0.0) + status = str( + primary_target.get("closure_forecast_reacquisition_persistence_status", "none") + ) + age_runs = int( + primary_target.get("closure_forecast_reacquisition_age_runs", 0) or 0 + ) + score = float( + primary_target.get("closure_forecast_reacquisition_persistence_score", 0.0) + or 0.0 + ) if status == "just-reacquired": return ( f"{label} has only just re-earned stronger closure-forecast posture, so it is still " @@ -1196,12 +1291,12 @@ def closure_forecast_reacquisition_persistence_summary( def closure_forecast_recovery_churn_summary( primary_target: dict[str, Any], recovery_churn_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str(primary_target.get("closure_forecast_recovery_churn_status", "none")) - score = float(primary_target.get("closure_forecast_recovery_churn_score", 0.0) or 0.0) + score = float( + primary_target.get("closure_forecast_recovery_churn_score", 0.0) or 0.0 + ) if status == "watch": return ( f"Recovery for {label} is wobbling enough that restored forecast strength may " @@ -1229,7 +1324,6 @@ def closure_forecast_recovery_churn_summary( return "No meaningful recovery churn is active right now." - def reacquisition_event_is_confirmation_like(event: dict[str, Any]) -> bool: return ( event.get("closure_forecast_reacquisition_status", "none") @@ -1250,16 +1344,12 @@ def reacquisition_event_is_clearance_like(event: dict[str, Any]) -> bool: in {"holding-clearance", "sustained-clearance"} or event.get("closure_forecast_hysteresis_status", "none") in {"pending-clearance", "confirmed-clearance"} - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} ) -def reacquisition_event_has_evidence( - event: dict[str, Any], - *, - reacquisition_event_is_confirmation_like: Callable[[dict[str, Any]], bool], - reacquisition_event_is_clearance_like: Callable[[dict[str, Any]], bool], -) -> bool: +def reacquisition_event_has_evidence(event: dict[str, Any]) -> bool: return ( reacquisition_event_is_confirmation_like(event) or reacquisition_event_is_clearance_like(event) @@ -1268,12 +1358,7 @@ def reacquisition_event_has_evidence( ) -def reacquisition_event_signal_label( - event: dict[str, Any], - *, - reacquisition_event_is_confirmation_like: Callable[[dict[str, Any]], bool], - reacquisition_event_is_clearance_like: Callable[[dict[str, Any]], bool], -) -> str: +def reacquisition_event_signal_label(event: dict[str, Any]) -> str: if reacquisition_event_is_confirmation_like(event): return "confirmation-like" if reacquisition_event_is_clearance_like(event): @@ -1287,14 +1372,12 @@ def closure_forecast_reacquisition_freshness_reason( recent_window_weight_share: float, decayed_confirmation_rate: float, decayed_clearance_rate: float, - *, - class_reacquisition_freshness_window_runs: int, ) -> str: if freshness_status == "fresh": return ( "Recent reacquired closure-forecast evidence is still current enough to trust, with " f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest " - f"{class_reacquisition_freshness_window_runs} runs." + f"{CLASS_REACQUISITION_FRESHNESS_WINDOW_RUNS} runs." ) if freshness_status == "mixed-age": return ( @@ -1332,29 +1415,19 @@ def recent_reacquisition_signal_mix( def closure_forecast_reacquisition_freshness_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], - *, - target_class_key: Callable[[dict[str, Any]], str], - reacquisition_event_has_evidence: Callable[[dict[str, Any]], bool], - reacquisition_event_signal_label: Callable[[dict[str, Any]], str], - closure_forecast_reacquisition_side_from_status: Callable[[str], str], - closure_forecast_reacquisition_side_from_event: Callable[[dict[str, Any]], str], - class_memory_recency_weights: Sequence[float], - history_window_runs: int, - class_reacquisition_freshness_window_runs: int, - freshness_status: Callable[[float, float], str], - freshness_reason: Callable[[str, float, float, float, float], str], - recent_signal_mix: Callable[[float, float, float, float], str], - reacquisition_event_is_confirmation_like: Callable[[dict[str, Any]], bool], - reacquisition_event_is_clearance_like: Callable[[dict[str, Any]], bool], ) -> dict[str, Any]: class_key = target_class_key(target) - class_events = [event for event in closure_forecast_events if event.get("class_key") == class_key] + class_events = [ + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ] relevant_events: list[dict[str, Any]] = [] for event in class_events: if not reacquisition_event_has_evidence(event): continue relevant_events.append(event) - if len(relevant_events) >= history_window_runs: + if len(relevant_events) >= HISTORY_WINDOW_RUNS: break weighted_reacquisition_evidence_count = 0.0 @@ -1363,7 +1436,7 @@ def closure_forecast_reacquisition_freshness_for_target( recent_reacquisition_weight = 0.0 recent_signals = [ reacquisition_event_signal_label(event) - for event in relevant_events[:class_reacquisition_freshness_window_runs] + for event in relevant_events[:CLASS_REACQUISITION_FRESHNESS_WINDOW_RUNS] ] current_side = closure_forecast_reacquisition_side_from_status( str(target.get("closure_forecast_reacquisition_persistence_status", "none")) @@ -1383,10 +1456,13 @@ def closure_forecast_reacquisition_freshness_for_target( ) for index, event in enumerate(relevant_events): - weight = class_memory_recency_weights[min(index, history_window_runs - 1)] + weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_reacquisition_evidence_count += weight event_side = closure_forecast_reacquisition_side_from_event(event) - if index < class_reacquisition_freshness_window_runs and event_side == current_side: + if ( + index < CLASS_REACQUISITION_FRESHNESS_WINDOW_RUNS + and event_side == current_side + ): recent_reacquisition_weight += weight if reacquisition_event_is_confirmation_like(event): weighted_confirmation_like += weight @@ -1397,7 +1473,7 @@ def closure_forecast_reacquisition_freshness_for_target( weighted_reacquisition_evidence_count, 1.0, ) - computed_freshness_status = freshness_status( + computed_freshness_status = closure_forecast_freshness_status( weighted_reacquisition_evidence_count, recent_window_weight_share, ) @@ -1411,17 +1487,19 @@ def closure_forecast_reacquisition_freshness_for_target( ) return { "closure_forecast_reacquisition_freshness_status": computed_freshness_status, - "closure_forecast_reacquisition_freshness_reason": freshness_reason( + "closure_forecast_reacquisition_freshness_reason": closure_forecast_reacquisition_freshness_reason( computed_freshness_status, weighted_reacquisition_evidence_count, recent_window_weight_share, decayed_confirmation_rate, decayed_clearance_rate, ), - "closure_forecast_reacquisition_memory_weight": round(recent_window_weight_share, 2), + "closure_forecast_reacquisition_memory_weight": round( + recent_window_weight_share, 2 + ), "decayed_reacquired_confirmation_rate": round(decayed_confirmation_rate, 2), "decayed_reacquired_clearance_rate": round(decayed_clearance_rate, 2), - "recent_reacquisition_signal_mix": recent_signal_mix( + "recent_reacquisition_signal_mix": recent_reacquisition_signal_mix( weighted_reacquisition_evidence_count, weighted_confirmation_like, weighted_clearance_like, @@ -1429,7 +1507,8 @@ def closure_forecast_reacquisition_freshness_for_target( ), "recent_reacquisition_signal_path": " -> ".join(recent_signals), "has_fresh_aligned_recent_evidence": any( - event.get("closure_forecast_freshness_status", "insufficient-data") == "fresh" + event.get("closure_forecast_freshness_status", "insufficient-data") + == "fresh" and closure_forecast_reacquisition_side_from_event(event) == current_side for event in relevant_events[:2] ), @@ -1462,9 +1541,6 @@ def apply_reacquisition_freshness_reset_control( persistence_score: float, persistence_status: str, persistence_reason: str, - closure_forecast_reacquisition_side_from_status: Callable[[str], str], - closure_forecast_reacquisition_side_from_event: Callable[[dict[str, Any]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], ) -> dict[str, Any]: freshness_status = freshness_meta.get( "closure_forecast_reacquisition_freshness_status", @@ -1516,14 +1592,18 @@ def restore_weaker_pending_posture( restored_resolution_status = "none" restored_resolution_reason = "" if recent_pending_status == "pending-support": - reverted_policy = target.get("pre_class_normalization_trust_policy", trust_policy) + reverted_policy = target.get( + "pre_class_normalization_trust_policy", trust_policy + ) reverted_reason = target.get( "pre_class_normalization_trust_policy_reason", trust_policy_reason, ) next_trust_policy = str(reverted_policy) next_trust_policy_reason = ( - reset_reason if reverted_policy == "verify-first" else str(reverted_reason) + reset_reason + if reverted_policy == "verify-first" + else str(reverted_reason) ) next_class_normalization_status = "candidate" next_class_normalization_reason = reset_reason @@ -1548,7 +1628,9 @@ def restore_weaker_pending_posture( ) if local_noise and current_side != "none": - blocked_reason = "Local target instability still overrides healthy reacquisition freshness." + blocked_reason = ( + "Local target instability still overrides healthy reacquisition freshness." + ) if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" elif closure_likely_outcome == "expire-risk": @@ -1856,7 +1938,6 @@ def closure_forecast_reacquisition_freshness_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -1878,7 +1959,9 @@ def closure_forecast_reacquisition_freshness_hotspots( "decayed_reacquired_clearance_rate", 0.0, ), - "recent_reacquisition_signal_mix": target.get("recent_reacquisition_signal_mix", ""), + "recent_reacquisition_signal_mix": target.get( + "recent_reacquisition_signal_mix", "" + ), "recent_reacquisition_persistence_path": target.get( "recent_reacquisition_persistence_path", "", @@ -1890,7 +1973,9 @@ def closure_forecast_reacquisition_freshness_hotspots( "reacquisition_event_count": len( [ part - for part in (target.get("recent_reacquisition_persistence_path", "") or "").split(" -> ") + for part in ( + target.get("recent_reacquisition_persistence_path", "") or "" + ).split(" -> ") if part ] ), @@ -1928,8 +2013,6 @@ def closure_forecast_reacquisition_freshness_summary( primary_target: dict[str, Any], stale_reacquisition_hotspots: list[dict[str, Any]], fresh_reacquisition_signal_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" freshness_status = primary_target.get( @@ -1975,11 +2058,11 @@ def closure_forecast_persistence_reset_summary( primary_target: dict[str, Any], stale_reacquisition_hotspots: list[dict[str, Any]], fresh_reacquisition_signal_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" - reset_status = primary_target.get("closure_forecast_persistence_reset_status", "none") + reset_status = primary_target.get( + "closure_forecast_persistence_reset_status", "none" + ) freshness_status = primary_target.get( "closure_forecast_reacquisition_freshness_status", "insufficient-data", diff --git a/src/operator_trend_closure_forecast_reset_controls.py b/src/operator_trend_closure_forecast_reset_controls.py index 0c9be9c..41c1a71 100644 --- a/src/operator_trend_closure_forecast_reset_controls.py +++ b/src/operator_trend_closure_forecast_reset_controls.py @@ -1,6 +1,56 @@ from __future__ import annotations -from typing import Any, Callable, NamedTuple, Sequence +from typing import Any, Callable, NamedTuple + +from src.operator_trend_closure_forecast_freshness_controls import ( + closure_forecast_freshness_status, +) +from src.operator_trend_support import ( + CLASS_MEMORY_RECENCY_WEIGHTS, + CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_PERSISTENCE_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERERESTORE_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, + CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, + CLASS_RESET_REENTRY_REFRESH_REBUILD_WINDOW_RUNS, + CLASS_RESET_REENTRY_WINDOW_RUNS, + HISTORY_WINDOW_RUNS, + clamp_round, + class_direction_flip_count, + closure_forecast_direction_majority, + closure_forecast_direction_reversing, + closure_forecast_reset_reentry_freshness_reason, + closure_forecast_reset_reentry_memory_side_from_event, + closure_forecast_reset_reentry_rebuild_path_label, + closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label, + closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label, + closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label, + closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event, + closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status, + closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status, + closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status, + closure_forecast_reset_reentry_rebuild_side_from_event, + closure_forecast_reset_reentry_rebuild_side_from_persistence_status, + closure_forecast_reset_reentry_rebuild_side_from_recovery_status, + closure_forecast_reset_reentry_rebuild_side_from_status, + closure_forecast_reset_reentry_refresh_path_label, + closure_forecast_reset_reentry_side_from_persistence_status, + closure_forecast_reset_reentry_side_from_status, + normalized_closure_forecast_direction, + ordered_reset_reentry_events_for_target, + recent_reset_reentry_signal_mix, + recommendation_bucket, + reset_reentry_event_has_evidence, + reset_reentry_event_is_clearance_like, + reset_reentry_event_is_confirmation_like, + reset_reentry_event_signal_label, + target_class_key, + target_label, + target_specific_normalization_noise, +) def closure_forecast_reset_side_from_status(status: str) -> str: @@ -13,10 +63,10 @@ def closure_forecast_reset_side_from_status(status: str) -> str: def closure_forecast_reset_refresh_path_label( event: dict[str, Any], - *, - normalized_closure_forecast_direction: Callable[[str, float], str], ) -> str: - reset_status = event.get("closure_forecast_persistence_reset_status", "none") or "none" + reset_status = ( + event.get("closure_forecast_persistence_reset_status", "none") or "none" + ) if reset_status != "none": return str(reset_status) score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) @@ -25,13 +75,17 @@ def closure_forecast_reset_refresh_path_label( score, ) freshness = str( - event.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") + event.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) ) if direction == "supporting-confirmation": return f"{freshness} confirmation" if direction == "supporting-clearance": return f"{freshness} clearance" - likely_outcome = str(event.get("transition_closure_likely_outcome", "none") or "none") + likely_outcome = str( + event.get("transition_closure_likely_outcome", "none") or "none" + ) if likely_outcome != "none": return likely_outcome return "hold" @@ -41,21 +95,13 @@ def closure_forecast_reset_refresh_recovery_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_reset_side_from_status: Callable[[str], str], - normalized_closure_forecast_direction: Callable[[str, float], str], - clamp_round: Callable[[float, float, float], float], - closure_forecast_direction_majority: Callable[[list[str]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_reset_refresh_path_label: Callable[[dict[str, Any]], str], - class_reset_reentry_window_runs: int, ) -> dict[str, Any]: class_key = target_class_key(target) matching_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key - ][:class_reset_reentry_window_runs] + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ][:CLASS_RESET_REENTRY_WINDOW_RUNS] recent_reset_side = "none" latest_reset_index: int | None = None for index, event in enumerate(matching_events): @@ -88,7 +134,7 @@ def closure_forecast_reset_refresh_recovery_for_target( continue relevant_events.append(event) directions.append(direction) - if len(relevant_events) > class_reset_reentry_window_runs: + if len(relevant_events) > CLASS_RESET_REENTRY_WINDOW_RUNS: break if direction == "neutral": signal_strength = 0.0 @@ -102,30 +148,51 @@ def closure_forecast_reset_refresh_recovery_for_target( "stale": 0.25, "insufficient-data": 0.10, }.get( - str(event.get("closure_forecast_reacquisition_freshness_status", "insufficient-data")), + str( + event.get( + "closure_forecast_reacquisition_freshness_status", + "insufficient-data", + ) + ), 0.10, ) - weight = (1.0, 0.8, 0.6, 0.4)[min(len(relevant_events) - 1, class_reset_reentry_window_runs - 1)] + weight = (1.0, 0.8, 0.6, 0.4)[ + min(len(relevant_events) - 1, CLASS_RESET_REENTRY_WINDOW_RUNS - 1) + ] weighted_total += sign * signal_strength * freshness_factor * weight weight_sum += weight - recovery_score = clamp_round(weighted_total / max(weight_sum, 1.0), -0.95, 0.95) + recovery_score = clamp_round( + weighted_total / max(weight_sum, 1.0), + lower=-0.95, + upper=0.95, + ) current_score = float(target.get("closure_forecast_reweight_score", 0.0) or 0.0) current_direction = normalized_closure_forecast_direction( str(target.get("closure_forecast_reweight_direction", "neutral")), current_score, ) current_freshness = str( - target.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") + target.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) + ) + current_momentum = str( + target.get("closure_forecast_momentum_status", "insufficient-data") ) - current_momentum = str(target.get("closure_forecast_momentum_status", "insufficient-data")) current_stability = str(target.get("closure_forecast_stability_status", "watch")) earlier_majority = closure_forecast_direction_majority(directions[1:]) local_noise = target_specific_normalization_noise(target, transition_history_meta) - direction_reversing = closure_forecast_direction_reversing(current_direction, earlier_majority) + direction_reversing = closure_forecast_direction_reversing( + current_direction, earlier_majority + ) opposes_reset = ( - recent_reset_side == "confirmation" and current_direction == "supporting-clearance" - ) or (recent_reset_side == "clearance" and current_direction == "supporting-confirmation") + recent_reset_side == "confirmation" + and current_direction == "supporting-clearance" + ) or ( + recent_reset_side == "clearance" + and current_direction == "supporting-confirmation" + ) aligned_fresh_runs_after_reset = 0 if latest_reset_index is not None and latest_reset_index > 0: @@ -144,7 +211,10 @@ def closure_forecast_reset_refresh_recovery_for_target( ) if ( event_side == recent_reset_side - and event.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") + and event.get( + "closure_forecast_reacquisition_freshness_status", + "insufficient-data", + ) == "fresh" ): aligned_fresh_runs_after_reset += 1 @@ -157,12 +227,17 @@ def closure_forecast_reset_refresh_recovery_for_target( ) current_event_already_counted = any( event.get("generated_at", "") == "" - and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) == current_score + and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + == current_score and event.get("closure_forecast_reweight_direction", "neutral") == target.get("closure_forecast_reweight_direction", "neutral") for event in matching_events[: latest_reset_index or 0] ) - if current_side == recent_reset_side and current_freshness == "fresh" and not current_event_already_counted: + if ( + current_side == recent_reset_side + and current_freshness == "fresh" + and not current_event_already_counted + ): aligned_fresh_runs_after_reset += 1 if len(relevant_events) < 2 or recent_reset_side == "none": @@ -236,7 +311,10 @@ def closure_forecast_reset_refresh_recovery_for_target( }: reentry_status = "blocked" reentry_reason = "Local target instability is still preventing positive confirmation-side re-entry." - elif recovery_status in {"recovering-confirmation-reset", "reentering-confirmation"}: + elif recovery_status in { + "recovering-confirmation-reset", + "reentering-confirmation", + }: reentry_status = "pending-confirmation-reentry" reentry_reason = ( "Fresh confirmation-side evidence is returning after a reset, but it has not yet " @@ -258,7 +336,9 @@ def closure_forecast_reset_refresh_recovery_for_target( "closure_forecast_reset_reentry_status": reentry_status, "closure_forecast_reset_reentry_reason": reentry_reason, "recent_reset_refresh_path": " -> ".join( - closure_forecast_reset_refresh_path_label(event) for event in matching_events if event + closure_forecast_reset_refresh_path_label(event) + for event in matching_events + if event ), "recent_reset_side": recent_reset_side, "aligned_fresh_runs_after_latest_reset": aligned_fresh_runs_after_reset, @@ -280,17 +360,27 @@ def apply_reset_refresh_reentry_control( reacquisition_status: str, reacquisition_reason: str, ) -> dict[str, Any]: - recovery_status = str(refresh_meta.get("closure_forecast_reset_refresh_recovery_status", "none")) - reentry_status = str(refresh_meta.get("closure_forecast_reset_reentry_status", "none")) + recovery_status = str( + refresh_meta.get("closure_forecast_reset_refresh_recovery_status", "none") + ) + reentry_status = str( + refresh_meta.get("closure_forecast_reset_reentry_status", "none") + ) reentry_reason = str(refresh_meta.get("closure_forecast_reset_reentry_reason", "")) recent_reset_side = str(refresh_meta.get("recent_reset_side", "none")) current_freshness = str( - target.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") + target.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) ) current_stability = str(target.get("closure_forecast_stability_status", "watch")) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) - decayed_clearance_rate = float(target.get("decayed_reacquired_clearance_rate", 0.0) or 0.0) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) + decayed_clearance_rate = float( + target.get("decayed_reacquired_clearance_rate", 0.0) or 0.0 + ) persistence_status = "none" persistence_reason = "" persistence_age_runs = 0 @@ -370,7 +460,10 @@ def apply_reset_refresh_reentry_control( } if recent_reset_side == "confirmation": - if recovery_status in {"recovering-confirmation-reset", "reentering-confirmation"}: + if recovery_status in { + "recovering-confirmation-reset", + "reentering-confirmation", + }: return { "transition_closure_likely_outcome": "hold", "closure_forecast_hysteresis_status": "pending-confirmation", @@ -386,7 +479,10 @@ def apply_reset_refresh_reentry_control( "closure_forecast_reacquisition_persistence_status": "none", "closure_forecast_reacquisition_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": "hold", "closure_forecast_hysteresis_status": "pending-confirmation", @@ -425,7 +521,10 @@ def apply_reset_refresh_reentry_control( "closure_forecast_reacquisition_persistence_status": "none", "closure_forecast_reacquisition_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: weaker_outcome = closure_likely_outcome if weaker_outcome == "expire-risk": weaker_outcome = "clear-risk" @@ -457,7 +556,9 @@ def apply_reset_refresh_reentry_control( "class_transition_resolution_reason": resolution_reason, "closure_forecast_reacquisition_status": reacquisition_status, "closure_forecast_reacquisition_reason": reacquisition_reason, - "closure_forecast_reacquisition_age_runs": target.get("closure_forecast_reacquisition_age_runs", 0), + "closure_forecast_reacquisition_age_runs": target.get( + "closure_forecast_reacquisition_age_runs", 0 + ), "closure_forecast_reacquisition_persistence_score": target.get( "closure_forecast_reacquisition_persistence_score", 0.0, @@ -477,7 +578,6 @@ def closure_forecast_reset_refresh_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -504,7 +604,9 @@ def closure_forecast_reset_refresh_hotspots( existing = grouped.get(class_key) if existing is None or abs( float(current["closure_forecast_reset_refresh_recovery_score"] or 0.0) - ) > abs(float(existing["closure_forecast_reset_refresh_recovery_score"] or 0.0)): + ) > abs( + float(existing["closure_forecast_reset_refresh_recovery_score"] or 0.0) + ): grouped[class_key] = current hotspots = list(grouped.values()) if mode == "confirmation": @@ -537,7 +639,12 @@ def closure_forecast_reset_refresh_hotspots( ] hotspots.sort( key=lambda item: ( - -abs(float(item.get("closure_forecast_reset_refresh_recovery_score", 0.0) or 0.0)), + -abs( + float( + item.get("closure_forecast_reset_refresh_recovery_score", 0.0) + or 0.0 + ) + ), str(item.get("label", "")), ) ) @@ -548,12 +655,14 @@ def closure_forecast_reset_refresh_recovery_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" - status = primary_target.get("closure_forecast_reset_refresh_recovery_status", "none") - score = float(primary_target.get("closure_forecast_reset_refresh_recovery_score", 0.0) or 0.0) + status = primary_target.get( + "closure_forecast_reset_refresh_recovery_status", "none" + ) + score = float( + primary_target.get("closure_forecast_reset_refresh_recovery_score", 0.0) or 0.0 + ) if status == "recovering-confirmation-reset": return ( f"Fresh confirmation-side evidence is returning for {label} after a reset, but it " @@ -602,8 +711,6 @@ def closure_forecast_reset_reentry_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = primary_target.get("closure_forecast_reset_reentry_status", "none") @@ -658,34 +765,19 @@ def closure_forecast_reset_reentry_summary( def closure_forecast_reset_reentry_freshness_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], - *, - target_class_key: Callable[[dict[str, Any]], str], - reset_reentry_event_has_evidence: Callable[[dict[str, Any]], bool], - reset_reentry_event_signal_label: Callable[[dict[str, Any]], str], - closure_forecast_reset_reentry_side_from_persistence_status: Callable[[str], str], - closure_forecast_reset_reentry_side_from_status: Callable[[str], str], - closure_forecast_reset_reentry_memory_side_from_event: Callable[[dict[str, Any]], str], - class_memory_recency_weights: Sequence[float], - history_window_runs: int, - class_reset_reentry_freshness_window_runs: int, - closure_forecast_freshness_status: Callable[[float, float], str], - closure_forecast_reset_reentry_freshness_reason: Callable[ - [str, float, float, float, float], str - ], - recent_reset_reentry_signal_mix: Callable[[float, float, float, float], str], - reset_reentry_event_is_confirmation_like: Callable[[dict[str, Any]], bool], - reset_reentry_event_is_clearance_like: Callable[[dict[str, Any]], bool], ) -> dict[str, Any]: class_key = target_class_key(target) class_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key + event + for event in closure_forecast_events + if event.get("class_key") == class_key ] relevant_events: list[dict[str, Any]] = [] for event in class_events: if not reset_reentry_event_has_evidence(event): continue relevant_events.append(event) - if len(relevant_events) >= history_window_runs: + if len(relevant_events) >= HISTORY_WINDOW_RUNS: break weighted_reset_reentry_evidence_count = 0.0 @@ -694,7 +786,7 @@ def closure_forecast_reset_reentry_freshness_for_target( recent_reset_reentry_weight = 0.0 recent_signals = [ reset_reentry_event_signal_label(event) - for event in relevant_events[:class_reset_reentry_freshness_window_runs] + for event in relevant_events[:CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS] ] current_side = closure_forecast_reset_reentry_side_from_persistence_status( str(target.get("closure_forecast_reset_reentry_persistence_status", "none")) @@ -705,10 +797,13 @@ def closure_forecast_reset_reentry_freshness_for_target( ) for index, event in enumerate(relevant_events): - weight = class_memory_recency_weights[min(index, history_window_runs - 1)] + weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_reset_reentry_evidence_count += weight event_side = closure_forecast_reset_reentry_memory_side_from_event(event) - if index < class_reset_reentry_freshness_window_runs and event_side == current_side: + if ( + index < CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS + and event_side == current_side + ): recent_reset_reentry_weight += weight if reset_reentry_event_is_confirmation_like(event): weighted_confirmation_like += weight @@ -764,7 +859,9 @@ def closure_forecast_reset_reentry_freshness_for_target( "has_fresh_aligned_recent_evidence": any( closure_forecast_reset_reentry_memory_side_from_event(event) == current_side and reset_reentry_event_signal_label(event) != "neutral" - and event.get("closure_forecast_reacquisition_freshness_status", "insufficient-data") + and event.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) == "fresh" for event in relevant_events[:2] ), @@ -791,22 +888,27 @@ def apply_reset_reentry_freshness_reset_control( persistence_score: float, persistence_status: str, persistence_reason: str, - closure_forecast_reset_reentry_side_from_persistence_status: Callable[[str], str], - closure_forecast_reset_reentry_side_from_status: Callable[[str], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], ) -> dict[str, Any]: freshness_status = str( - freshness_meta.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") + freshness_meta.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) ) decayed_clearance_rate = float( freshness_meta.get("decayed_reset_reentered_clearance_rate", 0.0) or 0.0 ) - churn_status = str(target.get("closure_forecast_reset_reentry_churn_status", "none")) - current_side = closure_forecast_reset_reentry_side_from_persistence_status(persistence_status) + churn_status = str( + target.get("closure_forecast_reset_reentry_churn_status", "none") + ) + current_side = closure_forecast_reset_reentry_side_from_persistence_status( + persistence_status + ) if current_side == "none": current_side = closure_forecast_reset_reentry_side_from_status(reentry_status) local_noise = target_specific_normalization_noise(target, transition_history_meta) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) has_fresh_aligned_recent_evidence = bool( freshness_meta.get("has_fresh_aligned_recent_evidence", False) ) @@ -834,7 +936,9 @@ def restore_weaker_pending_posture( ) if local_noise and current_side != "none": - blocked_reason = "Local target instability still overrides healthy reset re-entry freshness." + blocked_reason = ( + "Local target instability still overrides healthy reset re-entry freshness." + ) if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" elif closure_likely_outcome == "expire-risk": @@ -899,7 +1003,10 @@ def restore_weaker_pending_posture( ), "closure_forecast_reset_reentry_persistence_reason": softened_reason, } - if persistence_status == "holding-confirmation-reentry" and churn_status == "churn": + if ( + persistence_status == "holding-confirmation-reentry" + and churn_status == "churn" + ): freshness_status = "stale" if current_side == "clearance" and freshness_status == "mixed-age": @@ -931,7 +1038,10 @@ def restore_weaker_pending_posture( ), "closure_forecast_reset_reentry_persistence_reason": softened_reason, } - if persistence_status == "holding-clearance-reentry" and churn_status == "churn": + if ( + persistence_status == "holding-clearance-reentry" + and churn_status == "churn" + ): freshness_status = "stale" needs_reset = ( @@ -1088,7 +1198,6 @@ def closure_forecast_reset_reentry_freshness_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -1119,14 +1228,19 @@ def closure_forecast_reset_reentry_freshness_hotspots( "", ), "dominant_count": max( - float(target.get("decayed_reset_reentered_confirmation_rate", 0.0) or 0.0), + float( + target.get("decayed_reset_reentered_confirmation_rate", 0.0) or 0.0 + ), float(target.get("decayed_reset_reentered_clearance_rate", 0.0) or 0.0), ), "reset_reentry_event_count": len( [ part for part in ( - str(target.get("recent_reset_reentry_persistence_path", "") or "") + str( + target.get("recent_reset_reentry_persistence_path", "") + or "" + ) ).split(" -> ") if part ] @@ -1165,12 +1279,12 @@ def closure_forecast_reset_reentry_freshness_summary( primary_target: dict[str, Any], stale_reset_reentry_hotspots: list[dict[str, Any]], fresh_reset_reentry_signal_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" freshness_status = str( - primary_target.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") + primary_target.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) ) if freshness_status == "fresh": return ( @@ -1209,13 +1323,15 @@ def closure_forecast_reset_reentry_reset_summary( primary_target: dict[str, Any], stale_reset_reentry_hotspots: list[dict[str, Any]], fresh_reset_reentry_signal_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" - reset_status = str(primary_target.get("closure_forecast_reset_reentry_reset_status", "none")) + reset_status = str( + primary_target.get("closure_forecast_reset_reentry_reset_status", "none") + ) freshness_status = str( - primary_target.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") + primary_target.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) ) confirmation_rate = float( primary_target.get("decayed_reset_reentered_confirmation_rate", 0.0) or 0.0 @@ -1284,33 +1400,14 @@ def closure_forecast_reset_reentry_refresh_recovery_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_side_from_status: Callable[[str], str], - normalized_closure_forecast_direction: Callable[[str, float], str], - clamp_round: Callable[..., float], - closure_forecast_direction_majority: Callable[[list[str]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_reset_reentry_refresh_path_label: Callable[[dict[str, Any]], str], - class_reset_reentry_refresh_rebuild_window_runs: int, ) -> dict[str, Any]: return _recovery_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_RESET_REENTRY_RECOVERY_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=normalized_closure_forecast_direction, - clamp_round=clamp_round, - closure_forecast_direction_majority=closure_forecast_direction_majority, - target_specific_normalization_noise=target_specific_normalization_noise, - closure_forecast_direction_reversing=closure_forecast_direction_reversing, path_label=closure_forecast_reset_reentry_refresh_path_label, - window_runs=class_reset_reentry_refresh_rebuild_window_runs, + window_runs=CLASS_RESET_REENTRY_REFRESH_REBUILD_WINDOW_RUNS, ) @@ -1336,17 +1433,29 @@ def apply_reset_reentry_refresh_rebuild_control( persistence_reason: str, ) -> dict[str, Any]: recovery_status = str( - refresh_meta.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") + refresh_meta.get( + "closure_forecast_reset_reentry_refresh_recovery_status", "none" + ) + ) + rebuild_status = str( + refresh_meta.get("closure_forecast_reset_reentry_rebuild_status", "none") + ) + rebuild_reason = str( + refresh_meta.get("closure_forecast_reset_reentry_rebuild_reason", "") + ) + recent_reset_reentry_side = str( + refresh_meta.get("recent_reset_reentry_side", "none") ) - rebuild_status = str(refresh_meta.get("closure_forecast_reset_reentry_rebuild_status", "none")) - rebuild_reason = str(refresh_meta.get("closure_forecast_reset_reentry_rebuild_reason", "")) - recent_reset_reentry_side = str(refresh_meta.get("recent_reset_reentry_side", "none")) current_freshness = str( - target.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") + target.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) ) current_stability = str(target.get("closure_forecast_stability_status", "watch")) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) decayed_clearance_rate = float( target.get("decayed_reset_reentered_clearance_rate", 0.0) or 0.0 ) @@ -1449,7 +1558,10 @@ def apply_reset_reentry_refresh_rebuild_control( "closure_forecast_reset_reentry_persistence_status": "none", "closure_forecast_reset_reentry_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -1490,7 +1602,10 @@ def apply_reset_reentry_refresh_rebuild_control( "closure_forecast_reset_reentry_persistence_status": "none", "closure_forecast_reset_reentry_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -1550,7 +1665,6 @@ def _refresh_hotspots_base( *, spec: _RefreshHotspotsSpec, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -1598,19 +1712,33 @@ def _refresh_hotspots_base( _RESET_REENTRY_REFRESH_HOTSPOTS_SPEC = _RefreshHotspotsSpec( - score_key='closure_forecast_reset_reentry_refresh_recovery_score', - status_key='closure_forecast_reset_reentry_refresh_recovery_status', - path_key='recent_reset_reentry_refresh_path', - confirmation_statuses=frozenset({'rebuilding-confirmation-reentry', 'recovering-confirmation-reentry-reset'}), - clearance_statuses=frozenset({'rebuilding-clearance-reentry', 'recovering-clearance-reentry-reset'}), + score_key="closure_forecast_reset_reentry_refresh_recovery_score", + status_key="closure_forecast_reset_reentry_refresh_recovery_status", + path_key="recent_reset_reentry_refresh_path", + confirmation_statuses=frozenset( + {"rebuilding-confirmation-reentry", "recovering-confirmation-reentry-reset"} + ), + clearance_statuses=frozenset( + {"rebuilding-clearance-reentry", "recovering-clearance-reentry-reset"} + ), ) _REBUILD_REENTRY_REFRESH_HOTSPOTS_SPEC = _RefreshHotspotsSpec( - score_key='closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score', - status_key='closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status', - path_key='recent_reset_reentry_rebuild_reentry_refresh_path', - confirmation_statuses=frozenset({'recovering-confirmation-rebuild-reentry-reset', 'restoring-confirmation-rebuild-reentry'}), - clearance_statuses=frozenset({'recovering-clearance-rebuild-reentry-reset', 'restoring-clearance-rebuild-reentry'}), + score_key="closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score", + status_key="closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + path_key="recent_reset_reentry_rebuild_reentry_refresh_path", + confirmation_statuses=frozenset( + { + "recovering-confirmation-rebuild-reentry-reset", + "restoring-confirmation-rebuild-reentry", + } + ), + clearance_statuses=frozenset( + { + "recovering-clearance-rebuild-reentry-reset", + "restoring-clearance-rebuild-reentry", + } + ), ) @@ -1618,13 +1746,11 @@ def closure_forecast_reset_reentry_refresh_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: return _refresh_hotspots_base( resolution_targets, spec=_RESET_REENTRY_REFRESH_HOTSPOTS_SPEC, mode=mode, - target_class_key=target_class_key, ) @@ -1663,7 +1789,6 @@ def _refresh_recovery_summary_base( recovering_clearance_hotspots: list[dict[str, Any]], *, spec: _RefreshRecoverySummarySpec, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str(primary_target.get(spec.status_key, "none")) @@ -1699,41 +1824,41 @@ def _refresh_recovery_summary_base( _RESET_REENTRY_REFRESH_RECOVERY_SUMMARY_SPEC = _RefreshRecoverySummarySpec( - status_key='closure_forecast_reset_reentry_refresh_recovery_status', - score_key='closure_forecast_reset_reentry_refresh_recovery_score', - reason_key='closure_forecast_reset_reentry_rebuild_reason', - recovering_confirmation_status='recovering-confirmation-reentry-reset', - recovering_clearance_status='recovering-clearance-reentry-reset', - rebuilding_confirmation_status='rebuilding-confirmation-reentry', - rebuilding_clearance_status='rebuilding-clearance-reentry', - recovering_confirmation_text='Fresh confirmation-side evidence is returning after reset re-entry softened or reset for {label}, but it has not yet rebuilt stronger reset re-entry ({score:.2f}).', - recovering_clearance_text='Fresh clearance-side evidence is returning after reset re-entry softened or reset for {label}, but it has not yet rebuilt stronger reset re-entry ({score:.2f}).', - rebuilding_confirmation_text='Confirmation-side reset re-entry for {label} is rebuilding strongly enough that stronger restored posture may be re-earned soon ({score:.2f}).', - rebuilding_clearance_text='Clearance-side reset re-entry for {label} is rebuilding strongly enough that stronger restored caution may be re-earned soon ({score:.2f}).', - reversing_text='The post-reset reset re-entry recovery attempt for {label} is changing direction, so rebuild stays blocked ({score:.2f}).', - blocked_reason_default='Local target instability is still preventing positive confirmation-side reset re-entry rebuild for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side reset re-entry recovery is strongest around {hotspot_label}, so those classes are closest to rebuilding stronger restored confirmation posture.', - recovering_clearance_hotspot_text='Clearance-side reset re-entry recovery is strongest around {hotspot_label}, so those classes are closest to rebuilding stronger restored clearance posture.', - default_text='No reset re-entry rebuild attempt is active enough yet to re-earn stronger restored posture.', + status_key="closure_forecast_reset_reentry_refresh_recovery_status", + score_key="closure_forecast_reset_reentry_refresh_recovery_score", + reason_key="closure_forecast_reset_reentry_rebuild_reason", + recovering_confirmation_status="recovering-confirmation-reentry-reset", + recovering_clearance_status="recovering-clearance-reentry-reset", + rebuilding_confirmation_status="rebuilding-confirmation-reentry", + rebuilding_clearance_status="rebuilding-clearance-reentry", + recovering_confirmation_text="Fresh confirmation-side evidence is returning after reset re-entry softened or reset for {label}, but it has not yet rebuilt stronger reset re-entry ({score:.2f}).", + recovering_clearance_text="Fresh clearance-side evidence is returning after reset re-entry softened or reset for {label}, but it has not yet rebuilt stronger reset re-entry ({score:.2f}).", + rebuilding_confirmation_text="Confirmation-side reset re-entry for {label} is rebuilding strongly enough that stronger restored posture may be re-earned soon ({score:.2f}).", + rebuilding_clearance_text="Clearance-side reset re-entry for {label} is rebuilding strongly enough that stronger restored caution may be re-earned soon ({score:.2f}).", + reversing_text="The post-reset reset re-entry recovery attempt for {label} is changing direction, so rebuild stays blocked ({score:.2f}).", + blocked_reason_default="Local target instability is still preventing positive confirmation-side reset re-entry rebuild for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side reset re-entry recovery is strongest around {hotspot_label}, so those classes are closest to rebuilding stronger restored confirmation posture.", + recovering_clearance_hotspot_text="Clearance-side reset re-entry recovery is strongest around {hotspot_label}, so those classes are closest to rebuilding stronger restored clearance posture.", + default_text="No reset re-entry rebuild attempt is active enough yet to re-earn stronger restored posture.", ) _REBUILD_REENTRY_REFRESH_RECOVERY_SUMMARY_SPEC = _RefreshRecoverySummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status', - score_key='closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_reason', - recovering_confirmation_status='recovering-confirmation-rebuild-reentry-reset', - recovering_clearance_status='recovering-clearance-rebuild-reentry-reset', - rebuilding_confirmation_status='restoring-confirmation-rebuild-reentry', - rebuilding_clearance_status='restoring-clearance-rebuild-reentry', - recovering_confirmation_text='Fresh confirmation-side evidence is returning after rebuilt re-entry softened or reset for {label}, but it has not yet restored stronger rebuilt re-entry posture ({score:.2f}).', - recovering_clearance_text='Fresh clearance-side evidence is returning after rebuilt re-entry softened or reset for {label}, but it has not yet restored stronger rebuilt re-entry posture ({score:.2f}).', - rebuilding_confirmation_text='Confirmation-side rebuilt re-entry for {label} is recovering strongly enough that stronger rebuilt re-entry posture may be restored soon ({score:.2f}).', - rebuilding_clearance_text='Clearance-side rebuilt re-entry for {label} is recovering strongly enough that stronger rebuilt re-entry posture may be restored soon ({score:.2f}).', - reversing_text='The post-reset rebuilt re-entry recovery attempt for {label} is changing direction, so stronger rebuilt re-entry posture stays blocked ({score:.2f}).', - blocked_reason_default='Local target instability is still preventing positive confirmation-side rebuilt re-entry restore for {label}.', - recovering_confirmation_hotspot_text='Confirmation-side rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to restoring stronger rebuilt confirmation posture.', - recovering_clearance_hotspot_text='Clearance-side rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to restoring stronger rebuilt clearance posture.', - default_text='No rebuilt re-entry recovery attempt is active enough yet to restore stronger posture.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + score_key="closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_reason", + recovering_confirmation_status="recovering-confirmation-rebuild-reentry-reset", + recovering_clearance_status="recovering-clearance-rebuild-reentry-reset", + rebuilding_confirmation_status="restoring-confirmation-rebuild-reentry", + rebuilding_clearance_status="restoring-clearance-rebuild-reentry", + recovering_confirmation_text="Fresh confirmation-side evidence is returning after rebuilt re-entry softened or reset for {label}, but it has not yet restored stronger rebuilt re-entry posture ({score:.2f}).", + recovering_clearance_text="Fresh clearance-side evidence is returning after rebuilt re-entry softened or reset for {label}, but it has not yet restored stronger rebuilt re-entry posture ({score:.2f}).", + rebuilding_confirmation_text="Confirmation-side rebuilt re-entry for {label} is recovering strongly enough that stronger rebuilt re-entry posture may be restored soon ({score:.2f}).", + rebuilding_clearance_text="Clearance-side rebuilt re-entry for {label} is recovering strongly enough that stronger rebuilt re-entry posture may be restored soon ({score:.2f}).", + reversing_text="The post-reset rebuilt re-entry recovery attempt for {label} is changing direction, so stronger rebuilt re-entry posture stays blocked ({score:.2f}).", + blocked_reason_default="Local target instability is still preventing positive confirmation-side rebuilt re-entry restore for {label}.", + recovering_confirmation_hotspot_text="Confirmation-side rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to restoring stronger rebuilt confirmation posture.", + recovering_clearance_hotspot_text="Clearance-side rebuilt re-entry recovery is strongest around {hotspot_label}, so those classes are closest to restoring stronger rebuilt clearance posture.", + default_text="No rebuilt re-entry recovery attempt is active enough yet to restore stronger posture.", ) @@ -1741,15 +1866,12 @@ def closure_forecast_reset_reentry_refresh_recovery_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: return _refresh_recovery_summary_base( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, spec=_RESET_REENTRY_REFRESH_RECOVERY_SUMMARY_SPEC, - target_label=target_label, ) @@ -1786,7 +1908,6 @@ def _tier_summary_base( recovering_clearance_hotspots: list[dict[str, Any]], *, spec: _TierSummarySpec, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str(primary_target.get(spec.status_key, "none")) @@ -1819,54 +1940,54 @@ def _tier_summary_base( _REBUILD_SUMMARY_SPEC = _TierSummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_status', - reason_key='closure_forecast_reset_reentry_rebuild_reason', - pending_confirmation_status='pending-confirmation-rebuild', - pending_clearance_status='pending-clearance-rebuild', - settled_confirmation_status='rebuilt-confirmation-reentry', - settled_clearance_status='rebuilt-clearance-reentry', - pending_confirmation_text='Fresh confirmation-side evidence is returning after reset re-entry softened or reset for {label}, but stronger reset re-entry still needs more fresh follow-through before it is rebuilt.', - pending_clearance_text='Fresh clearance-side evidence is returning after reset re-entry softened or reset for {label}, but stronger reset re-entry still needs more fresh follow-through before it is rebuilt.', - settled_confirmation_text='Fresh confirmation-side follow-through for {label} has rebuilt stronger confirmation-side reset re-entry.', - settled_clearance_text='Fresh clearance-side pressure for {label} has rebuilt stronger clearance-side reset re-entry.', - blocked_reason_default='Local target instability is still preventing positive confirmation-side reset re-entry rebuild for {label}.', - recovering_confirmation_text='Confirmation-side reset re-entry rebuild is closest around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.', - recovering_clearance_text='Clearance-side reset re-entry rebuild is closest around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.', - default_text='No reset re-entry rebuild is changing the current restored closure-forecast posture right now.', + status_key="closure_forecast_reset_reentry_rebuild_status", + reason_key="closure_forecast_reset_reentry_rebuild_reason", + pending_confirmation_status="pending-confirmation-rebuild", + pending_clearance_status="pending-clearance-rebuild", + settled_confirmation_status="rebuilt-confirmation-reentry", + settled_clearance_status="rebuilt-clearance-reentry", + pending_confirmation_text="Fresh confirmation-side evidence is returning after reset re-entry softened or reset for {label}, but stronger reset re-entry still needs more fresh follow-through before it is rebuilt.", + pending_clearance_text="Fresh clearance-side evidence is returning after reset re-entry softened or reset for {label}, but stronger reset re-entry still needs more fresh follow-through before it is rebuilt.", + settled_confirmation_text="Fresh confirmation-side follow-through for {label} has rebuilt stronger confirmation-side reset re-entry.", + settled_clearance_text="Fresh clearance-side pressure for {label} has rebuilt stronger clearance-side reset re-entry.", + blocked_reason_default="Local target instability is still preventing positive confirmation-side reset re-entry rebuild for {label}.", + recovering_confirmation_text="Confirmation-side reset re-entry rebuild is closest around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.", + recovering_clearance_text="Clearance-side reset re-entry rebuild is closest around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.", + default_text="No reset re-entry rebuild is changing the current restored closure-forecast posture right now.", ) _RESTORE_SUMMARY_SPEC = _TierSummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_status', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_reason', - pending_confirmation_status='pending-confirmation-rebuild-reentry-restore', - pending_clearance_status='pending-clearance-rebuild-reentry-restore', - settled_confirmation_status='restored-confirmation-rebuild-reentry', - settled_clearance_status='restored-clearance-rebuild-reentry', - pending_confirmation_text='Fresh confirmation-side evidence is returning after rebuilt re-entry softened or reset for {label}, but stronger rebuilt re-entry posture still needs more fresh follow-through before it is restored.', - pending_clearance_text='Fresh clearance-side evidence is returning after rebuilt re-entry softened or reset for {label}, but stronger rebuilt re-entry posture still needs more fresh follow-through before it is restored.', - settled_confirmation_text='Fresh confirmation-side follow-through for {label} has restored stronger rebuilt re-entry posture.', - settled_clearance_text='Fresh clearance-side pressure for {label} has restored stronger rebuilt re-entry posture.', - blocked_reason_default='Local target instability is still preventing positive confirmation-side rebuilt re-entry restore for {label}.', - recovering_confirmation_text='Confirmation-side rebuilt re-entry is closest to being restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.', - recovering_clearance_text='Clearance-side rebuilt re-entry is closest to being restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.', - default_text='No rebuilt re-entry restore control is changing the current closure-forecast posture right now.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_status", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_reason", + pending_confirmation_status="pending-confirmation-rebuild-reentry-restore", + pending_clearance_status="pending-clearance-rebuild-reentry-restore", + settled_confirmation_status="restored-confirmation-rebuild-reentry", + settled_clearance_status="restored-clearance-rebuild-reentry", + pending_confirmation_text="Fresh confirmation-side evidence is returning after rebuilt re-entry softened or reset for {label}, but stronger rebuilt re-entry posture still needs more fresh follow-through before it is restored.", + pending_clearance_text="Fresh clearance-side evidence is returning after rebuilt re-entry softened or reset for {label}, but stronger rebuilt re-entry posture still needs more fresh follow-through before it is restored.", + settled_confirmation_text="Fresh confirmation-side follow-through for {label} has restored stronger rebuilt re-entry posture.", + settled_clearance_text="Fresh clearance-side pressure for {label} has restored stronger rebuilt re-entry posture.", + blocked_reason_default="Local target instability is still preventing positive confirmation-side rebuilt re-entry restore for {label}.", + recovering_confirmation_text="Confirmation-side rebuilt re-entry is closest to being restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.", + recovering_clearance_text="Clearance-side rebuilt re-entry is closest to being restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.", + default_text="No rebuilt re-entry restore control is changing the current closure-forecast posture right now.", ) _RERERERESTORE_SUMMARY_SPEC = _TierSummarySpec( - status_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status', - reason_key='closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_reason', - pending_confirmation_status='pending-confirmation-rebuild-reentry-rerererestore', - pending_clearance_status='pending-clearance-rebuild-reentry-rerererestore', - settled_confirmation_status='rerererestored-confirmation-rebuild-reentry', - settled_clearance_status='rerererestored-clearance-rebuild-reentry', - pending_confirmation_text='Fresh confirmation-side evidence is returning after re-re-restored rebuilt re-entry softened or reset for {label}, but stronger re-re-restored posture still needs more fresh follow-through before it is re-re-re-restored.', - pending_clearance_text='Fresh clearance-side evidence is returning after re-re-restored rebuilt re-entry softened or reset for {label}, but stronger re-re-restored posture still needs more fresh follow-through before it is re-re-re-restored.', - settled_confirmation_text='Fresh confirmation-side follow-through for {label} has re-re-re-restored stronger re-re-restored rebuilt re-entry posture.', - settled_clearance_text='Fresh clearance-side pressure for {label} has re-re-re-restored stronger re-re-restored rebuilt re-entry posture.', - blocked_reason_default='Local target instability is still preventing positive confirmation-side re-re-restored rebuilt re-entry re-re-re-restore for {label}.', - recovering_confirmation_text='Confirmation-side re-re-restored rebuilt re-entry is closest to being re-re-re-restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.', - recovering_clearance_text='Clearance-side re-re-restored rebuilt re-entry is closest to being re-re-re-restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.', - default_text='No re-re-restored rebuilt re-entry re-re-re-restore control is changing the current closure-forecast posture right now.', + status_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status", + reason_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_reason", + pending_confirmation_status="pending-confirmation-rebuild-reentry-rerererestore", + pending_clearance_status="pending-clearance-rebuild-reentry-rerererestore", + settled_confirmation_status="rerererestored-confirmation-rebuild-reentry", + settled_clearance_status="rerererestored-clearance-rebuild-reentry", + pending_confirmation_text="Fresh confirmation-side evidence is returning after re-re-restored rebuilt re-entry softened or reset for {label}, but stronger re-re-restored posture still needs more fresh follow-through before it is re-re-re-restored.", + pending_clearance_text="Fresh clearance-side evidence is returning after re-re-restored rebuilt re-entry softened or reset for {label}, but stronger re-re-restored posture still needs more fresh follow-through before it is re-re-re-restored.", + settled_confirmation_text="Fresh confirmation-side follow-through for {label} has re-re-re-restored stronger re-re-restored rebuilt re-entry posture.", + settled_clearance_text="Fresh clearance-side pressure for {label} has re-re-re-restored stronger re-re-restored rebuilt re-entry posture.", + blocked_reason_default="Local target instability is still preventing positive confirmation-side re-re-restored rebuilt re-entry re-re-re-restore for {label}.", + recovering_confirmation_text="Confirmation-side re-re-restored rebuilt re-entry is closest to being re-re-re-restored around {hotspot_label}, but it still needs one more layer of fresh confirmation follow-through.", + recovering_clearance_text="Clearance-side re-re-restored rebuilt re-entry is closest to being re-re-re-restored around {hotspot_label}, but it still needs one more layer of fresh clearance follow-through.", + default_text="No re-re-restored rebuilt re-entry re-re-re-restore control is changing the current closure-forecast posture right now.", ) @@ -1874,22 +1995,17 @@ def closure_forecast_reset_reentry_rebuild_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: return _tier_summary_base( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, spec=_REBUILD_SUMMARY_SPEC, - target_label=target_label, ) def _reset_reentry_rebuild_event_is_confirmation_like( event: dict[str, Any], - *, - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], ) -> bool: event_side = closure_forecast_reset_reentry_rebuild_side_from_event(event) persistence_status = str( @@ -1915,8 +2031,6 @@ def _reset_reentry_rebuild_event_is_confirmation_like( def _reset_reentry_rebuild_event_is_clearance_like( event: dict[str, Any], - *, - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], ) -> bool: event_side = closure_forecast_reset_reentry_rebuild_side_from_event(event) persistence_status = str( @@ -1936,27 +2050,20 @@ def _reset_reentry_rebuild_event_is_clearance_like( ) or event.get("closure_forecast_hysteresis_status", "none") in {"pending-clearance", "confirmed-clearance"} - or event.get("transition_closure_likely_outcome", "none") in {"clear-risk", "expire-risk"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} ) def _reset_reentry_rebuild_event_has_evidence( event: dict[str, Any], - *, - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], ) -> bool: return ( _reset_reentry_rebuild_event_is_confirmation_like( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ) or _reset_reentry_rebuild_event_is_clearance_like( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ) or event.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") in {"watch", "churn", "blocked"} @@ -1965,21 +2072,13 @@ def _reset_reentry_rebuild_event_has_evidence( def _reset_reentry_rebuild_event_signal_label( event: dict[str, Any], - *, - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], ) -> str: if _reset_reentry_rebuild_event_is_confirmation_like( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ): return "confirmation-like" if _reset_reentry_rebuild_event_is_clearance_like( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ): return "clearance-like" return "neutral" @@ -1991,15 +2090,13 @@ def _closure_forecast_reset_reentry_rebuild_freshness_reason( recent_window_weight_share: float, decayed_confirmation_rate: float, decayed_clearance_rate: float, - *, - class_reset_reentry_rebuild_freshness_window_runs: int, ) -> str: if freshness_status == "fresh": return ( "Recent rebuilt reset re-entry evidence is still current enough to keep the " "restored posture trusted, with " f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest " - f"{class_reset_reentry_rebuild_freshness_window_runs} runs." + f"{CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS} runs." ) if freshness_status == "mixed-age": return ( @@ -2037,29 +2134,21 @@ def _recent_reset_reentry_rebuild_signal_mix( def closure_forecast_reset_reentry_rebuild_freshness_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], - closure_forecast_reset_reentry_rebuild_side_from_persistence_status: Callable[[str], str], - closure_forecast_reset_reentry_rebuild_side_from_status: Callable[[str], str], - closure_forecast_freshness_status: Callable[[float, float], str], - class_memory_recency_weights: tuple[float, ...], - class_reset_reentry_rebuild_freshness_window_runs: int, - history_window_runs: int, ) -> dict[str, Any]: class_key = target_class_key(target) - class_events = [event for event in closure_forecast_events if event.get("class_key") == class_key] + class_events = [ + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ] relevant_events: list[dict[str, Any]] = [] for event in class_events: if not _reset_reentry_rebuild_event_has_evidence( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ): continue relevant_events.append(event) - if len(relevant_events) >= history_window_runs: + if len(relevant_events) >= HISTORY_WINDOW_RUNS: break weighted_rebuild_evidence_count = 0.0 @@ -2069,14 +2158,15 @@ def closure_forecast_reset_reentry_rebuild_freshness_for_target( recent_signals = [ _reset_reentry_rebuild_event_signal_label( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ) - for event in relevant_events[:class_reset_reentry_rebuild_freshness_window_runs] + for event in relevant_events[:CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS] ] current_side = closure_forecast_reset_reentry_rebuild_side_from_persistence_status( - str(target.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none")) + str( + target.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", "none" + ) + ) ) if current_side == "none": current_side = closure_forecast_reset_reentry_rebuild_side_from_status( @@ -2084,33 +2174,36 @@ def closure_forecast_reset_reentry_rebuild_freshness_for_target( ) for index, event in enumerate(relevant_events): - weight = class_memory_recency_weights[min(index, history_window_runs - 1)] + weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_rebuild_evidence_count += weight event_side = closure_forecast_reset_reentry_rebuild_side_from_event(event) - if index < class_reset_reentry_rebuild_freshness_window_runs and event_side == current_side: + if ( + index < CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS + and event_side == current_side + ): recent_rebuild_weight += weight if _reset_reentry_rebuild_event_is_confirmation_like( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ): weighted_confirmation_like += weight if _reset_reentry_rebuild_event_is_clearance_like( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ): weighted_clearance_like += weight - recent_window_weight_share = recent_rebuild_weight / max(weighted_rebuild_evidence_count, 1.0) + recent_window_weight_share = recent_rebuild_weight / max( + weighted_rebuild_evidence_count, 1.0 + ) freshness_status = closure_forecast_freshness_status( weighted_rebuild_evidence_count, recent_window_weight_share, ) - decayed_confirmation_rate = weighted_confirmation_like / max(weighted_rebuild_evidence_count, 1.0) - decayed_clearance_rate = weighted_clearance_like / max(weighted_rebuild_evidence_count, 1.0) + decayed_confirmation_rate = weighted_confirmation_like / max( + weighted_rebuild_evidence_count, 1.0 + ) + decayed_clearance_rate = weighted_clearance_like / max( + weighted_rebuild_evidence_count, 1.0 + ) return { "closure_forecast_reset_reentry_rebuild_freshness_status": freshness_status, "closure_forecast_reset_reentry_rebuild_freshness_reason": ( @@ -2120,16 +2213,15 @@ def closure_forecast_reset_reentry_rebuild_freshness_for_target( recent_window_weight_share, decayed_confirmation_rate, decayed_clearance_rate, - class_reset_reentry_rebuild_freshness_window_runs=( - class_reset_reentry_rebuild_freshness_window_runs - ), ) ), "closure_forecast_reset_reentry_rebuild_memory_weight": round( recent_window_weight_share, 2, ), - "decayed_rebuilt_confirmation_reentry_rate": round(decayed_confirmation_rate, 2), + "decayed_rebuilt_confirmation_reentry_rate": round( + decayed_confirmation_rate, 2 + ), "decayed_rebuilt_clearance_reentry_rate": round(decayed_clearance_rate, 2), "recent_reset_reentry_rebuild_signal_mix": _recent_reset_reentry_rebuild_signal_mix( weighted_rebuild_evidence_count, @@ -2139,12 +2231,10 @@ def closure_forecast_reset_reentry_rebuild_freshness_for_target( ), "recent_reset_reentry_rebuild_signal_path": " -> ".join(recent_signals), "has_fresh_aligned_recent_evidence": any( - closure_forecast_reset_reentry_rebuild_side_from_event(event) == current_side + closure_forecast_reset_reentry_rebuild_side_from_event(event) + == current_side and _reset_reentry_rebuild_event_signal_label( event, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), ) != "neutral" for event in relevant_events[:2] @@ -2170,24 +2260,30 @@ def apply_reset_reentry_rebuild_freshness_reset_control( persistence_score: float, persistence_status: str, persistence_reason: str, - closure_forecast_reset_reentry_rebuild_side_from_persistence_status: Callable[[str], str], - closure_forecast_reset_reentry_rebuild_side_from_status: Callable[[str], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], ) -> dict[str, Any]: freshness_status = str( - freshness_meta.get("closure_forecast_reset_reentry_rebuild_freshness_status", "insufficient-data") + freshness_meta.get( + "closure_forecast_reset_reentry_rebuild_freshness_status", + "insufficient-data", + ) ) decayed_clearance_rate = float( freshness_meta.get("decayed_rebuilt_clearance_reentry_rate", 0.0) or 0.0 ) - churn_status = str(target.get("closure_forecast_reset_reentry_rebuild_churn_status", "none")) + churn_status = str( + target.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") + ) current_side = closure_forecast_reset_reentry_rebuild_side_from_persistence_status( persistence_status ) if current_side == "none": - current_side = closure_forecast_reset_reentry_rebuild_side_from_status(rebuild_status) + current_side = closure_forecast_reset_reentry_rebuild_side_from_status( + rebuild_status + ) local_noise = target_specific_normalization_noise(target, transition_history_meta) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) has_fresh_aligned_recent_evidence = bool( freshness_meta.get("has_fresh_aligned_recent_evidence", False) ) @@ -2213,9 +2309,7 @@ def _restore_weaker_pending_posture(reset_reason: str) -> tuple[str, str, str, s ) if local_noise and current_side != "none": - blocked_reason = ( - "Local target instability still overrides healthy rebuilt reset re-entry freshness." - ) + blocked_reason = "Local target instability still overrides healthy rebuilt reset re-entry freshness." if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" elif closure_likely_outcome == "expire-risk": @@ -2274,7 +2368,10 @@ def _restore_weaker_pending_posture(reset_reason: str) -> tuple[str, str, str, s "closure_forecast_reset_reentry_rebuild_persistence_status": "holding-confirmation-rebuild", "closure_forecast_reset_reentry_rebuild_persistence_reason": softened_reason, } - if persistence_status == "holding-confirmation-rebuild" and churn_status == "churn": + if ( + persistence_status == "holding-confirmation-rebuild" + and churn_status == "churn" + ): freshness_status = "stale" if current_side == "clearance" and freshness_status == "mixed-age": @@ -2302,7 +2399,10 @@ def _restore_weaker_pending_posture(reset_reason: str) -> tuple[str, str, str, s "closure_forecast_reset_reentry_rebuild_persistence_status": "holding-clearance-rebuild", "closure_forecast_reset_reentry_rebuild_persistence_reason": softened_reason, } - if persistence_status == "holding-clearance-rebuild" and churn_status == "churn": + if ( + persistence_status == "holding-clearance-rebuild" + and churn_status == "churn" + ): freshness_status = "stale" needs_reset = ( @@ -2454,7 +2554,6 @@ def closure_forecast_reset_reentry_rebuild_freshness_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -2485,21 +2584,26 @@ def closure_forecast_reset_reentry_rebuild_freshness_hotspots( "", ), "dominant_count": max( - float(target.get("decayed_rebuilt_confirmation_reentry_rate", 0.0) or 0.0), + float( + target.get("decayed_rebuilt_confirmation_reentry_rate", 0.0) or 0.0 + ), float(target.get("decayed_rebuilt_clearance_reentry_rate", 0.0) or 0.0), ), "rebuild_event_count": len( [ part for part in ( - target.get("recent_reset_reentry_rebuild_persistence_path", "") or "" + target.get("recent_reset_reentry_rebuild_persistence_path", "") + or "" ).split(" -> ") if part ] ), } existing = grouped.get(class_key) - if existing is None or float(current["dominant_count"]) > float(existing["dominant_count"]): + if existing is None or float(current["dominant_count"]) > float( + existing["dominant_count"] + ): grouped[class_key] = current hotspots = list(grouped.values()) @@ -2507,14 +2611,16 @@ def closure_forecast_reset_reentry_rebuild_freshness_hotspots( hotspots = [ item for item in hotspots - if item.get("closure_forecast_reset_reentry_rebuild_freshness_status") == "fresh" + if item.get("closure_forecast_reset_reentry_rebuild_freshness_status") + == "fresh" and float(item.get("dominant_count", 0.0) or 0.0) > 0.0 ] else: hotspots = [ item for item in hotspots - if item.get("closure_forecast_reset_reentry_rebuild_freshness_status") == "stale" + if item.get("closure_forecast_reset_reentry_rebuild_freshness_status") + == "stale" and float(item.get("dominant_count", 0.0) or 0.0) > 0.0 ] hotspots.sort( @@ -2531,12 +2637,13 @@ def closure_forecast_reset_reentry_rebuild_freshness_summary( primary_target: dict[str, Any], stale_reset_reentry_rebuild_hotspots: list[dict[str, Any]], fresh_reset_reentry_rebuild_signal_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" freshness_status = str( - primary_target.get("closure_forecast_reset_reentry_rebuild_freshness_status", "insufficient-data") + primary_target.get( + "closure_forecast_reset_reentry_rebuild_freshness_status", + "insufficient-data", + ) ) if freshness_status == "fresh": return ( @@ -2575,15 +2682,18 @@ def closure_forecast_reset_reentry_rebuild_reset_summary( primary_target: dict[str, Any], stale_reset_reentry_rebuild_hotspots: list[dict[str, Any]], fresh_reset_reentry_rebuild_signal_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" reset_status = str( - primary_target.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + primary_target.get( + "closure_forecast_reset_reentry_rebuild_reset_status", "none" + ) ) freshness_status = str( - primary_target.get("closure_forecast_reset_reentry_rebuild_freshness_status", "insufficient-data") + primary_target.get( + "closure_forecast_reset_reentry_rebuild_freshness_status", + "insufficient-data", + ) ) confirmation_rate = float( primary_target.get("decayed_rebuilt_confirmation_reentry_rate", 0.0) or 0.0 @@ -2657,20 +2767,11 @@ def apply_reset_reentry_rebuild_freshness_and_reset( *, current_generated_at: str, confidence_calibration: dict[str, Any], - recommendation_bucket: Callable[[dict[str, Any]], Any], class_closure_forecast_events: Callable[..., list[dict[str, Any]]], class_transition_events: Callable[..., list[dict[str, Any]]], - target_class_transition_history: Callable[[dict[str, Any], list[dict[str, Any]]], dict[str, Any]], - target_class_key: Callable[[dict[str, Any]], str], - target_label: Callable[[dict[str, Any]], str], - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], - closure_forecast_reset_reentry_rebuild_side_from_persistence_status: Callable[[str], str], - closure_forecast_reset_reentry_rebuild_side_from_status: Callable[[str], str], - closure_forecast_freshness_status: Callable[[float, float], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - class_memory_recency_weights: tuple[float, ...], - class_reset_reentry_rebuild_freshness_window_runs: int, - history_window_runs: int, + target_class_transition_history: Callable[ + [dict[str, Any], list[dict[str, Any]]], dict[str, Any] + ], ) -> dict[str, Any]: del confidence_calibration if not resolution_targets: @@ -2683,7 +2784,7 @@ def apply_reset_reentry_rebuild_freshness_and_reset( "closure_forecast_reset_reentry_rebuild_reset_summary": "No reset re-entry rebuild reset is recorded because there is no active target.", "stale_reset_reentry_rebuild_hotspots": [], "fresh_reset_reentry_rebuild_signal_hotspots": [], - "closure_forecast_reset_reentry_rebuild_decay_window_runs": class_reset_reentry_rebuild_freshness_window_runs, + "closure_forecast_reset_reentry_rebuild_decay_window_runs": CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS, } current_primary_target = resolution_targets[0] @@ -2709,53 +2810,62 @@ def apply_reset_reentry_rebuild_freshness_and_reset( signal_mix = "" reset_status = "none" reset_reason = "" - closure_likely_outcome = str(target.get("transition_closure_likely_outcome", "none")) - closure_hysteresis_status = str(target.get("closure_forecast_hysteresis_status", "none")) - closure_hysteresis_reason = str(target.get("closure_forecast_hysteresis_reason", "")) + closure_likely_outcome = str( + target.get("transition_closure_likely_outcome", "none") + ) + closure_hysteresis_status = str( + target.get("closure_forecast_hysteresis_status", "none") + ) + closure_hysteresis_reason = str( + target.get("closure_forecast_hysteresis_reason", "") + ) transition_status = str(target.get("class_reweight_transition_status", "none")) transition_reason = str(target.get("class_reweight_transition_reason", "")) - resolution_status = str(target.get("class_transition_resolution_status", "none")) + resolution_status = str( + target.get("class_transition_resolution_status", "none") + ) resolution_reason = str(target.get("class_transition_resolution_reason", "")) - rebuild_status = str(target.get("closure_forecast_reset_reentry_rebuild_status", "none")) - rebuild_reason = str(target.get("closure_forecast_reset_reentry_rebuild_reason", "")) - persistence_age_runs = int(target.get("closure_forecast_reset_reentry_rebuild_age_runs", 0) or 0) + rebuild_status = str( + target.get("closure_forecast_reset_reentry_rebuild_status", "none") + ) + rebuild_reason = str( + target.get("closure_forecast_reset_reentry_rebuild_reason", "") + ) + persistence_age_runs = int( + target.get("closure_forecast_reset_reentry_rebuild_age_runs", 0) or 0 + ) persistence_score = float( - target.get("closure_forecast_reset_reentry_rebuild_persistence_score", 0.0) or 0.0 + target.get("closure_forecast_reset_reentry_rebuild_persistence_score", 0.0) + or 0.0 ) persistence_status = str( - target.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") + target.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", "none" + ) ) persistence_reason = str( target.get("closure_forecast_reset_reentry_rebuild_persistence_reason", "") ) if recommendation_bucket(target) == current_bucket: - transition_history_meta = target_class_transition_history(target, transition_events) - freshness_meta = closure_forecast_reset_reentry_rebuild_freshness_for_target( - target, - closure_forecast_events, - target_class_key=target_class_key, - closure_forecast_reset_reentry_rebuild_side_from_event=( - closure_forecast_reset_reentry_rebuild_side_from_event - ), - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - closure_forecast_reset_reentry_rebuild_side_from_status - ), - closure_forecast_freshness_status=closure_forecast_freshness_status, - class_memory_recency_weights=class_memory_recency_weights, - class_reset_reentry_rebuild_freshness_window_runs=( - class_reset_reentry_rebuild_freshness_window_runs - ), - history_window_runs=history_window_runs, + transition_history_meta = target_class_transition_history( + target, transition_events + ) + freshness_meta = ( + closure_forecast_reset_reentry_rebuild_freshness_for_target( + target, + closure_forecast_events, + ) ) freshness_status = str( - freshness_meta["closure_forecast_reset_reentry_rebuild_freshness_status"] + freshness_meta[ + "closure_forecast_reset_reentry_rebuild_freshness_status" + ] ) freshness_reason = str( - freshness_meta["closure_forecast_reset_reentry_rebuild_freshness_reason"] + freshness_meta[ + "closure_forecast_reset_reentry_rebuild_freshness_reason" + ] ) memory_weight = float( freshness_meta["closure_forecast_reset_reentry_rebuild_memory_weight"] @@ -2784,36 +2894,53 @@ def apply_reset_reentry_rebuild_freshness_and_reset( persistence_score=persistence_score, persistence_status=persistence_status, persistence_reason=persistence_reason, - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - closure_forecast_reset_reentry_rebuild_side_from_status - ), - target_specific_normalization_noise=target_specific_normalization_noise, ) - reset_status = str(control_updates["closure_forecast_reset_reentry_rebuild_reset_status"]) - reset_reason = str(control_updates["closure_forecast_reset_reentry_rebuild_reset_reason"]) - closure_likely_outcome = str(control_updates["transition_closure_likely_outcome"]) - closure_hysteresis_status = str(control_updates["closure_forecast_hysteresis_status"]) - closure_hysteresis_reason = str(control_updates["closure_forecast_hysteresis_reason"]) - transition_status = str(control_updates["class_reweight_transition_status"]) - transition_reason = str(control_updates["class_reweight_transition_reason"]) - resolution_status = str(control_updates["class_transition_resolution_status"]) - resolution_reason = str(control_updates["class_transition_resolution_reason"]) - rebuild_status = str(control_updates["closure_forecast_reset_reentry_rebuild_status"]) - rebuild_reason = str(control_updates["closure_forecast_reset_reentry_rebuild_reason"]) + reset_status = str( + control_updates["closure_forecast_reset_reentry_rebuild_reset_status"] + ) + reset_reason = str( + control_updates["closure_forecast_reset_reentry_rebuild_reset_reason"] + ) + closure_likely_outcome = str( + control_updates["transition_closure_likely_outcome"] + ) + closure_hysteresis_status = str( + control_updates["closure_forecast_hysteresis_status"] + ) + closure_hysteresis_reason = str( + control_updates["closure_forecast_hysteresis_reason"] + ) + transition_status = str(control_updates["class_reweight_transition_status"]) + transition_reason = str(control_updates["class_reweight_transition_reason"]) + resolution_status = str( + control_updates["class_transition_resolution_status"] + ) + resolution_reason = str( + control_updates["class_transition_resolution_reason"] + ) + rebuild_status = str( + control_updates["closure_forecast_reset_reentry_rebuild_status"] + ) + rebuild_reason = str( + control_updates["closure_forecast_reset_reentry_rebuild_reason"] + ) persistence_age_runs = int( control_updates["closure_forecast_reset_reentry_rebuild_age_runs"] ) persistence_score = float( - control_updates["closure_forecast_reset_reentry_rebuild_persistence_score"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_persistence_score" + ] ) persistence_status = str( - control_updates["closure_forecast_reset_reentry_rebuild_persistence_status"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_persistence_status" + ] ) persistence_reason = str( - control_updates["closure_forecast_reset_reentry_rebuild_persistence_reason"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_persistence_reason" + ] ) updated_targets.append( @@ -2845,16 +2972,16 @@ def apply_reset_reentry_rebuild_freshness_and_reset( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - stale_reset_reentry_rebuild_hotspots = closure_forecast_reset_reentry_rebuild_freshness_hotspots( - resolution_targets, - mode="stale", - target_class_key=target_class_key, + stale_reset_reentry_rebuild_hotspots = ( + closure_forecast_reset_reentry_rebuild_freshness_hotspots( + resolution_targets, + mode="stale", + ) ) fresh_reset_reentry_rebuild_signal_hotspots = ( closure_forecast_reset_reentry_rebuild_freshness_hotspots( resolution_targets, mode="fresh", - target_class_key=target_class_key, ) ) return { @@ -2871,7 +2998,6 @@ def apply_reset_reentry_rebuild_freshness_and_reset( primary_target, stale_reset_reentry_rebuild_hotspots, fresh_reset_reentry_rebuild_signal_hotspots, - target_label=target_label, ) ), "primary_target_closure_forecast_reset_reentry_rebuild_reset_status": primary_target.get( @@ -2887,12 +3013,11 @@ def apply_reset_reentry_rebuild_freshness_and_reset( primary_target, stale_reset_reentry_rebuild_hotspots, fresh_reset_reentry_rebuild_signal_hotspots, - target_label=target_label, ) ), "stale_reset_reentry_rebuild_hotspots": stale_reset_reentry_rebuild_hotspots, "fresh_reset_reentry_rebuild_signal_hotspots": fresh_reset_reentry_rebuild_signal_hotspots, - "closure_forecast_reset_reentry_rebuild_decay_window_runs": class_reset_reentry_rebuild_freshness_window_runs, + "closure_forecast_reset_reentry_rebuild_decay_window_runs": CLASS_RESET_REENTRY_REBUILD_FRESHNESS_WINDOW_RUNS, } @@ -2930,13 +3055,7 @@ def _persistence_for_target_base( transition_history_meta: dict[str, Any], *, spec: _PersistenceTierSpec, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], side_from_event: Callable[[dict[str, Any]], str], - closure_forecast_direction_majority: Callable[[list[str]], str], - closure_forecast_direction_reversing: Callable[[str, str], bool], - clamp_round: Callable[..., float], path_label: Callable[[dict[str, Any]], str], persistence_window_runs: int, ) -> dict[str, Any]: @@ -3113,10 +3232,16 @@ def _persistence_for_target_base( freshness_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status", reset_key="closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status", settled_values=frozenset( - {"rererestored-confirmation-rebuild-reentry", "rererestored-clearance-rebuild-reentry"} + { + "rererestored-confirmation-rebuild-reentry", + "rererestored-clearance-rebuild-reentry", + } ), settling_values=frozenset( - {"rererestoring-confirmation-rebuild-reentry", "rererestoring-clearance-rebuild-reentry"} + { + "rererestoring-confirmation-rebuild-reentry", + "rererestoring-clearance-rebuild-reentry", + } ), just_value="just-rererestored", sustained_confirmation="sustained-confirmation-rebuild-reentry-rererestore", @@ -3144,29 +3269,15 @@ def closure_forecast_reset_reentry_rebuild_persistence_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], - closure_forecast_direction_majority: Callable[[list[str]], str], - closure_forecast_direction_reversing: Callable[[str, str], bool], - clamp_round: Callable[..., float], - closure_forecast_reset_reentry_rebuild_path_label: Callable[[dict[str, Any]], str], - class_reset_reentry_rebuild_persistence_window_runs: int, ) -> dict[str, Any]: return _persistence_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_REBUILD_PERSISTENCE_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, side_from_event=closure_forecast_reset_reentry_rebuild_side_from_event, - closure_forecast_direction_majority=closure_forecast_direction_majority, - closure_forecast_direction_reversing=closure_forecast_direction_reversing, - clamp_round=clamp_round, path_label=closure_forecast_reset_reentry_rebuild_path_label, - persistence_window_runs=class_reset_reentry_rebuild_persistence_window_runs, + persistence_window_runs=CLASS_RESET_REENTRY_REBUILD_PERSISTENCE_WINDOW_RUNS, ) @@ -3193,15 +3304,7 @@ def _churn_for_target_base( transition_history_meta: dict[str, Any], *, spec: _ChurnTierSpec, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], side_from_event: Callable[[dict[str, Any]], str], - class_direction_flip_count: Callable[[list[str]], int], - target_specific_normalization_noise: Callable[ - [dict[str, Any], dict[str, Any]], bool - ], - clamp_round: Callable[..., float], path_label: Callable[[dict[str, Any]], str], window_runs: int, ) -> dict[str, Any]: @@ -3316,29 +3419,15 @@ def closure_forecast_reset_reentry_rebuild_churn_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_reentry_rebuild_side_from_event: Callable[[dict[str, Any]], str], - class_direction_flip_count: Callable[[list[str]], int], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - clamp_round: Callable[..., float], - closure_forecast_reset_reentry_rebuild_path_label: Callable[[dict[str, Any]], str], - class_reset_reentry_rebuild_persistence_window_runs: int, ) -> dict[str, Any]: return _churn_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_REBUILD_CHURN_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, side_from_event=closure_forecast_reset_reentry_rebuild_side_from_event, - class_direction_flip_count=class_direction_flip_count, - target_specific_normalization_noise=target_specific_normalization_noise, - clamp_round=clamp_round, path_label=closure_forecast_reset_reentry_rebuild_path_label, - window_runs=class_reset_reentry_rebuild_persistence_window_runs, + window_runs=CLASS_RESET_REENTRY_REBUILD_PERSISTENCE_WINDOW_RUNS, ) @@ -3355,27 +3444,45 @@ def apply_reset_reentry_rebuild_persistence_and_churn_control( transition_reason: str, resolution_status: str, resolution_reason: str, - closure_forecast_reset_reentry_rebuild_side_from_status: Callable[[str], str], - closure_forecast_reset_reentry_rebuild_side_from_recovery_status: Callable[[str], str], ) -> dict[str, Any]: persistence_status = str( - persistence_meta.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") + persistence_meta.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", "none" + ) ) persistence_reason = str( - persistence_meta.get("closure_forecast_reset_reentry_rebuild_persistence_reason", "") + persistence_meta.get( + "closure_forecast_reset_reentry_rebuild_persistence_reason", "" + ) + ) + churn_status = str( + churn_meta.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") + ) + churn_reason = str( + churn_meta.get("closure_forecast_reset_reentry_rebuild_churn_reason", "") + ) + current_rebuild_status = str( + target.get("closure_forecast_reset_reentry_rebuild_status", "none") ) - churn_status = str(churn_meta.get("closure_forecast_reset_reentry_rebuild_churn_status", "none")) - churn_reason = str(churn_meta.get("closure_forecast_reset_reentry_rebuild_churn_reason", "")) - current_rebuild_status = str(target.get("closure_forecast_reset_reentry_rebuild_status", "none")) current_freshness_status = str( - target.get("closure_forecast_reset_reentry_freshness_status", "insufficient-data") + target.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) ) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) - current_side = closure_forecast_reset_reentry_rebuild_side_from_status(current_rebuild_status) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) + current_side = closure_forecast_reset_reentry_rebuild_side_from_status( + current_rebuild_status + ) if current_side == "none": current_side = closure_forecast_reset_reentry_rebuild_side_from_recovery_status( - str(target.get("closure_forecast_reset_reentry_refresh_recovery_status", "none")) + str( + target.get( + "closure_forecast_reset_reentry_refresh_recovery_status", "none" + ) + ) ) if ( current_side == "none" @@ -3397,7 +3504,9 @@ def apply_reset_reentry_rebuild_persistence_and_churn_control( closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": closure_hysteresis_status = "pending-confirmation" - closure_hysteresis_reason = churn_reason or persistence_reason or closure_hysteresis_reason + closure_hysteresis_reason = ( + churn_reason or persistence_reason or closure_hysteresis_reason + ) return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -3434,11 +3543,14 @@ def apply_reset_reentry_rebuild_persistence_and_churn_control( closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": closure_hysteresis_status = "pending-confirmation" - closure_hysteresis_reason = churn_reason or persistence_reason or closure_hysteresis_reason + closure_hysteresis_reason = ( + churn_reason or persistence_reason or closure_hysteresis_reason + ) if current_rebuild_status == "rebuilt-clearance-reentry": if ( - persistence_status in {"holding-clearance-rebuild", "sustained-clearance-rebuild"} + persistence_status + in {"holding-clearance-rebuild", "sustained-clearance-rebuild"} and churn_status != "churn" ): if closure_likely_outcome == "expire-risk" and transition_age_runs < 3: @@ -3466,12 +3578,15 @@ def apply_reset_reentry_rebuild_persistence_and_churn_control( closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-clearance": closure_hysteresis_status = "pending-clearance" - closure_hysteresis_reason = churn_reason or persistence_reason or closure_hysteresis_reason + closure_hysteresis_reason = ( + churn_reason or persistence_reason or closure_hysteresis_reason + ) if ( resolution_status == "cleared" and recent_pending_status in {"pending-support", "pending-caution"} and ( - persistence_status not in {"holding-clearance-rebuild", "sustained-clearance-rebuild"} + persistence_status + not in {"holding-clearance-rebuild", "sustained-clearance-rebuild"} or churn_status == "churn" ) ): @@ -3520,7 +3635,6 @@ def _hotspots_base( *, spec: _HotspotsTierSpec, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -3632,13 +3746,11 @@ def closure_forecast_reset_reentry_rebuild_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: return _hotspots_base( resolution_targets, spec=_REBUILD_HOTSPOTS_SPEC, mode=mode, - target_class_key=target_class_key, ) @@ -3646,15 +3758,22 @@ def closure_forecast_reset_reentry_rebuild_persistence_summary( primary_target: dict[str, Any], just_rebuilt_hotspots: list[dict[str, Any]], holding_reset_reentry_rebuild_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str( - primary_target.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") + primary_target.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", "none" + ) + ) + age_runs = int( + primary_target.get("closure_forecast_reset_reentry_rebuild_age_runs", 0) or 0 + ) + score = float( + primary_target.get( + "closure_forecast_reset_reentry_rebuild_persistence_score", 0.0 + ) + or 0.0 ) - age_runs = int(primary_target.get("closure_forecast_reset_reentry_rebuild_age_runs", 0) or 0) - score = float(primary_target.get("closure_forecast_reset_reentry_rebuild_persistence_score", 0.0) or 0.0) if status == "just-rebuilt": return ( f"{label} has only just rebuilt stronger reset re-entry posture, so it is still fragile " @@ -3686,9 +3805,7 @@ def closure_forecast_reset_reentry_rebuild_persistence_summary( f"({score:.2f})." ) if status == "insufficient-data": - return ( - f"Rebuilt reset re-entry for {label} is still too lightly exercised to say whether the restored forecast can hold." - ) + return f"Rebuilt reset re-entry for {label} is still too lightly exercised to say whether the restored forecast can hold." if just_rebuilt_hotspots: hotspot = just_rebuilt_hotspots[0] return ( @@ -3707,12 +3824,17 @@ def closure_forecast_reset_reentry_rebuild_persistence_summary( def closure_forecast_reset_reentry_rebuild_churn_summary( primary_target: dict[str, Any], reset_reentry_rebuild_churn_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" - status = str(primary_target.get("closure_forecast_reset_reentry_rebuild_churn_status", "none")) - score = float(primary_target.get("closure_forecast_reset_reentry_rebuild_churn_score", 0.0) or 0.0) + status = str( + primary_target.get( + "closure_forecast_reset_reentry_rebuild_churn_status", "none" + ) + ) + score = float( + primary_target.get("closure_forecast_reset_reentry_rebuild_churn_score", 0.0) + or 0.0 + ) if status == "watch": return ( f"Rebuilt reset re-entry for {label} is wobbling enough that restored forecast strength may soften soon " @@ -3777,17 +3899,6 @@ def _recovery_for_target_base( transition_history_meta: dict[str, Any], *, spec: _RecoveryTierSpec, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_side_from_status: Callable[[str], str], - normalized_closure_forecast_direction: Callable[[str, float], str], - clamp_round: Callable[..., float], - closure_forecast_direction_majority: Callable[[list[str]], str], - target_specific_normalization_noise: Callable[ - [dict[str, Any], dict[str, Any]], bool - ], - closure_forecast_direction_reversing: Callable[[str, str], bool], path_label: Callable[[dict[str, Any]], str], window_runs: int, ) -> dict[str, Any]: @@ -4062,28 +4173,28 @@ def _recovery_for_target_base( _RESET_REENTRY_RECOVERY_SPEC = _RecoveryTierSpec( - reset_key='closure_forecast_reset_reentry_reset_status', - freshness_key='closure_forecast_reset_reentry_freshness_status', - restoring_confirmation='rebuilding-confirmation-reentry', - restoring_clearance='rebuilding-clearance-reentry', - recovering_confirmation='recovering-confirmation-reentry-reset', - recovering_clearance='recovering-clearance-reentry-reset', - restored_confirmation='rebuilt-confirmation-reentry', - restored_clearance='rebuilt-clearance-reentry', - pending_confirmation='pending-confirmation-rebuild', - pending_clearance='pending-clearance-rebuild', - reason_restored_confirmation='Fresh confirmation-side follow-through has rebuilt stronger confirmation-side reset re-entry.', - reason_restored_clearance='Fresh clearance-side pressure has rebuilt stronger clearance-side reset re-entry.', - reason_blocked='Local target instability is still preventing positive confirmation-side reset re-entry rebuild.', - reason_pending_confirmation='Fresh confirmation-side evidence is returning after reset re-entry was softened or reset, but it has not yet rebuilt stronger reset re-entry.', - reason_pending_clearance='Fresh clearance-side evidence is returning after reset re-entry was softened or reset, but it has not yet rebuilt stronger reset re-entry.', - score_key='closure_forecast_reset_reentry_refresh_recovery_score', - recovery_status_key='closure_forecast_reset_reentry_refresh_recovery_status', - next_status_key='closure_forecast_reset_reentry_rebuild_status', - next_reason_key='closure_forecast_reset_reentry_rebuild_reason', - path_key='recent_reset_reentry_refresh_path', - reset_side_key='recent_reset_reentry_side', - aligned_fresh_key='aligned_fresh_runs_after_latest_reset_reentry_reset', + reset_key="closure_forecast_reset_reentry_reset_status", + freshness_key="closure_forecast_reset_reentry_freshness_status", + restoring_confirmation="rebuilding-confirmation-reentry", + restoring_clearance="rebuilding-clearance-reentry", + recovering_confirmation="recovering-confirmation-reentry-reset", + recovering_clearance="recovering-clearance-reentry-reset", + restored_confirmation="rebuilt-confirmation-reentry", + restored_clearance="rebuilt-clearance-reentry", + pending_confirmation="pending-confirmation-rebuild", + pending_clearance="pending-clearance-rebuild", + reason_restored_confirmation="Fresh confirmation-side follow-through has rebuilt stronger confirmation-side reset re-entry.", + reason_restored_clearance="Fresh clearance-side pressure has rebuilt stronger clearance-side reset re-entry.", + reason_blocked="Local target instability is still preventing positive confirmation-side reset re-entry rebuild.", + reason_pending_confirmation="Fresh confirmation-side evidence is returning after reset re-entry was softened or reset, but it has not yet rebuilt stronger reset re-entry.", + reason_pending_clearance="Fresh clearance-side evidence is returning after reset re-entry was softened or reset, but it has not yet rebuilt stronger reset re-entry.", + score_key="closure_forecast_reset_reentry_refresh_recovery_score", + recovery_status_key="closure_forecast_reset_reentry_refresh_recovery_status", + next_status_key="closure_forecast_reset_reentry_rebuild_status", + next_reason_key="closure_forecast_reset_reentry_rebuild_reason", + path_key="recent_reset_reentry_refresh_path", + reset_side_key="recent_reset_reentry_side", + aligned_fresh_key="aligned_fresh_runs_after_latest_reset_reentry_reset", ) @@ -4091,35 +4202,14 @@ def closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_side_from_status: Callable[[str], str], - normalized_closure_forecast_direction: Callable[[str, float], str], - clamp_round: Callable[..., float], - closure_forecast_direction_majority: Callable[[list[str]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label: Callable[ - [dict[str, Any]], str - ], - class_reset_reentry_rebuild_reentry_refresh_restore_window_runs: int, ) -> dict[str, Any]: return _recovery_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_REBUILD_RECOVERY_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=normalized_closure_forecast_direction, - clamp_round=clamp_round, - closure_forecast_direction_majority=closure_forecast_direction_majority, - target_specific_normalization_noise=target_specific_normalization_noise, - closure_forecast_direction_reversing=closure_forecast_direction_reversing, path_label=closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label, - window_runs=class_reset_reentry_rebuild_reentry_refresh_restore_window_runs, + window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS, ) @@ -4143,23 +4233,35 @@ def apply_reset_reentry_rebuild_reentry_refresh_restore_control( persistence_reason: str, ) -> dict[str, Any]: recovery_status = str( - refresh_meta.get("closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", "none") + refresh_meta.get( + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + "none", + ) ) restore_status = str( - refresh_meta.get("closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none") + refresh_meta.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) ) restore_reason = str( - refresh_meta.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reason", "") + refresh_meta.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_reason", "" + ) ) recent_rebuild_reentry_reset_side = str( refresh_meta.get("recent_rebuild_reentry_reset_side", "none") ) current_freshness = str( - target.get("closure_forecast_reset_reentry_rebuild_reentry_freshness_status", "insufficient-data") + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", + "insufficient-data", + ) ) current_stability = str(target.get("closure_forecast_stability_status", "watch")) transition_age_runs = int(target.get("class_transition_age_runs", 0) or 0) - recent_pending_status = str(transition_history_meta.get("recent_pending_status", "none")) + recent_pending_status = str( + transition_history_meta.get("recent_pending_status", "none") + ) decayed_clearance_rate = float( target.get("decayed_reentered_rebuild_clearance_rate", 0.0) or 0.0 ) @@ -4259,7 +4361,10 @@ def apply_reset_reentry_rebuild_reentry_refresh_restore_control( "closure_forecast_reset_reentry_rebuild_reentry_persistence_status": "none", "closure_forecast_reset_reentry_rebuild_reentry_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -4302,7 +4407,10 @@ def apply_reset_reentry_rebuild_reentry_refresh_restore_control( "closure_forecast_reset_reentry_rebuild_reentry_persistence_status": "none", "closure_forecast_reset_reentry_rebuild_reentry_persistence_reason": "", } - if recovery_status == "reversing" or current_freshness in {"stale", "insufficient-data"}: + if recovery_status == "reversing" or current_freshness in { + "stale", + "insufficient-data", + }: return { "transition_closure_likely_outcome": closure_likely_outcome, "closure_forecast_hysteresis_status": closure_hysteresis_status, @@ -4340,13 +4448,11 @@ def closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: return _refresh_hotspots_base( resolution_targets, spec=_REBUILD_REENTRY_REFRESH_HOTSPOTS_SPEC, mode=mode, - target_class_key=target_class_key, ) @@ -4354,15 +4460,12 @@ def closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: return _refresh_recovery_summary_base( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, spec=_REBUILD_REENTRY_REFRESH_RECOVERY_SUMMARY_SPEC, - target_label=target_label, ) @@ -4370,15 +4473,12 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_summary( primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: return _tier_summary_base( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, spec=_RESTORE_SUMMARY_SPEC, - target_label=target_label, ) @@ -4388,25 +4488,11 @@ def apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( *, current_generated_at: str, confidence_calibration: dict[str, Any], - recommendation_bucket: Callable[[dict[str, Any]], Any], class_closure_forecast_events: Callable[..., list[dict[str, Any]]], class_transition_events: Callable[..., list[dict[str, Any]]], - target_class_transition_history: Callable[[dict[str, Any], list[dict[str, Any]]], dict[str, Any]], - target_class_key: Callable[[dict[str, Any]], str], - target_label: Callable[[dict[str, Any]], str], - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_side_from_status: Callable[[str], str], - normalized_closure_forecast_direction: Callable[[str, float], str], - clamp_round: Callable[..., float], - closure_forecast_direction_majority: Callable[[list[str]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label: Callable[ - [dict[str, Any]], str + target_class_transition_history: Callable[ + [dict[str, Any], list[dict[str, Any]]], dict[str, Any] ], - class_reset_reentry_rebuild_reentry_refresh_restore_window_runs: int, ) -> dict[str, Any]: del confidence_calibration if not resolution_targets: @@ -4417,7 +4503,7 @@ def apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary": "No reset re-entry rebuild re-entry refresh recovery is recorded because there is no active target.", "closure_forecast_reset_reentry_rebuild_reentry_restore_summary": "No reset re-entry rebuild re-entry restore is recorded because there is no active target.", - "closure_forecast_reset_reentry_rebuild_reentry_refresh_window_runs": class_reset_reentry_rebuild_reentry_refresh_restore_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_refresh_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS, "recovering_from_confirmation_rebuild_reentry_reset_hotspots": [], "recovering_from_clearance_rebuild_reentry_reset_hotspots": [], } @@ -4442,97 +4528,143 @@ def apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( restore_status = "none" restore_reason = "" refresh_path = "" - closure_likely_outcome = str(target.get("transition_closure_likely_outcome", "none")) - closure_hysteresis_status = str(target.get("closure_forecast_hysteresis_status", "none")) - closure_hysteresis_reason = str(target.get("closure_forecast_hysteresis_reason", "")) + closure_likely_outcome = str( + target.get("transition_closure_likely_outcome", "none") + ) + closure_hysteresis_status = str( + target.get("closure_forecast_hysteresis_status", "none") + ) + closure_hysteresis_reason = str( + target.get("closure_forecast_hysteresis_reason", "") + ) transition_status = str(target.get("class_reweight_transition_status", "none")) transition_reason = str(target.get("class_reweight_transition_reason", "")) - resolution_status = str(target.get("class_transition_resolution_status", "none")) + resolution_status = str( + target.get("class_transition_resolution_status", "none") + ) resolution_reason = str(target.get("class_transition_resolution_reason", "")) - reentry_status = str(target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none")) - reentry_reason = str(target.get("closure_forecast_reset_reentry_rebuild_reentry_reason", "")) - persistence_age_runs = int(target.get("closure_forecast_reset_reentry_rebuild_reentry_age_runs", 0) or 0) + reentry_status = str( + target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") + ) + reentry_reason = str( + target.get("closure_forecast_reset_reentry_rebuild_reentry_reason", "") + ) + persistence_age_runs = int( + target.get("closure_forecast_reset_reentry_rebuild_reentry_age_runs", 0) + or 0 + ) persistence_score = float( - target.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_score", 0.0) or 0.0 + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_score", 0.0 + ) + or 0.0 ) persistence_status = str( - target.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_status", "none") + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", + "none", + ) ) persistence_reason = str( - target.get("closure_forecast_reset_reentry_rebuild_reentry_persistence_reason", "") + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_reason", "" + ) ) if recommendation_bucket(target) == current_bucket: - transition_history_meta = target_class_transition_history(target, transition_events) + transition_history_meta = target_class_transition_history( + target, transition_events + ) refresh_meta = closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_for_target( target, closure_forecast_events, transition_history_meta, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=normalized_closure_forecast_direction, - clamp_round=clamp_round, - closure_forecast_direction_majority=closure_forecast_direction_majority, - target_specific_normalization_noise=target_specific_normalization_noise, - closure_forecast_direction_reversing=closure_forecast_direction_reversing, - closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label=( - closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label - ), - class_reset_reentry_rebuild_reentry_refresh_restore_window_runs=( - class_reset_reentry_rebuild_reentry_refresh_restore_window_runs - ), ) refresh_recovery_score = float( - refresh_meta["closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score"] + refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score" + ] ) refresh_recovery_status = str( - refresh_meta["closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status"] + refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status" + ] ) restore_status = str( - refresh_meta["closure_forecast_reset_reentry_rebuild_reentry_restore_status"] + refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_status" + ] ) restore_reason = str( - refresh_meta["closure_forecast_reset_reentry_rebuild_reentry_restore_reason"] + refresh_meta[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_reason" + ] ) - refresh_path = str(refresh_meta["recent_reset_reentry_rebuild_reentry_refresh_path"]) - control_updates = apply_reset_reentry_rebuild_reentry_refresh_restore_control( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, + refresh_path = str( + refresh_meta["recent_reset_reentry_rebuild_reentry_refresh_path"] + ) + control_updates = ( + apply_reset_reentry_rebuild_reentry_refresh_restore_control( + target, + refresh_meta=refresh_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + persistence_age_runs=persistence_age_runs, + persistence_score=persistence_score, + persistence_status=persistence_status, + persistence_reason=persistence_reason, + ) + ) + closure_likely_outcome = str( + control_updates["transition_closure_likely_outcome"] + ) + closure_hysteresis_status = str( + control_updates["closure_forecast_hysteresis_status"] + ) + closure_hysteresis_reason = str( + control_updates["closure_forecast_hysteresis_reason"] ) - closure_likely_outcome = str(control_updates["transition_closure_likely_outcome"]) - closure_hysteresis_status = str(control_updates["closure_forecast_hysteresis_status"]) - closure_hysteresis_reason = str(control_updates["closure_forecast_hysteresis_reason"]) transition_status = str(control_updates["class_reweight_transition_status"]) transition_reason = str(control_updates["class_reweight_transition_reason"]) - resolution_status = str(control_updates["class_transition_resolution_status"]) - resolution_reason = str(control_updates["class_transition_resolution_reason"]) - reentry_status = str(control_updates["closure_forecast_reset_reentry_rebuild_reentry_status"]) - reentry_reason = str(control_updates["closure_forecast_reset_reentry_rebuild_reentry_reason"]) + resolution_status = str( + control_updates["class_transition_resolution_status"] + ) + resolution_reason = str( + control_updates["class_transition_resolution_reason"] + ) + reentry_status = str( + control_updates["closure_forecast_reset_reentry_rebuild_reentry_status"] + ) + reentry_reason = str( + control_updates["closure_forecast_reset_reentry_rebuild_reentry_reason"] + ) persistence_age_runs = int( - control_updates["closure_forecast_reset_reentry_rebuild_reentry_age_runs"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_reentry_age_runs" + ] ) persistence_score = float( - control_updates["closure_forecast_reset_reentry_rebuild_reentry_persistence_score"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_reentry_persistence_score" + ] ) persistence_status = str( - control_updates["closure_forecast_reset_reentry_rebuild_reentry_persistence_status"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status" + ] ) persistence_reason = str( - control_updates["closure_forecast_reset_reentry_rebuild_reentry_persistence_reason"] + control_updates[ + "closure_forecast_reset_reentry_rebuild_reentry_persistence_reason" + ] ) updated_targets.append( @@ -4561,15 +4693,17 @@ def apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - recovering_confirmation_hotspots = closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots( - resolution_targets, - mode="confirmation", - target_class_key=target_class_key, + recovering_confirmation_hotspots = ( + closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots( + resolution_targets, + mode="confirmation", + ) ) - recovering_clearance_hotspots = closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots( - resolution_targets, - mode="clearance", - target_class_key=target_class_key, + recovering_clearance_hotspots = ( + closure_forecast_reset_reentry_rebuild_reentry_refresh_hotspots( + resolution_targets, + mode="clearance", + ) ) return { "primary_target_closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_score": primary_target.get( @@ -4593,7 +4727,6 @@ def apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, - target_label=target_label, ) ), "closure_forecast_reset_reentry_rebuild_reentry_restore_summary": ( @@ -4601,10 +4734,9 @@ def apply_reset_reentry_rebuild_reentry_refresh_recovery_and_restore( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, - target_label=target_label, ) ), - "closure_forecast_reset_reentry_rebuild_reentry_refresh_window_runs": class_reset_reentry_rebuild_reentry_refresh_restore_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_refresh_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_REFRESH_RESTORE_WINDOW_RUNS, "recovering_from_confirmation_rebuild_reentry_reset_hotspots": recovering_confirmation_hotspots, "recovering_from_clearance_rebuild_reentry_reset_hotspots": recovering_clearance_hotspots, } @@ -4678,14 +4810,12 @@ def _rererestore_freshness_reason( recent_window_weight_share: float, decayed_confirmation_rate: float, decayed_clearance_rate: float, - *, - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs: int, ) -> str: if freshness_status == "fresh": return ( "Recent re-re-restored rebuilt re-entry evidence is still current enough to keep the stronger re-re-restored posture trusted, with " f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest " - f"{class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs} runs." + f"{CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS} runs." ) if freshness_status == "mixed-age": return ( @@ -4693,9 +4823,7 @@ def _rererestore_freshness_reason( f"{recent_window_weight_share:.0%} of the weighted signal is recent and the rest is older carry-forward." ) if freshness_status == "stale": - return ( - "Older re-re-restored rebuilt re-entry strength is carrying more of the signal than recent runs, so it should not keep stronger posture alive on memory alone." - ) + return "Older re-re-restored rebuilt re-entry strength is carrying more of the signal than recent runs, so it should not keep stronger posture alive on memory alone." return ( "Re-re-restored rebuilt re-entry memory is still too lightly exercised to judge freshness, with " f"{weighted_rererestore_evidence_count:.2f} weighted re-re-restored run(s), " @@ -4719,71 +4847,52 @@ def _recent_rererestore_signal_mix( def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target( target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], - *, - target_class_key: Callable[[dict[str, Any]], str], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status: Callable[ - [str], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status: Callable[ - [str], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event: Callable[ - [dict[str, Any]], str - ], - closure_forecast_freshness_status: Callable[[float, float], str], - class_memory_recency_weights: tuple[float, ...], - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs: int, - history_window_runs: int, ) -> dict[str, Any]: class_key = target_class_key(target) class_events = [ - event for event in closure_forecast_events if event.get("class_key") == class_key + event + for event in closure_forecast_events + if event.get("class_key") == class_key ] relevant_events: list[dict[str, Any]] = [] for event in class_events: if not _rererestore_event_has_evidence(event): continue relevant_events.append(event) - if len(relevant_events) >= history_window_runs: + if len(relevant_events) >= HISTORY_WINDOW_RUNS: break weighted_rererestore_evidence_count = 0.0 weighted_confirmation_like = 0.0 weighted_clearance_like = 0.0 recent_rererestore_weight = 0.0 - current_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( - str( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", - "none", - ) + current_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( + str( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", + "none", ) ) ) if current_side == "none": - current_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( - str( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", - "none", - ) + current_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( + str( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", + "none", ) ) ) for index, event in enumerate(relevant_events): - weight = class_memory_recency_weights[min(index, history_window_runs - 1)] + weight = CLASS_MEMORY_RECENCY_WEIGHTS[min(index, HISTORY_WINDOW_RUNS - 1)] weighted_rererestore_evidence_count += weight - event_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event( - event - ) + event_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event( + event ) if ( index - < class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs + < CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS and event_side == current_side ): recent_rererestore_weight += weight @@ -4816,9 +4925,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness recent_window_weight_share, decayed_confirmation_rate, decayed_clearance_rate, - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs=( - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs - ), ), "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_memory_weight": round( recent_window_weight_share, @@ -4873,13 +4979,6 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_cont persistence_score: float, persistence_status: str, persistence_reason: str, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status: Callable[ - [str], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status: Callable[ - [str], str - ], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], ) -> dict[str, Any]: freshness_status = str( freshness_meta.get( @@ -4900,16 +4999,12 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_cont "none", ) ) - current_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( - persistence_status - ) + current_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( + persistence_status ) if current_side == "none": - current_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( - rererestore_status - ) + current_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( + rererestore_status ) local_noise = target_specific_normalization_noise(target, transition_history_meta) recent_pending_status = str( @@ -4942,9 +5037,7 @@ def _restore_weaker_pending_posture( ) if local_noise and current_side != "none": - blocked_reason = ( - "Local target instability still overrides healthy re-re-restored built re-entry freshness." - ) + blocked_reason = "Local target instability still overrides healthy re-re-restored built re-entry freshness." if closure_likely_outcome == "confirm-soon": closure_likely_outcome = "hold" elif closure_likely_outcome == "expire-risk": @@ -4979,12 +5072,11 @@ def _restore_weaker_pending_posture( } if current_side == "confirmation" and freshness_status == "mixed-age": - if persistence_status == "sustained-confirmation-rebuild-reentry-rererestore" and ( - churn_status != "churn" or has_fresh_aligned_recent_evidence + if ( + persistence_status == "sustained-confirmation-rebuild-reentry-rererestore" + and (churn_status != "churn" or has_fresh_aligned_recent_evidence) ): - softened_reason = ( - "Re-re-restored confirmation-side rebuilt re-entry is still visible, but it is aging and has been stepped down from sustained strength." - ) + softened_reason = "Re-re-restored confirmation-side rebuilt re-entry is still visible, but it is aging and has been stepped down from sustained strength." return { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_status": "confirmation-softened", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_reason": softened_reason, @@ -5018,9 +5110,7 @@ def _restore_weaker_pending_posture( if persistence_status == "sustained-clearance-rebuild-reentry-rererestore" and ( churn_status != "churn" or has_fresh_aligned_recent_evidence ): - softened_reason = ( - "Re-re-restored clearance-side rebuilt re-entry is still visible, but it is aging and has been stepped down from sustained strength." - ) + softened_reason = "Re-re-restored clearance-side rebuilt re-entry is still visible, but it is aging and has been stepped down from sustained strength." return { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_status": "clearance-softened", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_reason": softened_reason, @@ -5072,9 +5162,7 @@ def _restore_weaker_pending_posture( if needs_reset: if current_side == "confirmation": - reset_reason = ( - "Re-re-restored confirmation-side rebuilt re-entry has aged out enough that the stronger carry-forward has been withdrawn." - ) + reset_reason = "Re-re-restored confirmation-side rebuilt re-entry has aged out enough that the stronger carry-forward has been withdrawn." closure_likely_outcome = "hold" if closure_hysteresis_status == "confirmed-confirmation": closure_hysteresis_status = "pending-confirmation" @@ -5103,9 +5191,7 @@ def _restore_weaker_pending_posture( "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "", } - reset_reason = ( - "Re-re-restored clearance-side rebuilt re-entry has aged out enough that the stronger carry-forward has been withdrawn." - ) + reset_reason = "Re-re-restored clearance-side rebuilt re-entry has aged out enough that the stronger carry-forward has been withdrawn." if closure_likely_outcome == "expire-risk": closure_likely_outcome = "clear-risk" elif closure_likely_outcome == "clear-risk": @@ -5158,9 +5244,7 @@ def _restore_weaker_pending_posture( or churn_status == "churn" ) ): - reset_reason = ( - "Re-re-restored clearance-side rebuilt re-entry has aged out enough that the stronger carry-forward has been withdrawn." - ) + reset_reason = "Re-re-restored clearance-side rebuilt re-entry has aged out enough that the stronger carry-forward has been withdrawn." ( transition_status, transition_reason, @@ -5220,7 +5304,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -5309,12 +5392,12 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary( primary_target: dict[str, Any], - stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[dict[str, Any]], + stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[ + dict[str, Any] + ], fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots: list[ dict[str, Any] ], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" freshness_status = primary_target.get( @@ -5322,40 +5405,30 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness "insufficient-data", ) if freshness_status == "fresh": - return ( - f"{label} still has recent re-re-restored rebuilt re-entry evidence that is current enough to keep the stronger re-re-restored posture trusted." - ) + return f"{label} still has recent re-re-restored rebuilt re-entry evidence that is current enough to keep the stronger re-re-restored posture trusted." if freshness_status == "mixed-age": - return ( - f"{label} still has useful re-re-restored rebuilt re-entry memory, but the stronger posture is no longer getting fully fresh reinforcement." - ) + return f"{label} still has useful re-re-restored rebuilt re-entry memory, but the stronger posture is no longer getting fully fresh reinforcement." if freshness_status == "stale": - return ( - f"{label} is leaning on older re-re-restored rebuilt re-entry strength more than fresh runs, so stronger re-re-restored posture should not keep carrying forward on memory alone." - ) + return f"{label} is leaning on older re-re-restored rebuilt re-entry strength more than fresh runs, so stronger re-re-restored posture should not keep carrying forward on memory alone." if fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots: - hotspot = fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots[0] - return ( - f"Fresh re-re-restored rebuilt re-entry evidence is strongest around {hotspot.get('label', 'recent hotspots')}, so those classes can keep stronger re-re-restored posture more safely than older carry-forward." + hotspot = ( + fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots[0] ) + return f"Fresh re-re-restored rebuilt re-entry evidence is strongest around {hotspot.get('label', 'recent hotspots')}, so those classes can keep stronger re-re-restored posture more safely than older carry-forward." if stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: hotspot = stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots[0] - return ( - f"Older re-re-restored rebuilt re-entry strength is lingering most around {hotspot.get('label', 'recent hotspots')}, so those classes should keep resetting re-re-restored posture when fresh follow-through stops." - ) - return ( - "Re-re-restored rebuilt re-entry memory is still too lightly exercised to say whether stronger re-re-restored posture is being reinforced by fresh evidence or older carry-forward." - ) + return f"Older re-re-restored rebuilt re-entry strength is lingering most around {hotspot.get('label', 'recent hotspots')}, so those classes should keep resetting re-re-restored posture when fresh follow-through stops." + return "Re-re-restored rebuilt re-entry memory is still too lightly exercised to say whether stronger re-re-restored posture is being reinforced by fresh evidence or older carry-forward." def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary( primary_target: dict[str, Any], - stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[dict[str, Any]], + stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[ + dict[str, Any] + ], fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots: list[ dict[str, Any] ], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" reset_status = primary_target.get( @@ -5375,21 +5448,13 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_sum 0.0, ) if reset_status == "confirmation-softened": - return ( - f"Re-re-restored confirmation-side rebuilt re-entry for {label} is still visible, but it is aging and has been stepped down from sustained strength." - ) + return f"Re-re-restored confirmation-side rebuilt re-entry for {label} is still visible, but it is aging and has been stepped down from sustained strength." if reset_status == "clearance-softened": - return ( - f"Re-re-restored clearance-side rebuilt re-entry for {label} is still visible, but it is aging and has been stepped down from sustained strength." - ) + return f"Re-re-restored clearance-side rebuilt re-entry for {label} is still visible, but it is aging and has been stepped down from sustained strength." if reset_status == "confirmation-reset": - return ( - f"Re-re-restored confirmation-side rebuilt re-entry for {label} has aged out enough that the stronger carry-forward has been withdrawn." - ) + return f"Re-re-restored confirmation-side rebuilt re-entry for {label} has aged out enough that the stronger carry-forward has been withdrawn." if reset_status == "clearance-reset": - return ( - f"Re-re-restored clearance-side rebuilt re-entry for {label} has aged out enough that the stronger carry-forward has been withdrawn." - ) + return f"Re-re-restored clearance-side rebuilt re-entry for {label} has aged out enough that the stronger carry-forward has been withdrawn." if reset_status == "blocked": return str( primary_target.get( @@ -5398,30 +5463,20 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_sum ) ) if freshness_status == "fresh" and confirmation_rate >= clearance_rate: - return ( - f"Fresh re-re-restored rebuilt re-entry evidence for {label} is still reinforcing confirmation-side re-re-restored posture more than clearance pressure." - ) + return f"Fresh re-re-restored rebuilt re-entry evidence for {label} is still reinforcing confirmation-side re-re-restored posture more than clearance pressure." if freshness_status == "fresh": - return ( - f"Fresh re-re-restored rebuilt re-entry evidence for {label} is still reinforcing clearance-side re-re-restored posture more than confirmation-side carry-forward." - ) + return f"Fresh re-re-restored rebuilt re-entry evidence for {label} is still reinforcing clearance-side re-re-restored posture more than confirmation-side carry-forward." if freshness_status == "mixed-age": - return ( - f"Re-re-restored rebuilt re-entry posture for {label} is aging enough that it can keep holding, but it should no longer stay indefinitely at sustained strength." - ) + return f"Re-re-restored rebuilt re-entry posture for {label} is aging enough that it can keep holding, but it should no longer stay indefinitely at sustained strength." if stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: hotspot = stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots[0] - return ( - f"Re-re-restored rebuilt re-entry posture is aging out fastest around {hotspot.get('label', 'recent hotspots')}, so those classes should reset re-re-restored carry-forward instead of relying on older follow-through." - ) + return f"Re-re-restored rebuilt re-entry posture is aging out fastest around {hotspot.get('label', 'recent hotspots')}, so those classes should reset re-re-restored carry-forward instead of relying on older follow-through." if fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots: - hotspot = fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots[0] - return ( - f"Fresh re-re-restored rebuilt re-entry follow-through is strongest around {hotspot.get('label', 'recent hotspots')}, so those classes can preserve re-re-restored posture longer than aging carry-forward elsewhere." + hotspot = ( + fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots[0] ) - return ( - "No re-re-restored rebuilt re-entry reset is changing the current stronger closure-forecast posture right now." - ) + return f"Fresh re-re-restored rebuilt re-entry follow-through is strongest around {hotspot.get('label', 'recent hotspots')}, so those classes can preserve re-re-restored posture longer than aging carry-forward elsewhere." + return "No re-re-restored rebuilt re-entry reset is changing the current stronger closure-forecast posture right now." def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( @@ -5430,24 +5485,11 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( *, current_generated_at: str, confidence_calibration: dict[str, Any], - recommendation_bucket: Callable[[dict[str, Any]], object], class_closure_forecast_events: Callable[..., list[dict[str, Any]]], class_transition_events: Callable[..., list[dict[str, Any]]], - target_class_transition_history: Callable[[dict[str, Any], list[dict[str, Any]]], dict[str, Any]], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target: Callable[ + target_class_transition_history: Callable[ [dict[str, Any], list[dict[str, Any]]], dict[str, Any] ], - apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control: Callable[..., dict[str, Any]], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots: Callable[ - ..., list[dict[str, Any]] - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary: Callable[ - [dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary: Callable[ - [dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]], str - ], - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs: int, ) -> dict[str, Any]: if not resolution_targets: return { @@ -5459,7 +5501,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary": "No reset re-entry rebuild re-entry restore re-re-restore reset is recorded because there is no active target.", "stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots": [], "fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots": [], - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_decay_window_runs": class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_decay_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS, } current_primary_target = resolution_targets[0] @@ -5499,9 +5541,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( resolution_status = str( target.get("class_transition_resolution_status", "none") ) - resolution_reason = str( - target.get("class_transition_resolution_reason", "") - ) + resolution_reason = str(target.get("class_transition_resolution_reason", "")) reentry_status = str( target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") ) @@ -5576,11 +5616,9 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( target, transition_events, ) - freshness_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target( - target, - closure_forecast_events, - ) + freshness_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target( + target, + closure_forecast_events, ) freshness_status = str( freshness_meta[ @@ -5598,9 +5636,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( ] ) decayed_confirmation_rate = float( - freshness_meta[ - "decayed_rererestored_rebuild_reentry_confirmation_rate" - ] + freshness_meta["decayed_rererestored_rebuild_reentry_confirmation_rate"] ) decayed_clearance_rate = float( freshness_meta["decayed_rererestored_rebuild_reentry_clearance_rate"] @@ -5610,31 +5646,29 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix" ] ) - control_updates = ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control( - target, - freshness_meta=freshness_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - persistence_age_runs=persistence_age_runs, - persistence_score=persistence_score, - persistence_status=persistence_status, - persistence_reason=persistence_reason, - ) + control_updates = apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control( + target, + freshness_meta=freshness_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + rererestore_status=rererestore_status, + rererestore_reason=rererestore_reason, + persistence_age_runs=persistence_age_runs, + persistence_score=persistence_score, + persistence_status=persistence_status, + persistence_reason=persistence_reason, ) reset_status = str( control_updates[ @@ -5657,8 +5691,12 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( ) transition_status = str(control_updates["class_reweight_transition_status"]) transition_reason = str(control_updates["class_reweight_transition_reason"]) - resolution_status = str(control_updates["class_transition_resolution_status"]) - resolution_reason = str(control_updates["class_transition_resolution_reason"]) + resolution_status = str( + control_updates["class_transition_resolution_status"] + ) + resolution_reason = str( + control_updates["class_transition_resolution_reason"] + ) reentry_status = str( control_updates["closure_forecast_reset_reentry_rebuild_reentry_status"] ) @@ -5751,17 +5789,13 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - stale_hotspots = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( - resolution_targets, - mode="stale", - ) + stale_hotspots = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( + resolution_targets, + mode="stale", ) - fresh_hotspots = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( - resolution_targets, - mode="fresh", - ) + fresh_hotspots = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( + resolution_targets, + mode="fresh", ) return { "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": primary_target.get( @@ -5792,7 +5826,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( ), "stale_reset_reentry_rebuild_reentry_restore_rererestore_hotspots": stale_hotspots, "fresh_reset_reentry_rebuild_reentry_restore_rererestore_signal_hotspots": fresh_hotspots, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_decay_window_runs": class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_decay_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_FRESHNESS_WINDOW_RUNS, } @@ -5800,33 +5834,15 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persisten target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event: Callable[ - [dict[str, Any]], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label: Callable[ - [dict[str, Any]], str - ], - closure_forecast_direction_majority: Callable[[list[str]], str], - closure_forecast_direction_reversing: Callable[[str, str], bool], - clamp_round: Callable[..., float], - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs: int, ) -> dict[str, Any]: return _persistence_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_RERERESTORE_PERSISTENCE_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, side_from_event=closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event, - closure_forecast_direction_majority=closure_forecast_direction_majority, - closure_forecast_direction_reversing=closure_forecast_direction_reversing, - clamp_round=clamp_round, path_label=closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label, - persistence_window_runs=class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs, + persistence_window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, ) @@ -5834,33 +5850,15 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event: Callable[ - [dict[str, Any]], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label: Callable[ - [dict[str, Any]], str - ], - class_direction_flip_count: Callable[[list[str]], int], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - clamp_round: Callable[..., float], - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs: int, ) -> dict[str, Any]: return _churn_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_RERERESTORE_CHURN_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, side_from_event=closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event, - class_direction_flip_count=class_direction_flip_count, - target_specific_normalization_noise=target_specific_normalization_noise, - clamp_round=clamp_round, path_label=closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label, - window_runs=class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs, + window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, ) @@ -5885,12 +5883,6 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur rerestore_reason: str, rererestore_status: str, rererestore_reason: str, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status: Callable[ - [str], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status: Callable[ - [str], str - ], ) -> dict[str, Any]: persistence_status = str( persistence_meta.get( @@ -5926,19 +5918,15 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur recent_pending_status = str( transition_history_meta.get("recent_pending_status", "none") ) - current_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( - rererestore_status - ) + current_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( + rererestore_status ) if current_side == "none": - current_side = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status( - str( - target.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", - "none", - ) + current_side = closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status( + str( + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", + "none", ) ) ) @@ -6114,12 +6102,17 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur closure_hysteresis_reason = ( churn_reason or persistence_reason or closure_hysteresis_reason ) - if resolution_status == "cleared" and recent_pending_status in { - "pending-support", - "pending-caution", - } and ( - persistence_status in {"reversing", "none", "insufficient-data"} - or churn_status == "churn" + if ( + resolution_status == "cleared" + and recent_pending_status + in { + "pending-support", + "pending-caution", + } + and ( + persistence_status in {"reversing", "none", "insufficient-data"} + or churn_status == "churn" + ) ): transition_status = recent_pending_status transition_reason = ( @@ -6174,13 +6167,11 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots( resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: return _hotspots_base( resolution_targets, spec=_RERERESTORE_HOTSPOTS_SPEC, mode=mode, - target_class_key=target_class_key, ) @@ -6190,8 +6181,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persisten holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: list[ dict[str, Any] ], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str( @@ -6209,46 +6198,26 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persisten 0.0, ) if status == "just-rererestored": - return ( - f"{label} has only just re-re-restored stronger rerestored posture, so it is still fragile ({score:.2f}; {age_runs} run)." - ) + return f"{label} has only just re-re-restored stronger rerestored posture, so it is still fragile ({score:.2f}; {age_runs} run)." if status == "holding-confirmation-rebuild-reentry-rererestore": - return ( - f"Confirmation-side re-re-restored posture for {label} has held long enough to keep the stronger rerestored forecast in place ({score:.2f}; {age_runs} runs)." - ) + return f"Confirmation-side re-re-restored posture for {label} has held long enough to keep the stronger rerestored forecast in place ({score:.2f}; {age_runs} runs)." if status == "holding-clearance-rebuild-reentry-rererestore": - return ( - f"Clearance-side re-re-restored posture for {label} has held long enough to keep the stronger rerestored caution in place ({score:.2f}; {age_runs} runs)." - ) + return f"Clearance-side re-re-restored posture for {label} has held long enough to keep the stronger rerestored caution in place ({score:.2f}; {age_runs} runs)." if status == "sustained-confirmation-rebuild-reentry-rererestore": - return ( - f"Confirmation-side re-re-restored posture for {label} is now holding with enough follow-through to trust the stronger rerestored forecast more ({score:.2f}; {age_runs} runs)." - ) + return f"Confirmation-side re-re-restored posture for {label} is now holding with enough follow-through to trust the stronger rerestored forecast more ({score:.2f}; {age_runs} runs)." if status == "sustained-clearance-rebuild-reentry-rererestore": - return ( - f"Clearance-side re-re-restored posture for {label} is now holding with enough follow-through to trust the stronger rerestored caution more ({score:.2f}; {age_runs} runs)." - ) + return f"Clearance-side re-re-restored posture for {label} is now holding with enough follow-through to trust the stronger rerestored caution more ({score:.2f}; {age_runs} runs)." if status == "reversing": - return ( - f"The re-re-restored rebuilt re-entry posture for {label} is already weakening, so it is being softened again ({score:.2f})." - ) + return f"The re-re-restored rebuilt re-entry posture for {label} is already weakening, so it is being softened again ({score:.2f})." if status == "insufficient-data": - return ( - f"Re-re-restored rebuilt re-entry for {label} is still too lightly exercised to say whether the stronger posture can hold." - ) + return f"Re-re-restored rebuilt re-entry for {label} is still too lightly exercised to say whether the stronger posture can hold." if just_rererestored_rebuild_reentry_hotspots: hotspot = just_rererestored_rebuild_reentry_hotspots[0] - return ( - f"Newly re-re-restored posture is most fragile around {hotspot.get('label', 'recent hotspots')}, so those classes still need follow-through before the stronger rerestored posture can be trusted." - ) + return f"Newly re-re-restored posture is most fragile around {hotspot.get('label', 'recent hotspots')}, so those classes still need follow-through before the stronger rerestored posture can be trusted." if holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: hotspot = holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots[0] - return ( - f"Re-re-restored posture is holding most cleanly around {hotspot.get('label', 'recent hotspots')}, so those classes are closest to keeping the stronger rerestored posture safely." - ) - return ( - "No re-re-restored rebuilt re-entry posture is active enough yet to judge whether it can hold." - ) + return f"Re-re-restored posture is holding most cleanly around {hotspot.get('label', 'recent hotspots')}, so those classes are closest to keeping the stronger rerestored posture safely." + return "No re-re-restored rebuilt re-entry posture is active enough yet to judge whether it can hold." def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary( @@ -6256,8 +6225,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_sum reset_reentry_rebuild_reentry_restore_rererestore_churn_hotspots: list[ dict[str, Any] ], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str( @@ -6271,13 +6238,9 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_sum 0.0, ) if status == "watch": - return ( - f"Re-re-restored rebuilt re-entry for {label} is wobbling enough that stronger rerestored posture may soften soon ({score:.2f})." - ) + return f"Re-re-restored rebuilt re-entry for {label} is wobbling enough that stronger rerestored posture may soften soon ({score:.2f})." if status == "churn": - return ( - f"Re-re-restored rebuilt re-entry for {label} is flipping enough that stronger rerestored posture should be softened quickly ({score:.2f})." - ) + return f"Re-re-restored rebuilt re-entry for {label} is flipping enough that stronger rerestored posture should be softened quickly ({score:.2f})." if status == "blocked": return str( primary_target.get( @@ -6287,9 +6250,7 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_sum ) if reset_reentry_rebuild_reentry_restore_rererestore_churn_hotspots: hotspot = reset_reentry_rebuild_reentry_restore_rererestore_churn_hotspots[0] - return ( - f"Re-re-restored rebuilt re-entry churn is highest around {hotspot.get('label', 'recent hotspots')}, so stronger rerestored posture there should soften quickly if the wobble continues." - ) + return f"Re-re-restored rebuilt re-entry churn is highest around {hotspot.get('label', 'recent hotspots')}, so stronger rerestored posture there should soften quickly if the wobble continues." return "No meaningful re-re-restored rebuilt re-entry churn is active right now." @@ -6299,31 +6260,11 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur *, current_generated_at: str, confidence_calibration: dict[str, Any], - recommendation_bucket: Callable[[dict[str, Any]], object], class_closure_forecast_events: Callable[..., list[dict[str, Any]]], class_transition_events: Callable[..., list[dict[str, Any]]], - target_class_transition_history: Callable[[dict[str, Any], list[dict[str, Any]]], dict[str, Any]], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control: Callable[ - ..., - dict[str, Any], - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots: Callable[ - ..., - list[dict[str, Any]], - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary: Callable[ - [dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary: Callable[ - [dict[str, Any], list[dict[str, Any]]], str + target_class_transition_history: Callable[ + [dict[str, Any], list[dict[str, Any]]], dict[str, Any] ], - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs: int, ) -> dict[str, Any]: if not resolution_targets: return { @@ -6332,7 +6273,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "none", "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary": "No reset re-entry rebuild re-entry restore re-re-restore persistence is recorded because there is no active target.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_window_runs": class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, "just_rererestored_rebuild_reentry_hotspots": [], "holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots": [], "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.0, @@ -6380,9 +6321,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur resolution_status = str( target.get("class_transition_resolution_status", "none") ) - resolution_reason = str( - target.get("class_transition_resolution_reason", "") - ) + resolution_reason = str(target.get("class_transition_resolution_reason", "")) reentry_status = str( target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") ) @@ -6431,19 +6370,15 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur target, transition_events, ) - persistence_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + persistence_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( + target, + closure_forecast_events, + transition_history_meta, ) - churn_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + churn_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target( + target, + closure_forecast_events, + transition_history_meta, ) persistence_age_runs = int( persistence_meta[ @@ -6490,28 +6425,26 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path" ] ) - control_updates = ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - ) + control_updates = apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control( + target, + persistence_meta=persistence_meta, + churn_meta=churn_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + rererestore_status=rererestore_status, + rererestore_reason=rererestore_reason, ) closure_likely_outcome = str( control_updates["transition_closure_likely_outcome"] @@ -6524,8 +6457,12 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur ) transition_status = str(control_updates["class_reweight_transition_status"]) transition_reason = str(control_updates["class_reweight_transition_reason"]) - resolution_status = str(control_updates["class_transition_resolution_status"]) - resolution_reason = str(control_updates["class_transition_resolution_reason"]) + resolution_status = str( + control_updates["class_transition_resolution_status"] + ) + resolution_reason = str( + control_updates["class_transition_resolution_reason"] + ) reentry_status = str( control_updates["closure_forecast_reset_reentry_rebuild_reentry_status"] ) @@ -6635,7 +6572,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_chur just_rererestored_rebuild_reentry_hotspots, holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots, ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_window_runs": class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_WINDOW_RUNS, "just_rererestored_rebuild_reentry_hotspots": just_rererestored_rebuild_reentry_hotspots, "holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots": holding_reset_reentry_rebuild_reentry_restore_rererestore_hotspots, "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": primary_target.get( @@ -6662,35 +6599,14 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_r target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - ordered_reset_reentry_events_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]]], list[dict[str, Any]] - ], - closure_forecast_reset_side_from_status: Callable[[str], str], - normalized_closure_forecast_direction: Callable[[str, float], str], - clamp_round: Callable[..., float], - closure_forecast_direction_majority: Callable[[list[str]], str], - target_specific_normalization_noise: Callable[[dict[str, Any], dict[str, Any]], bool], - closure_forecast_direction_reversing: Callable[[str, str], bool], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label: Callable[ - [dict[str, Any]], str - ], - class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs: int, ) -> dict[str, Any]: return _recovery_for_target_base( target, closure_forecast_events, transition_history_meta, spec=_RERERESTORE_RECOVERY_SPEC, - ordered_reset_reentry_events_for_target=ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=normalized_closure_forecast_direction, - clamp_round=clamp_round, - closure_forecast_direction_majority=closure_forecast_direction_majority, - target_specific_normalization_noise=target_specific_normalization_noise, - closure_forecast_direction_reversing=closure_forecast_direction_reversing, path_label=closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label, - window_runs=class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs, + window_runs=CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, ) @@ -6981,7 +6897,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_h resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -7065,8 +6980,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_r primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str( @@ -7143,15 +7056,12 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary primary_target: dict[str, Any], recovering_confirmation_hotspots: list[dict[str, Any]], recovering_clearance_hotspots: list[dict[str, Any]], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: return _tier_summary_base( primary_target, recovering_confirmation_hotspots, recovering_clearance_hotspots, spec=_RERERERESTORE_SUMMARY_SPEC, - target_label=target_label, ) @@ -7161,30 +7071,11 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and *, current_generated_at: str, confidence_calibration: dict[str, Any], - recommendation_bucket: Callable[[dict[str, Any]], Any], class_closure_forecast_events: Callable[..., list[dict[str, Any]]], class_transition_events: Callable[..., list[dict[str, Any]]], target_class_transition_history: Callable[ [dict[str, Any], list[dict[str, Any]]], dict[str, Any] ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], - apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control: Callable[ - ..., - dict[str, Any], - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots: Callable[ - ..., - list[dict[str, Any]], - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary: Callable[ - [dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]], str - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary: Callable[ - [dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]], str - ], - class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs: int, ) -> dict[str, Any]: del confidence_calibration if not resolution_targets: @@ -7195,7 +7086,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary": "No reset re-entry rebuild re-entry restore re-re-restore refresh recovery is recorded because there is no active target.", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_summary": "No reset re-entry rebuild re-entry restore re-re-re-restore is recorded because there is no active target.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs": class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, "recovering_from_confirmation_rebuild_reentry_rererestore_reset_hotspots": [], "recovering_from_clearance_rebuild_reentry_rererestore_reset_hotspots": [], } @@ -7231,7 +7122,9 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and ) transition_status = str(target.get("class_reweight_transition_status", "none")) transition_reason = str(target.get("class_reweight_transition_reason", "")) - resolution_status = str(target.get("class_transition_resolution_status", "none")) + resolution_status = str( + target.get("class_transition_resolution_status", "none") + ) resolution_reason = str(target.get("class_transition_resolution_reason", "")) reentry_status = str( target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") @@ -7246,7 +7139,9 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and ) ) restore_reason = str( - target.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reason", "") + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_reason", "" + ) ) rerestore_status = str( target.get( @@ -7323,12 +7218,10 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and target, transition_events, ) - refresh_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + refresh_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_for_target( + target, + closure_forecast_events, + transition_history_meta, ) refresh_recovery_score = float( refresh_meta[ @@ -7355,36 +7248,36 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path" ] ) - control_updates = ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( - target, - refresh_meta=refresh_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - rererestore_age_runs=rererestore_age_runs, - rererestore_persistence_score=rererestore_persistence_score, - rererestore_persistence_status=rererestore_persistence_status, - rererestore_persistence_reason=rererestore_persistence_reason, - rererestore_churn_score=rererestore_churn_score, - rererestore_churn_status=rererestore_churn_status, - rererestore_churn_reason=rererestore_churn_reason, - ) + control_updates = apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( + target, + refresh_meta=refresh_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + rererestore_status=rererestore_status, + rererestore_reason=rererestore_reason, + rererestore_age_runs=rererestore_age_runs, + rererestore_persistence_score=rererestore_persistence_score, + rererestore_persistence_status=rererestore_persistence_status, + rererestore_persistence_reason=rererestore_persistence_reason, + rererestore_churn_score=rererestore_churn_score, + rererestore_churn_status=rererestore_churn_status, + rererestore_churn_reason=rererestore_churn_reason, + ) + closure_likely_outcome = str( + control_updates["transition_closure_likely_outcome"] ) - closure_likely_outcome = str(control_updates["transition_closure_likely_outcome"]) closure_hysteresis_status = str( control_updates["closure_forecast_hysteresis_status"] ) @@ -7393,8 +7286,12 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and ) transition_status = str(control_updates["class_reweight_transition_status"]) transition_reason = str(control_updates["class_reweight_transition_reason"]) - resolution_status = str(control_updates["class_transition_resolution_status"]) - resolution_reason = str(control_updates["class_transition_resolution_reason"]) + resolution_status = str( + control_updates["class_transition_resolution_status"] + ) + resolution_reason = str( + control_updates["class_transition_resolution_reason"] + ) reentry_status = str( control_updates["closure_forecast_reset_reentry_rebuild_reentry_status"] ) @@ -7502,17 +7399,13 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and resolution_targets[:] = updated_targets primary_target = resolution_targets[0] - recovering_confirmation_hotspots = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots( - resolution_targets, - mode="confirmation", - ) + recovering_confirmation_hotspots = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots( + resolution_targets, + mode="confirmation", ) - recovering_clearance_hotspots = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots( - resolution_targets, - mode="clearance", - ) + recovering_clearance_hotspots = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_hotspots( + resolution_targets, + mode="clearance", ) return { "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": primary_target.get( @@ -7545,7 +7438,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_and recovering_clearance_hotspots, ) ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs": class_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERESTORE_REFRESH_WINDOW_RUNS, "recovering_from_confirmation_rebuild_reentry_rererestore_reset_hotspots": recovering_confirmation_hotspots, "recovering_from_clearance_rebuild_reentry_rererestore_reset_hotspots": recovering_clearance_hotspots, } @@ -7610,7 +7503,9 @@ def _shift_restore_tier(token: str, delta: int) -> str: return token -def _translate_restore_tier_status(status: str, *, delta: int, recognized: frozenset[str]) -> str: +def _translate_restore_tier_status( + status: str, *, delta: int, recognized: frozenset[str] +) -> str: # Recognized inputs are translated by shifting their restore tier `delta` levels. # Passthrough terms (none/blocked/reversing/insufficient-data) are recognized but # carry no tier word, so the shift returns them unchanged. Anything else -> "none". @@ -7752,13 +7647,13 @@ def _translate_target_for_persistence(target: dict[str, Any]) -> dict[str, Any]: def _translate_event_for_persistence(event: dict[str, Any]) -> dict[str, Any]: translated = _translate_target_for_persistence(event) - translated["closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status"] = ( - _status_to_rererestore_status( - str( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status", - "none", - ) + translated[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ] = _status_to_rererestore_status( + str( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status", + "none", ) ) ) @@ -7793,21 +7688,15 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persist target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], ) -> dict[str, Any]: translated_target = _translate_target_for_persistence(target) translated_events = [ _translate_event_for_persistence(event) for event in closure_forecast_events ] - persistence_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( - translated_target, - translated_events, - transition_history_meta, - ) + persistence_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( + translated_target, + translated_events, + transition_history_meta, ) return { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": ( @@ -7859,21 +7748,15 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_f target: dict[str, Any], closure_forecast_events: list[dict[str, Any]], transition_history_meta: dict[str, Any], - *, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], ) -> dict[str, Any]: translated_target = _translate_target_for_persistence(target) translated_events = [ _translate_event_for_persistence(event) for event in closure_forecast_events ] - churn_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target( - translated_target, - translated_events, - transition_history_meta, - ) + churn_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target( + translated_target, + translated_events, + transition_history_meta, ) return { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": churn_meta.get( @@ -7924,10 +7807,6 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch rerestore_reason: str, rererestore_status: str, rererestore_reason: str, - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control: Callable[ - ..., - dict[str, Any], - ], ) -> dict[str, Any]: translated_target = _translate_target_for_persistence(target) translated_persistence_meta = { @@ -7962,28 +7841,26 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch ) ), } - return ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control( - translated_target, - persistence_meta=translated_persistence_meta, - churn_meta=translated_churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - ) + return apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control( + translated_target, + persistence_meta=translated_persistence_meta, + churn_meta=translated_churn_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + rererestore_status=rererestore_status, + rererestore_reason=rererestore_reason, ) @@ -7991,7 +7868,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspot resolution_targets: list[dict[str, Any]], *, mode: str, - target_class_key: Callable[[dict[str, Any]], str], ) -> list[dict[str, Any]]: grouped: dict[str, dict[str, Any]] = {} for target in resolution_targets: @@ -8126,8 +8002,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persist holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots: list[ dict[str, Any] ], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str( @@ -8195,7 +8069,9 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persist "follow-through before the stronger re-re-restored posture can be trusted." ) if holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots: - hotspot = holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots[0] + hotspot = holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots[ + 0 + ] return ( "Re-re-re-restored posture is holding most cleanly around " f"{hotspot.get('label', 'recent hotspots')}, so those classes are closest " @@ -8212,8 +8088,6 @@ def closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_s reset_reentry_rebuild_reentry_restore_rerererestore_churn_hotspots: list[ dict[str, Any] ], - *, - target_label: Callable[[dict[str, Any]], str], ) -> str: label = target_label(primary_target) or "The current target" status = str( @@ -8262,25 +8136,11 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch *, current_generated_at: str, confidence_calibration: dict[str, Any], - recommendation_bucket: Callable[[dict[str, Any]], Any], class_closure_forecast_events: Callable[..., list[dict[str, Any]]], class_transition_events: Callable[..., list[dict[str, Any]]], target_class_transition_history: Callable[ [dict[str, Any], list[dict[str, Any]]], dict[str, Any] ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target: Callable[ - [dict[str, Any], list[dict[str, Any]], dict[str, Any]], dict[str, Any] - ], - apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control: Callable[ - ..., - dict[str, Any], - ], - target_class_key: Callable[[dict[str, Any]], str], - target_label: Callable[[dict[str, Any]], str], - class_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs: int, ) -> dict[str, Any]: del confidence_calibration if not resolution_targets: @@ -8290,7 +8150,7 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary": "No reset re-entry rebuild re-entry restore re-re-re-restore persistence is recorded because there is no active target.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs": class_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERERESTORE_WINDOW_RUNS, "just_rerererestored_rebuild_reentry_hotspots": [], "holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots": [], "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, @@ -8335,7 +8195,9 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch ) transition_status = str(target.get("class_reweight_transition_status", "none")) transition_reason = str(target.get("class_reweight_transition_reason", "")) - resolution_status = str(target.get("class_transition_resolution_status", "none")) + resolution_status = str( + target.get("class_transition_resolution_status", "none") + ) resolution_reason = str(target.get("class_transition_resolution_reason", "")) reentry_status = str( target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") @@ -8349,7 +8211,9 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch ) ) restore_reason = str( - target.get("closure_forecast_reset_reentry_rebuild_reentry_restore_reason", "") + target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_reason", "" + ) ) rerestore_status = str( target.get( @@ -8381,19 +8245,15 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch target, transition_events, ) - persistence_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + persistence_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target( + target, + closure_forecast_events, + transition_history_meta, ) - churn_meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target( - target, - closure_forecast_events, - transition_history_meta, - ) + churn_meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target( + target, + closure_forecast_events, + transition_history_meta, ) persistence_age_runs = int( persistence_meta[ @@ -8440,30 +8300,30 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path" ] ) - control_updates = ( - apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( - target, - persistence_meta=persistence_meta, - churn_meta=churn_meta, - transition_history_meta=transition_history_meta, - closure_likely_outcome=closure_likely_outcome, - closure_hysteresis_status=closure_hysteresis_status, - closure_hysteresis_reason=closure_hysteresis_reason, - transition_status=transition_status, - transition_reason=transition_reason, - resolution_status=resolution_status, - resolution_reason=resolution_reason, - reentry_status=reentry_status, - reentry_reason=reentry_reason, - restore_status=restore_status, - restore_reason=restore_reason, - rerestore_status=rerestore_status, - rerestore_reason=rerestore_reason, - rererestore_status=rererestore_status, - rererestore_reason=rererestore_reason, - ) + control_updates = apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( + target, + persistence_meta=persistence_meta, + churn_meta=churn_meta, + transition_history_meta=transition_history_meta, + closure_likely_outcome=closure_likely_outcome, + closure_hysteresis_status=closure_hysteresis_status, + closure_hysteresis_reason=closure_hysteresis_reason, + transition_status=transition_status, + transition_reason=transition_reason, + resolution_status=resolution_status, + resolution_reason=resolution_reason, + reentry_status=reentry_status, + reentry_reason=reentry_reason, + restore_status=restore_status, + restore_reason=restore_reason, + rerestore_status=rerestore_status, + rerestore_reason=rerestore_reason, + rererestore_status=rererestore_status, + rererestore_reason=rererestore_reason, + ) + closure_likely_outcome = str( + control_updates["transition_closure_likely_outcome"] ) - closure_likely_outcome = str(control_updates["transition_closure_likely_outcome"]) closure_hysteresis_status = str( control_updates["closure_forecast_hysteresis_status"] ) @@ -8472,8 +8332,12 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch ) transition_status = str(control_updates["class_reweight_transition_status"]) transition_reason = str(control_updates["class_reweight_transition_reason"]) - resolution_status = str(control_updates["class_transition_resolution_status"]) - resolution_reason = str(control_updates["class_transition_resolution_reason"]) + resolution_status = str( + control_updates["class_transition_resolution_status"] + ) + resolution_reason = str( + control_updates["class_transition_resolution_reason"] + ) reentry_status = str( control_updates["closure_forecast_reset_reentry_rebuild_reentry_status"] ) @@ -8547,21 +8411,18 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots( resolution_targets, mode="just-rerererestored", - target_class_key=target_class_key, ) ) holding_hotspots = ( closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots( resolution_targets, mode="holding", - target_class_key=target_class_key, ) ) churn_hotspots = ( closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots( resolution_targets, mode="churn", - target_class_key=target_class_key, ) ) return { @@ -8586,10 +8447,9 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch primary_target, just_hotspots, holding_hotspots, - target_label=target_label, ) ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs": class_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs": CLASS_RESET_REENTRY_REBUILD_REENTRY_RESTORE_RERERERESTORE_WINDOW_RUNS, "just_rerererestored_rebuild_reentry_hotspots": just_hotspots, "holding_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots": holding_hotspots, "primary_target_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": primary_target.get( @@ -8608,7 +8468,6 @@ def apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_ch closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary( primary_target, churn_hotspots, - target_label=target_label, ) ), "reset_reentry_rebuild_reentry_restore_rerererestore_churn_hotspots": churn_hotspots, diff --git a/src/operator_trend_support.py b/src/operator_trend_support.py index c7aea5a..8ebb0c7 100644 --- a/src/operator_trend_support.py +++ b/src/operator_trend_support.py @@ -1,5 +1,7 @@ from __future__ import annotations +from functools import lru_cache + LANE_LABELS = { "blocked": "Blocked", "urgent": "Needs Attention Now", @@ -56,6 +58,71 @@ CLASS_MEMORY_RECENCY_WEIGHTS = (1.0, 1.0, 0.7, 0.7, 0.4, 0.4, 0.4, 0.2, 0.2, 0.2) + +def target_class_key(item: dict) -> str: + return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" + + +def normalized_closure_forecast_direction(direction: str, score: float) -> str: + if direction in {"supporting-confirmation", "supporting-clearance", "neutral"}: + return direction + if score >= 0.20: + return "supporting-confirmation" + if score <= -0.20: + return "supporting-clearance" + return "neutral" + + +def target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: + return ( + history_meta.get("recent_reopened", False) + or history_meta.get("recent_policy_flip_count", 0) > 0 + or target.get("trust_recovery_status") == "blocked" + ) + + +def clamp_round(value: float, *, lower: float, upper: float) -> float: + return round(max(lower, min(upper, value)), 2) + + +def closure_forecast_direction_majority(directions: list[str]) -> str: + confirmation_count = sum( + 1 for direction in directions if direction == "supporting-confirmation" + ) + clearance_count = sum( + 1 for direction in directions if direction == "supporting-clearance" + ) + if confirmation_count > clearance_count: + return "supporting-confirmation" + if clearance_count > confirmation_count: + return "supporting-clearance" + return "neutral" + + +def closure_forecast_direction_reversing( + current_direction: str, earlier_majority: str +) -> bool: + if current_direction == "neutral" or earlier_majority == "neutral": + return False + return current_direction != earlier_majority + + +def class_direction_flip_count(directions: list[str]) -> int: + non_neutral = [direction for direction in directions if direction != "neutral"] + if len(non_neutral) < 2: + return 0 + return sum( + 1 + for previous, current in zip(non_neutral, non_neutral[1:]) + if current != previous + ) + + +def target_label(item: dict) -> str: + repo = f"{item.get('repo')}: " if item.get("repo") else "" + return f"{repo}{item.get('title', '')}".strip(": ") + + GENERIC_RECOMMENDATION_PHRASES = ( "continue the normal audit/control-center loop", "continue the normal operator loop", @@ -65,7 +132,10 @@ "open the repo queue details", ) -GENERIC_MONITOR_PHRASES = ("keep the operator loop light", "keep the operator loop lightweight") +GENERIC_MONITOR_PHRASES = ( + "keep the operator loop light", + "keep the operator loop lightweight", +) GENERIC_BASELINE_PHRASES = ( "run the next full audit to refresh the baseline", @@ -82,7 +152,9 @@ def is_generic_recommendation(action: str) -> bool: def is_generic_monitor_guidance(action: str) -> bool: normalized = (action or "").strip().lower() - return bool(normalized) and any(phrase in normalized for phrase in GENERIC_MONITOR_PHRASES) + return bool(normalized) and any( + phrase in normalized for phrase in GENERIC_MONITOR_PHRASES + ) def is_generic_baseline_guidance( @@ -91,4 +163,918 @@ def is_generic_baseline_guidance( normalized = (action or "").strip().lower() if normalized and any(phrase in normalized for phrase in GENERIC_BASELINE_PHRASES): return True - return not normalized and bool(watch_guidance and watch_guidance.get("full_refresh_due")) + return not normalized and bool( + watch_guidance and watch_guidance.get("full_refresh_due") + ) + + +@lru_cache(maxsize=None) +def _side_sets( + confirmation_members: tuple[str, ...], +) -> tuple[frozenset[str], frozenset[str]]: + return ( + frozenset(confirmation_members), + frozenset( + member.replace("confirmation", "clearance") + for member in confirmation_members + ), + ) + + +def resolve_side(status: str, *confirmation_members: str) -> str: + # Shared side classifier for the reset/reentry/rebuild/restore status families. The + # clearance-side set is the confirmation-side set with "confirmation" swapped for + # "clearance"; confirmation membership wins, so a confirmation-only token (e.g. + # "just-rererestored") resolves to confirmation even though the swap also lands it + # in clearance. Returns "none" for anything unrecognized. + confirmation, clearance = _side_sets(confirmation_members) + if status in confirmation: + return "confirmation" + if status in clearance: + return "clearance" + return "none" + + +def closure_forecast_reset_reentry_side_from_status(status: str) -> str: + return resolve_side( + status, + "pending-confirmation-reentry", + "reentered-confirmation", + ) + + +def closure_forecast_reset_reentry_side_from_recovery_status(status: str) -> str: + return resolve_side( + status, + "recovering-confirmation-reset", + "reentering-confirmation", + ) + + +def closure_forecast_reset_reentry_side_from_event(event: dict) -> str: + side = closure_forecast_reset_reentry_side_from_status( + event.get("closure_forecast_reset_reentry_status", "none") + ) + if side != "none": + return side + return closure_forecast_reset_reentry_side_from_recovery_status( + event.get("closure_forecast_reset_refresh_recovery_status", "none") + ) + + +def closure_forecast_event_matches_target_state(event: dict, target: dict) -> bool: + return ( + event.get("key") == queue_identity(target) + and event.get("class_key") == target_class_key(target) + and float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + == float(target.get("closure_forecast_reweight_score", 0.0) or 0.0) + and event.get("closure_forecast_reweight_direction", "neutral") + == target.get("closure_forecast_reweight_direction", "neutral") + and event.get("closure_forecast_reset_refresh_recovery_status", "none") + == target.get("closure_forecast_reset_refresh_recovery_status", "none") + and event.get("closure_forecast_reset_reentry_status", "none") + == target.get("closure_forecast_reset_reentry_status", "none") + and event.get("closure_forecast_reset_reentry_persistence_status", "none") + == target.get("closure_forecast_reset_reentry_persistence_status", "none") + and event.get("closure_forecast_reset_reentry_churn_status", "none") + == target.get("closure_forecast_reset_reentry_churn_status", "none") + and event.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) + == target.get( + "closure_forecast_reset_reentry_freshness_status", "insufficient-data" + ) + and event.get("closure_forecast_reset_reentry_reset_status", "none") + == target.get("closure_forecast_reset_reentry_reset_status", "none") + and event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") + == target.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") + and event.get("closure_forecast_reset_reentry_rebuild_status", "none") + == target.get("closure_forecast_reset_reentry_rebuild_status", "none") + and event.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", "none" + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", "none" + ) + and event.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") + == target.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") + and event.get( + "closure_forecast_reset_reentry_rebuild_freshness_status", + "insufficient-data", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_freshness_status", + "insufficient-data", + ) + and event.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + == target.get("closure_forecast_reset_reentry_rebuild_reset_status", "none") + and event.get( + "closure_forecast_reset_reentry_rebuild_refresh_recovery_status", "none" + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_refresh_recovery_status", "none" + ) + and event.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") + == target.get("closure_forecast_reset_reentry_rebuild_reentry_status", "none") + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", "none" + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", "none" + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none" + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_churn_status", "none" + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", + "insufficient-data", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", + "insufficient-data", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none" + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none" + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + "none", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + "none", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + "none", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + "none", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", + "none", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", + "none", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", + "insufficient-data", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", + "insufficient-data", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status", + "none", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status", + "none", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", + "none", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", + "none", + ) + and event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", + "none", + ) + == target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", + "none", + ) + and event.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) + == target.get( + "closure_forecast_reacquisition_freshness_status", "insufficient-data" + ) + and event.get("closure_forecast_persistence_reset_status", "none") + == target.get("closure_forecast_persistence_reset_status", "none") + and event.get("transition_closure_likely_outcome", "none") + == target.get("transition_closure_likely_outcome", "none") + ) + + +def current_closure_forecast_event_for_target(target: dict) -> dict: + return { + "key": queue_identity(target), + "class_key": target_class_key(target), + "label": target_label(target), + "generated_at": "", + "closure_forecast_reweight_score": target.get( + "closure_forecast_reweight_score", 0.0 + ), + "closure_forecast_reweight_direction": target.get( + "closure_forecast_reweight_direction", + "neutral", + ), + "transition_closure_likely_outcome": target.get( + "transition_closure_likely_outcome", + "none", + ), + "class_reweight_transition_status": target.get( + "class_reweight_transition_status", + "none", + ), + "class_transition_resolution_status": target.get( + "class_transition_resolution_status", + "none", + ), + "closure_forecast_hysteresis_status": target.get( + "closure_forecast_hysteresis_status", + "none", + ), + "closure_forecast_momentum_status": target.get( + "closure_forecast_momentum_status", + "insufficient-data", + ), + "closure_forecast_stability_status": target.get( + "closure_forecast_stability_status", + "watch", + ), + "closure_forecast_freshness_status": target.get( + "closure_forecast_freshness_status", + "insufficient-data", + ), + "closure_forecast_decay_status": target.get( + "closure_forecast_decay_status", + "none", + ), + "closure_forecast_refresh_recovery_status": target.get( + "closure_forecast_refresh_recovery_status", + "none", + ), + "closure_forecast_reacquisition_status": target.get( + "closure_forecast_reacquisition_status", + "none", + ), + "closure_forecast_reacquisition_persistence_status": target.get( + "closure_forecast_reacquisition_persistence_status", + "none", + ), + "closure_forecast_recovery_churn_status": target.get( + "closure_forecast_recovery_churn_status", + "none", + ), + "closure_forecast_reacquisition_freshness_status": target.get( + "closure_forecast_reacquisition_freshness_status", + "insufficient-data", + ), + "closure_forecast_persistence_reset_status": target.get( + "closure_forecast_persistence_reset_status", + "none", + ), + "closure_forecast_reset_refresh_recovery_status": target.get( + "closure_forecast_reset_refresh_recovery_status", + "none", + ), + "closure_forecast_reset_reentry_status": target.get( + "closure_forecast_reset_reentry_status", + "none", + ), + "closure_forecast_reset_reentry_persistence_status": target.get( + "closure_forecast_reset_reentry_persistence_status", + "none", + ), + "closure_forecast_reset_reentry_churn_status": target.get( + "closure_forecast_reset_reentry_churn_status", + "none", + ), + "closure_forecast_reset_reentry_freshness_status": target.get( + "closure_forecast_reset_reentry_freshness_status", + "insufficient-data", + ), + "closure_forecast_reset_reentry_reset_status": target.get( + "closure_forecast_reset_reentry_reset_status", + "none", + ), + "closure_forecast_reset_reentry_refresh_recovery_status": target.get( + "closure_forecast_reset_reentry_refresh_recovery_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_status": target.get( + "closure_forecast_reset_reentry_rebuild_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_persistence_status": target.get( + "closure_forecast_reset_reentry_rebuild_persistence_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_churn_status": target.get( + "closure_forecast_reset_reentry_rebuild_churn_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_freshness_status": target.get( + "closure_forecast_reset_reentry_rebuild_freshness_status", + "insufficient-data", + ), + "closure_forecast_reset_reentry_rebuild_reset_status": target.get( + "closure_forecast_reset_reentry_rebuild_reset_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_refresh_recovery_status": target.get( + "closure_forecast_reset_reentry_rebuild_refresh_recovery_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_persistence_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_churn_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_churn_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_freshness_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", + "insufficient-data", + ), + "closure_forecast_reset_reentry_rebuild_reentry_reset_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_reset_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_churn_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_freshness_status", + "insufficient-data", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_reset_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_refresh_recovery_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", + "none", + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": target.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", + "none", + ), + } + + +def ordered_reset_reentry_events_for_target( + target: dict, + closure_forecast_events: list[dict], +) -> list[dict]: + class_key = target_class_key(target) + matching_events = [ + event + for event in closure_forecast_events + if event.get("class_key") == class_key + ][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] + if not matching_events: + return [current_closure_forecast_event_for_target(target)] + + current_index = next( + ( + index + for index, event in enumerate(matching_events) + if event.get("generated_at", "") == "" + and event.get("key") == queue_identity(target) + ), + None, + ) + if current_index is not None: + if current_index == 0: + return matching_events + current_event = matching_events[current_index] + remainder = ( + matching_events[:current_index] + matching_events[current_index + 1 :] + ) + return [current_event, *remainder][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] + + matching_index = next( + ( + index + for index, event in enumerate(matching_events) + if closure_forecast_event_matches_target_state(event, target) + ), + None, + ) + if matching_index is not None: + if matching_index == 0: + return matching_events + current_event = matching_events[matching_index] + remainder = ( + matching_events[:matching_index] + matching_events[matching_index + 1 :] + ) + return [current_event, *remainder][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] + + return [ + current_closure_forecast_event_for_target(target), + *matching_events, + ][:CLASS_RESET_REENTRY_PERSISTENCE_WINDOW_RUNS] + + +def closure_forecast_reset_reentry_side_from_persistence_status(status: str) -> str: + return resolve_side( + status, + "holding-confirmation-reentry", + "sustained-confirmation-reentry", + ) + + +def closure_forecast_reset_reentry_memory_side_from_event(event: dict) -> str: + side = closure_forecast_reset_reentry_side_from_persistence_status( + event.get("closure_forecast_reset_reentry_persistence_status", "none") + ) + if side != "none": + return side + return closure_forecast_reset_reentry_side_from_event(event) + + +def reset_reentry_event_is_confirmation_like(event: dict) -> bool: + event_side = closure_forecast_reset_reentry_memory_side_from_event(event) + persistence_status = event.get( + "closure_forecast_reset_reentry_persistence_status", "none" + ) + return ( + event.get("closure_forecast_reset_reentry_status", "none") + in {"pending-confirmation-reentry", "reentered-confirmation"} + or ( + persistence_status + in { + "just-reentered", + "holding-confirmation-reentry", + "sustained-confirmation-reentry", + } + and event_side == "confirmation" + ) + or event.get("closure_forecast_hysteresis_status", "none") + in {"pending-confirmation", "confirmed-confirmation"} + or event.get("transition_closure_likely_outcome", "none") == "confirm-soon" + ) + + +def reset_reentry_event_is_clearance_like(event: dict) -> bool: + event_side = closure_forecast_reset_reentry_memory_side_from_event(event) + persistence_status = event.get( + "closure_forecast_reset_reentry_persistence_status", "none" + ) + return ( + event.get("closure_forecast_reset_reentry_status", "none") + in {"pending-clearance-reentry", "reentered-clearance"} + or ( + persistence_status + in { + "just-reentered", + "holding-clearance-reentry", + "sustained-clearance-reentry", + } + and event_side == "clearance" + ) + or event.get("closure_forecast_hysteresis_status", "none") + in {"pending-clearance", "confirmed-clearance"} + or event.get("transition_closure_likely_outcome", "none") + in {"clear-risk", "expire-risk"} + ) + + +def reset_reentry_event_has_evidence(event: dict) -> bool: + return ( + reset_reentry_event_is_confirmation_like(event) + or reset_reentry_event_is_clearance_like(event) + or event.get("closure_forecast_reset_reentry_churn_status", "none") + in {"watch", "churn", "blocked"} + ) + + +def reset_reentry_event_signal_label(event: dict) -> str: + if reset_reentry_event_is_confirmation_like(event): + return "confirmation-like" + if reset_reentry_event_is_clearance_like(event): + return "clearance-like" + return "neutral" + + +def closure_forecast_reset_reentry_freshness_reason( + freshness_status: str, + weighted_reset_reentry_evidence_count: float, + recent_window_weight_share: float, + decayed_confirmation_rate: float, + decayed_clearance_rate: float, +) -> str: + if freshness_status == "fresh": + return ( + "Recent reset re-entry evidence is still current enough to trust, with " + f"{recent_window_weight_share:.0%} of the weighted signal coming from the latest " + f"{CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS} runs." + ) + if freshness_status == "mixed-age": + return ( + "Reset re-entry memory is still useful, but it is partly aging: " + f"{recent_window_weight_share:.0%} of the weighted signal is recent and the rest is older carry-forward." + ) + if freshness_status == "stale": + return "Older reset re-entry strength is carrying more of the signal than recent runs, so it should not keep stronger posture alive on memory alone." + return ( + "Reset re-entry memory is still too lightly exercised to judge freshness, with " + f"{weighted_reset_reentry_evidence_count:.2f} weighted reset re-entry run(s), " + f"{decayed_confirmation_rate:.0%} confirmation-like signal, and {decayed_clearance_rate:.0%} clearance-like signal." + ) + + +def recent_reset_reentry_signal_mix( + weighted_reset_reentry_evidence_count: float, + weighted_confirmation_like: float, + weighted_clearance_like: float, + recent_window_weight_share: float, +) -> str: + return ( + f"{weighted_reset_reentry_evidence_count:.2f} weighted reset re-entry run(s) with " + f"{weighted_confirmation_like:.2f} confirmation-like, {weighted_clearance_like:.2f} clearance-like, " + f"and {recent_window_weight_share:.0%} of the signal from the freshest runs." + ) + + +def closure_forecast_reset_reentry_rebuild_side_from_status(status: str) -> str: + return resolve_side( + status, + "pending-confirmation-rebuild", + "rebuilt-confirmation-reentry", + ) + + +def closure_forecast_reset_reentry_rebuild_side_from_recovery_status( + status: str, +) -> str: + return resolve_side( + status, + "recovering-confirmation-reentry-reset", + "rebuilding-confirmation-reentry", + ) + + +def closure_forecast_reset_reentry_refresh_path_label(event: dict) -> str: + rebuild_status = ( + event.get("closure_forecast_reset_reentry_rebuild_status", "none") or "none" + ) + if rebuild_status != "none": + return rebuild_status + recovery_status = ( + event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") + or "none" + ) + if recovery_status != "none": + return recovery_status + reset_status = ( + event.get("closure_forecast_reset_reentry_reset_status", "none") or "none" + ) + if reset_status != "none": + return reset_status + reentry_status = ( + event.get("closure_forecast_reset_reentry_status", "none") or "none" + ) + if reentry_status != "none": + return reentry_status + likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" + if likely_outcome != "none": + return likely_outcome + return "hold" + + +def closure_forecast_reset_reentry_rebuild_side_from_persistence_status( + status: str, +) -> str: + return resolve_side( + status, + "holding-confirmation-rebuild", + "sustained-confirmation-rebuild", + ) + + +def closure_forecast_reset_reentry_rebuild_side_from_event(event: dict) -> str: + side = closure_forecast_reset_reentry_rebuild_side_from_persistence_status( + event.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") + ) + if side != "none": + return side + side = closure_forecast_reset_reentry_rebuild_side_from_status( + event.get("closure_forecast_reset_reentry_rebuild_status", "none") + ) + if side != "none": + return side + return closure_forecast_reset_reentry_rebuild_side_from_recovery_status( + event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") + ) + + +def closure_forecast_reset_reentry_rebuild_path_label(event: dict) -> str: + persistence_status = ( + event.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") + or "none" + ) + if persistence_status != "none": + return persistence_status + churn_status = ( + event.get("closure_forecast_reset_reentry_rebuild_churn_status", "none") + or "none" + ) + if churn_status != "none": + return churn_status + rebuild_status = ( + event.get("closure_forecast_reset_reentry_rebuild_status", "none") or "none" + ) + if rebuild_status != "none": + return rebuild_status + recovery_status = ( + event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") + or "none" + ) + if recovery_status != "none": + return recovery_status + reset_status = ( + event.get("closure_forecast_reset_reentry_reset_status", "none") or "none" + ) + if reset_status != "none": + return reset_status + reentry_status = ( + event.get("closure_forecast_reset_reentry_status", "none") or "none" + ) + if reentry_status != "none": + return reentry_status + likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" + if likely_outcome != "none": + return likely_outcome + return "hold" + + +def closure_forecast_reset_reentry_rebuild_reentry_refresh_path_label( + event: dict, +) -> str: + restore_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_status", "none" + ) + or "none" + ) + if restore_status != "none": + return restore_status + refresh_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_status", + "none", + ) + or "none" + ) + if refresh_status != "none": + return refresh_status + reset_status = ( + event.get("closure_forecast_reset_reentry_rebuild_reentry_reset_status", "none") + or "none" + ) + if reset_status != "none": + return reset_status + score = float(event.get("closure_forecast_reweight_score", 0.0) or 0.0) + direction = normalized_closure_forecast_direction( + event.get("closure_forecast_reweight_direction", "neutral"), + score, + ) + freshness = event.get( + "closure_forecast_reset_reentry_rebuild_reentry_freshness_status", + "insufficient-data", + ) + if direction == "supporting-confirmation": + return f"{freshness} confirmation" + if direction == "supporting-clearance": + return f"{freshness} clearance" + likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" + if likely_outcome != "none": + return likely_outcome + return "hold" + + +def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( + status: str, +) -> str: + return resolve_side( + status, + "pending-confirmation-rebuild-reentry-rererestore", + "rererestored-confirmation-rebuild-reentry", + ) + + +def closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status( + status: str, +) -> str: + return resolve_side( + status, + "recovering-confirmation-rebuild-reentry-rerestore-reset", + "rererestoring-confirmation-rebuild-reentry", + ) + + +def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( + status: str, +) -> str: + return resolve_side( + status, + "just-rererestored", + "holding-confirmation-rebuild-reentry-rererestore", + "sustained-confirmation-rebuild-reentry-rererestore", + ) + + +def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event( + event: dict, +) -> str: + side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", + "none", + ) + ) + if side != "none": + return side + side = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", + "none", + ) + ) + if side != "none": + return side + return closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", + "none", + ) + ) + + +def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label( + event: dict, +) -> str: + persistence_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", + "none", + ) + or "none" + ) + if persistence_status != "none": + return persistence_status + churn_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status", + "none", + ) + or "none" + ) + if churn_status != "none": + return churn_status + rererestore_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", + "none", + ) + or "none" + ) + if rererestore_status != "none": + return rererestore_status + refresh_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status", + "none", + ) + or "none" + ) + if refresh_status != "none": + return refresh_status + rerestore_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status", + "none", + ) + or "none" + ) + if rerestore_status != "none": + return rerestore_status + rerestore_reset_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status", + "none", + ) + or "none" + ) + if rerestore_reset_status != "none": + return rerestore_reset_status + likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" + if likely_outcome != "none": + return likely_outcome + return "hold" + + +def closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path_label( + event: dict, +) -> str: + rerererestore_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status", + "none", + ) + or "none" + ) + if rerererestore_status != "none": + return rerererestore_status + refresh_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status", + "none", + ) + or "none" + ) + if refresh_status != "none": + return refresh_status + rererestore_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", + "none", + ) + or "none" + ) + if rererestore_status != "none": + return rererestore_status + rererestore_reset_status = ( + event.get( + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_status", + "none", + ) + or "none" + ) + if rererestore_reset_status != "none": + return rererestore_reset_status + likely_outcome = event.get("transition_closure_likely_outcome", "none") or "none" + if likely_outcome != "none": + return likely_outcome + return "hold" + + +def recommendation_bucket(item: dict) -> int: + lane = item.get("lane", "") + if lane == "blocked" and item.get("kind") == "setup": + return 0 + if lane == "blocked": + return 1 + if lane == "urgent" and item.get("aging_status") in {"stale", "chronic"}: + return 2 + if lane == "urgent" and item.get("reopened"): + return 3 + if lane == "urgent": + return 4 + if lane == "ready": + return 5 + return 6 + + +def queue_identity(item: dict) -> str: + if item.get("item_id"): + return item["item_id"] + repo = item.get("repo", "") + title = item.get("title", "") + return f"{repo}:{title}" diff --git a/src/portfolio_truth_status.py b/src/portfolio_truth_status.py new file mode 100644 index 0000000..e7930c0 --- /dev/null +++ b/src/portfolio_truth_status.py @@ -0,0 +1,177 @@ +"""Leaf status overlays used while publishing portfolio truth.""" + +from __future__ import annotations + +import json +import logging +import re +from datetime import date +from pathlib import Path + +from src.cache import ResponseCache +from src.cli_output import print_warning +from src.github_client import GitHubClient + +WAREHOUSE_REPORT_STALE_DAYS = 7 + + +def load_release_count_by_name(*, output_dir: Path, username: str) -> dict[str, int] | None: + audit_files = sorted( + output_dir.glob(f"audit-report-{username}-*.json"), + key=lambda path: path.stat().st_mtime, + ) + if not audit_files: + logging.getLogger(__name__).warning( + "--portfolio-truth-include-release-count requires a prior audit run; " + "no audit-report-%s-*.json found in %s — skipping release_count overlay", + username, + output_dir, + ) + return None + try: + with audit_files[-1].open() as fh: + data = json.load(fh) + except Exception as exc: # noqa: BLE001 + logging.getLogger(__name__).warning( + "--portfolio-truth-include-release-count: could not read %s: %s — skipping", + audit_files[-1], + exc, + ) + return None + result: dict[str, int] = {} + for audit in data.get("audits") or []: + name = (audit.get("metadata") or {}).get("name") + if not name: + continue + for analyzer_result in audit.get("analyzer_results") or []: + if analyzer_result.get("dimension") == "activity": + release_count = (analyzer_result.get("details") or {}).get("release_count") + if isinstance(release_count, int): + result[name] = release_count + break + return result + + +def latest_audit_report_path(*, output_dir: Path, username: str) -> Path | None: + audit_files = sorted( + output_dir.glob(f"audit-report-{username}-*.json"), + key=lambda path: path.stat().st_mtime, + ) + return audit_files[-1] if audit_files else None + + +def _repo_status_entries_from_metadata( + repo_metadata: list[dict], *, source: str +) -> dict[str, dict]: + result: dict[str, dict] = {} + for metadata in repo_metadata: + name = str(metadata.get("name") or "").strip() + full_name = str(metadata.get("full_name") or "").strip() + archived = metadata.get("archived") + if not name or not isinstance(archived, bool): + continue + entry = {"archived": archived, "full_name": full_name, "source": source} + result[name] = entry + repo_name = full_name.rsplit("/", 1)[-1] if full_name else "" + if repo_name: + result.setdefault(repo_name, entry) + return result + + +def load_live_repo_status_by_name( + *, username: str, token: str | None, cache: ResponseCache | None +) -> dict[str, dict] | None: + try: + repos = GitHubClient(token=token, cache=cache).list_repos(username) + except Exception as exc: # noqa: BLE001 + logging.getLogger(__name__).warning( + "--portfolio-truth: could not fetch live GitHub repo status for %s: %s — " + "falling back to latest audit report metadata", + username, + exc, + ) + return None + return _repo_status_entries_from_metadata(repos, source="github_api") + + +def load_repo_status_from_audit_by_name( + *, output_dir: Path, username: str +) -> dict[str, dict] | None: + audit_path = latest_audit_report_path(output_dir=output_dir, username=username) + if audit_path is None: + return None + try: + with audit_path.open() as fh: + data = json.load(fh) + except Exception as exc: # noqa: BLE001 + logging.getLogger(__name__).warning( + "--portfolio-truth: could not read repo status overlay from %s: %s — skipping", + audit_path, + exc, + ) + return None + repo_metadata = [ + metadata + for audit in data.get("audits") or [] + if isinstance(metadata := audit.get("metadata") or {}, dict) + ] + return _repo_status_entries_from_metadata(repo_metadata, source="audit_report") + + +def load_security_alerts_by_name( + *, output_dir: Path, username: str +) -> dict[str, dict] | None: + ghas_files = sorted( + output_dir.glob(f"ghas-alerts-{username}-*.json"), + key=lambda path: path.stat().st_mtime, + ) + if not ghas_files: + logging.getLogger(__name__).warning( + "--portfolio-truth-include-security requires a prior `audit report --ghas-alerts` " + "run; no ghas-alerts-%s-*.json found in %s — skipping security overlay", + username, + output_dir, + ) + return None + try: + with ghas_files[-1].open() as fh: + data = json.load(fh) + except Exception as exc: # noqa: BLE001 + logging.getLogger(__name__).warning( + "--portfolio-truth-include-security: could not read %s: %s — skipping", + ghas_files[-1], + exc, + ) + return None + if not isinstance(data, dict): + logging.getLogger(__name__).warning( + "--portfolio-truth-include-security: %s is not a name-keyed object — skipping", + ghas_files[-1], + ) + return None + return {name: entry for name, entry in data.items() if isinstance(entry, dict)} + + +def warn_if_warehouse_report_stale(output_dir: Path, username: str) -> None: + report_path = latest_audit_report_path(output_dir=output_dir, username=username) + if report_path is None: + print_warning( + f"No audit-report-{username}-*.json in {output_dir}: Notion's Repo Auditor " + f"signal reads that warehouse report and this --portfolio-truth run did not " + f"create one. Run `audit report {username}` to generate it (F2)." + ) + return + match = re.search(r"(\d{4}-\d{2}-\d{2})", report_path.name) + if not match: + return + try: + report_date = date.fromisoformat(match.group(1)) + except ValueError: + return + age = (date.today() - report_date).days + if age > WAREHOUSE_REPORT_STALE_DAYS: + print_warning( + f"Newest warehouse report {report_path.name} is {age}d old: Notion's Repo " + f"Auditor signal reads it and is now stale. Run `audit report {username}` to " + f"refresh the warehouse report (F2 — both artifacts kept live by decision)." + ) diff --git a/src/report_contracts.py b/src/report_contracts.py new file mode 100644 index 0000000..2d7bbe5 --- /dev/null +++ b/src/report_contracts.py @@ -0,0 +1,62 @@ +"""Typed contracts for the weekly-story and risk seams. + +These are the typed forms of the `weekly_story_v1` and risk-posture contracts +documented in `docs/architecture.md`, adopted per the 2026-07-10 elegance +review to put types at the enrichment boundary. They describe the shapes +produced by `src/weekly_packaging.py` (`_build_weekly_story_v1` and its +evidence-item helpers) and `src/report_enrichment.py` +(`build_risk_lookup` / `_extract_risk_posture`); they are annotations only +and introduce no runtime behavior. +""" + +from __future__ import annotations + +from typing import NotRequired, TypedDict + + +class WeeklyStoryEvidenceItem(TypedDict): + label: str + summary: str + kind: str + safe_posture: str + command_hint: NotRequired[str] + + +class WeeklyStorySection(TypedDict): + id: str + label: str + state: str + headline: str + next_step: str + next_label: str + reason_codes: list[str] + evidence_items: list[WeeklyStoryEvidenceItem] + + +class WeeklyStoryV1(TypedDict): + version: int + headline: str + decision: str + why_this_week: str + next_step: str + section_order: list[str] + sections: list[WeeklyStorySection] + + +class RiskLookupEntry(TypedDict): + risk_tier: str + risk_summary: str + + +class TopElevatedEntry(TypedDict): + repo: str + risk_summary: str + + +class RiskPosture(TypedDict): + elevated_count: int + moderate_count: int + baseline_count: int + deferred_count: int + tier_counts: dict[str, int] + top_elevated: list[TopElevatedEntry] diff --git a/src/report_enrichment.py b/src/report_enrichment.py index ceecd31..021d9a8 100644 --- a/src/report_enrichment.py +++ b/src/report_enrichment.py @@ -6,6 +6,7 @@ from typing import Any from src.portfolio_truth_types import truth_latest_path +from src.report_contracts import RiskLookupEntry, RiskPosture, TopElevatedEntry from src.terminology import ACTION_SYNC_CANONICAL_LABELS from src.weekly_packaging import finalize_weekly_pack from src.weekly_scheduling_overlay import apply_weekly_scheduling_overlay @@ -32,13 +33,17 @@ } NO_BASELINE_SUMMARY = "No prior baseline was available, so this view shows the current run summary and operator pressure without before/after deltas." -NO_HISTORY_SUMMARY = "No history is recorded yet, so this view is using the current run only." +NO_HISTORY_SUMMARY = ( + "No history is recorded yet, so this view is using the current run only." +) NO_LINKED_ARTIFACT_SUMMARY = "No linked artifact available yet." NO_FOLLOW_THROUGH_SUMMARY = "No follow-through evidence is recorded yet." NO_FOLLOW_THROUGH_CHECKPOINT = ( "Use the next run or linked artifact to confirm whether the recommendation moved." ) -NO_FOLLOW_THROUGH_ESCALATION = "No stronger follow-through escalation is currently surfaced." +NO_FOLLOW_THROUGH_ESCALATION = ( + "No stronger follow-through escalation is currently surfaced." +) NO_FOLLOW_THROUGH_RECOVERY = ( "No follow-through recovery or escalation-retirement signal is currently surfaced." ) @@ -64,18 +69,14 @@ NO_FOLLOW_THROUGH_REACQUISITION_DURABILITY = ( "No follow-through reacquisition durability signal is currently surfaced." ) -NO_FOLLOW_THROUGH_REACQUISITION_CONSOLIDATION = ( - "No follow-through reacquisition confidence-consolidation signal is currently surfaced." -) +NO_FOLLOW_THROUGH_REACQUISITION_CONSOLIDATION = "No follow-through reacquisition confidence-consolidation signal is currently surfaced." NO_FOLLOW_THROUGH_REACQUISITION_SOFTENING_DECAY = ( "No reacquisition softening-decay signal is currently surfaced." ) NO_FOLLOW_THROUGH_REACQUISITION_CONFIDENCE_RETIREMENT = ( "No reacquisition confidence-retirement signal is currently surfaced." ) -NO_FOLLOW_THROUGH_REACQUISITION_REVALIDATION_RECOVERY = ( - "No post-revalidation recovery or confidence re-earning signal is currently surfaced." -) +NO_FOLLOW_THROUGH_REACQUISITION_REVALIDATION_RECOVERY = "No post-revalidation recovery or confidence re-earning signal is currently surfaced." NO_OPERATOR_FOCUS_SUMMARY = "No operator focus bucket is currently surfaced." NO_PORTFOLIO_CATALOG_SUMMARY = "No portfolio catalog contract is recorded yet." NO_OPERATING_PATHS_SUMMARY = "No normalized operating-path contract is recorded yet." @@ -84,19 +85,19 @@ ) NO_SCORECARD_SUMMARY = "No maturity scorecard is recorded yet." NO_MATURITY_GAP_SUMMARY = "No maturity gap summary is recorded yet." -NO_WHERE_TO_START_SUMMARY = "No meaningful implementation hotspot is currently surfaced." -NO_OPERATOR_OUTCOMES_SUMMARY = "Not enough operator history is recorded yet to judge whether recent actions are improving portfolio outcomes." -NO_OPERATOR_EFFECTIVENESS_SUMMARY = ( - "Not enough judged recommendation history is recorded yet to judge operator effectiveness." +NO_WHERE_TO_START_SUMMARY = ( + "No meaningful implementation hotspot is currently surfaced." ) +NO_OPERATOR_OUTCOMES_SUMMARY = "Not enough operator history is recorded yet to judge whether recent actions are improving portfolio outcomes." +NO_OPERATOR_EFFECTIVENESS_SUMMARY = "Not enough judged recommendation history is recorded yet to judge operator effectiveness." NO_HIGH_PRESSURE_QUEUE_TREND = "High-pressure queue trend is not ready yet." -NO_ACTION_SYNC_SUMMARY = ( - "No current campaign needs Action Sync yet, so the safest next move is to keep the story local." -) +NO_ACTION_SYNC_SUMMARY = "No current campaign needs Action Sync yet, so the safest next move is to keep the story local." NO_ACTION_SYNC_STEP = "Stay local for now; no current campaign needs preview or apply." NO_ACTION_SYNC_LINE = "Action Sync: stay local until a campaign has meaningful actions and healthy writeback prerequisites." NO_APPLY_READINESS_SUMMARY = "No current campaign has a safe execution handoff yet, so the local story should stay local for now." -NO_NEXT_APPLY_CANDIDATE = "Stay local for now; no current campaign has a safe execution handoff." +NO_NEXT_APPLY_CANDIDATE = ( + "Stay local for now; no current campaign has a safe execution handoff." +) NO_ACTION_SYNC_COMMAND_HINT = "No Action Sync command is recommended yet." NO_CAMPAIGN_OUTCOMES_SUMMARY = "No recent Action Sync apply needs post-apply monitoring yet, so the local weekly story can stay local." NO_NEXT_MONITORING_STEP = ( @@ -107,20 +108,14 @@ ) NO_CAMPAIGN_TUNING_SUMMARY = "Campaign tuning stays neutral until there is enough outcome history to bias tied recommendations." NO_NEXT_TUNED_CAMPAIGN = "No current campaign needs a tie-break candidate yet." -NO_CAMPAIGN_TUNING_LINE = ( - "Campaign Tuning: recommendations stay neutral until more outcome history is available." -) +NO_CAMPAIGN_TUNING_LINE = "Campaign Tuning: recommendations stay neutral until more outcome history is available." NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY = "Historical portfolio intelligence is still thin, so the weekly story should stay grounded in the current run and recent operator queue." NO_NEXT_HISTORICAL_FOCUS = "Stay local for now; no repo has enough cross-run intervention evidence to demand a historical follow-up read yet." NO_HISTORICAL_INTELLIGENCE_LINE = "Historical Portfolio Intelligence: keep the weekly story anchored in the current run until more cross-run evidence accumulates." NO_AUTOMATION_GUIDANCE_SUMMARY = "Automation guidance stays quiet until a campaign has a clearly safe preview, follow-up, or manual-only posture." NO_NEXT_SAFE_AUTOMATION_STEP = "Stay local for now; no current campaign has a stronger safe automation posture than manual review." -NO_AUTOMATION_GUIDANCE_LINE = ( - "Automation Guidance: keep the next step human-led until a bounded safe posture is surfaced." -) -NO_APPROVAL_WORKFLOW_SUMMARY = ( - "No current approval needs review yet, so the approval workflow can stay local for now." -) +NO_AUTOMATION_GUIDANCE_LINE = "Automation Guidance: keep the next step human-led until a bounded safe posture is surfaced." +NO_APPROVAL_WORKFLOW_SUMMARY = "No current approval needs review yet, so the approval workflow can stay local for now." NO_NEXT_APPROVAL_REVIEW = "Stay local for now; no current approval needs review." NO_APPROVAL_WORKFLOW_LINE = "Approval Workflow: no current approval needs review yet." @@ -155,7 +150,7 @@ def _metadata(audit: Any) -> dict[str, Any]: return metadata -def build_risk_lookup(output_dir: Path | None) -> dict[str, dict[str, str]]: +def build_risk_lookup(output_dir: Path | None) -> dict[str, RiskLookupEntry]: """Canonical per-repo risk reader: display_name -> {risk_tier, risk_summary}. Single source of truth for risk data loaded from portfolio-truth-latest.json. @@ -172,14 +167,14 @@ def build_risk_lookup(output_dir: Path | None) -> dict[str, dict[str, str]]: truth = json.loads(truth_path.read_text()) except Exception: return {} - lookup: dict[str, dict[str, str]] = {} + lookup: dict[str, RiskLookupEntry] = {} for project in truth.get("projects") or []: identity = project.get("identity") or {} name = str(identity.get("display_name") or "") if not name: continue risk = project.get("risk") or {} - entry = { + entry: RiskLookupEntry = { "risk_tier": str(risk.get("risk_tier") or "baseline"), "risk_summary": str(risk.get("risk_summary") or ""), } @@ -195,13 +190,13 @@ def build_risk_lookup(output_dir: Path | None) -> dict[str, dict[str, str]]: return lookup -def _extract_risk_posture(output_dir: Path | None) -> dict[str, Any]: +def _extract_risk_posture(output_dir: Path | None) -> RiskPosture | dict[str, Any]: """Aggregate risk tier summary, derived from build_risk_lookup. Returns {} if unavailable.""" lookup = build_risk_lookup(output_dir) if not lookup: return {} tier_counts: dict[str, int] = {} - top_elevated: list[dict[str, Any]] = [] + top_elevated: list[TopElevatedEntry] = [] seen: set[int] = set() for name, entry in lookup.items(): # build_risk_lookup aliases each project under both its display_name and its @@ -369,7 +364,9 @@ def build_artifact_role_summary(report_data: Any, diff_data: dict | None = None) ) -def build_suggested_reading_order(report_data: Any, diff_data: dict | None = None) -> str: +def build_suggested_reading_order( + report_data: Any, diff_data: dict | None = None +) -> str: mode_key = _product_mode_key(report_data, diff_data) if mode_key == "action-sync": return ( @@ -392,7 +389,9 @@ def build_suggested_reading_order(report_data: Any, diff_data: dict | None = Non ) -def build_next_best_workflow_step(report_data: Any, diff_data: dict | None = None) -> str: +def build_next_best_workflow_step( + report_data: Any, diff_data: dict | None = None +) -> str: mode_key = _product_mode_key(report_data, diff_data) if mode_key == "action-sync": return "Keep the local artifact as the source of truth, then use campaign preview or writeback only when the repo decision is already clear." @@ -438,7 +437,9 @@ def _repo_trend_label(repo_name: str, audit: Any, report_data: Any) -> str: return f"Down {abs(delta):.3f} versus the last recorded run." -def _repo_last_movement(repo_name: str, report_data: Any, diff_data: dict | None) -> str: +def _repo_last_movement( + repo_name: str, report_data: Any, diff_data: dict | None +) -> str: change = _repo_change(repo_name, diff_data) if change: delta = change.get("delta") @@ -539,7 +540,9 @@ def _repo_hotspot_context(audit: Any) -> str: def _implementation_hotspot_line(hotspot: dict[str, Any]) -> str: path = str(hotspot.get("path") or "repo root") - category = str(hotspot.get("category") or "implementation pressure").replace("-", " ") + category = str(hotspot.get("category") or "implementation pressure").replace( + "-", " " + ) move = str(hotspot.get("suggested_first_move") or "").strip() prefix = f"{path} ({category})" return f"{prefix}: {move}" if move else prefix @@ -641,7 +644,11 @@ def build_score_explanation(audit: Any) -> dict[str, Any]: or best_action.get("action") or "Review the current hotspot and pick the next best repo action.", "next_best_action_rationale": best_action.get("rationale") - or (hotspots[0].get("summary") if hotspots else "No dominant rationale is recorded yet."), + or ( + hotspots[0].get("summary") + if hotspots + else "No dominant rationale is recorded yet." + ), } @@ -692,52 +699,71 @@ def build_repo_briefing( } strongest_drivers = explanation.get("top_positive_drivers", []) or [] biggest_drags = explanation.get("top_negative_drivers", []) or [] - next_tier_gap = explanation.get("next_tier_gap_summary") or "No next-tier gap is recorded yet." + next_tier_gap = ( + explanation.get("next_tier_gap_summary") or "No next-tier gap is recorded yet." + ) last_movement = _repo_last_movement(repo_name, report_data, diff_data) - recent_change_summary = _repo_change_summary(repo_name, audit, report_data, diff_data) + recent_change_summary = _repo_change_summary( + repo_name, audit, report_data, diff_data + ) hotspot_context = _repo_hotspot_context(audit) next_best_action = ( explanation.get("next_best_action") or "Review the current hotspot and pick the next best repo action." ) next_best_action_rationale = ( - explanation.get("next_best_action_rationale") or "No action rationale is recorded yet." + explanation.get("next_best_action_rationale") + or "No action rationale is recorded yet." ) top_action_candidates = _repo_action_candidates(audit) queue_item = _repo_queue_item(repo_name, report_data) review_target = _repo_review_target(repo_name, report_data) handoff_source = queue_item or review_target or {} - recommended_action = build_action_handoff_summary(handoff_source) or str(next_best_action) + recommended_action = build_action_handoff_summary(handoff_source) or str( + next_best_action + ) follow_through_status = build_follow_through_status_label(handoff_source) follow_through_summary = build_follow_through_summary(handoff_source) follow_through_checkpoint = build_follow_through_checkpoint(handoff_source) - follow_through_checkpoint_timing = build_follow_through_checkpoint_status_label(handoff_source) - follow_through_escalation = build_follow_through_escalation_status_label(handoff_source) - follow_through_escalation_summary = build_follow_through_escalation_summary(handoff_source) + follow_through_checkpoint_timing = build_follow_through_checkpoint_status_label( + handoff_source + ) + follow_through_escalation = build_follow_through_escalation_status_label( + handoff_source + ) + follow_through_escalation_summary = build_follow_through_escalation_summary( + handoff_source + ) follow_through_recovery = build_follow_through_recovery_status_label(handoff_source) - follow_through_recovery_summary = build_follow_through_recovery_summary(handoff_source) - follow_through_recovery_persistence = build_follow_through_recovery_persistence_status_label( + follow_through_recovery_summary = build_follow_through_recovery_summary( handoff_source ) - follow_through_recovery_persistence_summary = build_follow_through_recovery_persistence_summary( + follow_through_recovery_persistence = ( + build_follow_through_recovery_persistence_status_label(handoff_source) + ) + follow_through_recovery_persistence_summary = ( + build_follow_through_recovery_persistence_summary(handoff_source) + ) + follow_through_relapse_churn = build_follow_through_relapse_churn_status_label( handoff_source ) - follow_through_relapse_churn = build_follow_through_relapse_churn_status_label(handoff_source) follow_through_relapse_churn_summary = build_follow_through_relapse_churn_summary( handoff_source ) - follow_through_recovery_freshness = build_follow_through_recovery_freshness_status_label( - handoff_source + follow_through_recovery_freshness = ( + build_follow_through_recovery_freshness_status_label(handoff_source) ) - follow_through_recovery_freshness_summary = build_follow_through_recovery_freshness_summary( + follow_through_recovery_freshness_summary = ( + build_follow_through_recovery_freshness_summary(handoff_source) + ) + follow_through_recovery_decay = build_follow_through_recovery_decay_status_label( handoff_source ) - follow_through_recovery_decay = build_follow_through_recovery_decay_status_label(handoff_source) follow_through_recovery_decay_summary = build_follow_through_recovery_decay_summary( handoff_source ) - follow_through_recovery_memory_reset = build_follow_through_recovery_memory_reset_status_label( - handoff_source + follow_through_recovery_memory_reset = ( + build_follow_through_recovery_memory_reset_status_label(handoff_source) ) follow_through_recovery_memory_reset_summary = ( build_follow_through_recovery_memory_reset_summary(handoff_source) @@ -773,13 +799,17 @@ def build_repo_briefing( build_follow_through_reacquisition_softening_decay_summary(handoff_source) ) follow_through_reacquisition_confidence_retirement = ( - build_follow_through_reacquisition_confidence_retirement_status_label(handoff_source) + build_follow_through_reacquisition_confidence_retirement_status_label( + handoff_source + ) ) follow_through_reacquisition_confidence_retirement_summary = ( build_follow_through_reacquisition_confidence_retirement_summary(handoff_source) ) follow_through_reacquisition_revalidation_recovery = ( - build_follow_through_reacquisition_revalidation_recovery_status_label(handoff_source) + build_follow_through_reacquisition_revalidation_recovery_status_label( + handoff_source + ) ) follow_through_reacquisition_revalidation_recovery_summary = ( build_follow_through_reacquisition_revalidation_recovery_summary(handoff_source) @@ -801,7 +831,9 @@ def build_repo_briefing( campaign_tuning_line = build_campaign_tuning_line(handoff_source) historical_intelligence_line = build_historical_intelligence_line(handoff_source) automation_line = build_automation_line(handoff_source) - follow_through_resurfacing_reason = build_follow_through_resurfacing_reason(handoff_source) + follow_through_resurfacing_reason = build_follow_through_resurfacing_reason( + handoff_source + ) implementation_hotspots = _implementation_hotspots(audit)[:3] where_to_start_summary = _where_to_start_summary(audit) return { @@ -815,7 +847,8 @@ def build_repo_briefing( ), "why_this_repo_looks_this_way": { "strongest_drivers": _string_list( - list(strongest_drivers), fallback="No strong positive drivers recorded yet." + list(strongest_drivers), + fallback="No strong positive drivers recorded yet.", ), "biggest_drags": _string_list( list(biggest_drags), fallback="No major drag factors recorded yet." @@ -927,13 +960,17 @@ def build_repo_briefing( "suggested_writeback_target": str( handoff_source.get("suggested_writeback_target") or "none" ), - "apply_packet_state": str(handoff_source.get("apply_packet_state") or "stay-local"), + "apply_packet_state": str( + handoff_source.get("apply_packet_state") or "stay-local" + ), "apply_packet_summary": str( handoff_source.get("apply_packet_summary") or "No current apply packet is surfaced for this repo." ), "apply_packet_command": str(handoff_source.get("apply_packet_command") or ""), - "post_apply_state": str(handoff_source.get("post_apply_state") or "no-recent-apply"), + "post_apply_state": str( + handoff_source.get("post_apply_state") or "no-recent-apply" + ), "post_apply_summary": str( handoff_source.get("post_apply_summary") or "No post-apply monitoring is surfaced for this repo yet." @@ -945,14 +982,17 @@ def build_repo_briefing( handoff_source.get("campaign_tuning_summary") or "No campaign tuning evidence is surfaced for this repo yet." ), - "automation_posture": str(handoff_source.get("automation_posture") or "manual-only"), + "automation_posture": str( + handoff_source.get("automation_posture") or "manual-only" + ), "automation_summary": str( handoff_source.get("automation_summary") or "No automation guidance is surfaced for this repo yet." ), "automation_command": str(handoff_source.get("automation_command") or ""), "historical_intelligence_status": str( - handoff_source.get("historical_intelligence_status") or "insufficient-evidence" + handoff_source.get("historical_intelligence_status") + or "insufficient-evidence" ), "historical_intelligence_summary": str( handoff_source.get("historical_intelligence_summary") @@ -979,7 +1019,9 @@ def build_weekly_review_pack( ) repo_names: list[str] = [] for item in operator_queue: - repo = (_mapping(item).get("repo") or _mapping(item).get("repo_name") or "").strip() + repo = ( + _mapping(item).get("repo") or _mapping(item).get("repo_name") or "" + ).strip() if repo and repo not in repo_names: repo_names.append(repo) for audit in sorted(audits, key=_overall_score, reverse=True): @@ -1026,7 +1068,9 @@ def build_weekly_review_pack( "queue_pressure_summary": build_queue_pressure_summary(data, diff_data), "trust_actionability_summary": build_trust_actionability_summary(data), "top_recommendation_summary": top_recommendation, - "operator_focus_summary": _build_operator_focus_summary_from_groups(grouped_focus_items), + "operator_focus_summary": _build_operator_focus_summary_from_groups( + grouped_focus_items + ), "portfolio_catalog_summary": build_portfolio_catalog_summary(data), "operating_paths_summary": build_operating_paths_summary(data), "intent_alignment_summary": build_portfolio_intent_alignment_summary(data), @@ -1061,7 +1105,9 @@ def build_weekly_review_pack( or build_next_tuned_campaign_line(data) != NO_NEXT_TUNED_CAMPAIGN else NO_CAMPAIGN_TUNING_LINE ), - "historical_portfolio_intelligence": build_historical_portfolio_intelligence_summary(data), + "historical_portfolio_intelligence": build_historical_portfolio_intelligence_summary( + data + ), "next_historical_focus": build_next_historical_focus_line(data), "automation_guidance_summary": build_automation_guidance_summary(data), "next_safe_automation_step": build_next_safe_automation_step_line(data), @@ -1076,7 +1122,8 @@ def build_weekly_review_pack( "automation_guidance_line": ( f"{build_automation_guidance_summary(data)} Next step: {build_next_safe_automation_step_line(data)}" if build_automation_guidance_summary(data) != NO_AUTOMATION_GUIDANCE_SUMMARY - or build_next_safe_automation_step_line(data) != NO_NEXT_SAFE_AUTOMATION_STEP + or build_next_safe_automation_step_line(data) + != NO_NEXT_SAFE_AUTOMATION_STEP else NO_AUTOMATION_GUIDANCE_LINE ), "top_ready_for_review_approvals": list( @@ -1094,32 +1141,48 @@ def build_weekly_review_pack( "top_approved_manual_approvals": list( operator_summary.get("top_approved_manual_approvals") or [] ), - "top_blocked_approvals": list(operator_summary.get("top_blocked_approvals") or []), - "top_apply_ready_campaigns": list(operator_summary.get("top_apply_ready_campaigns") or []), + "top_blocked_approvals": list( + operator_summary.get("top_blocked_approvals") or [] + ), + "top_apply_ready_campaigns": list( + operator_summary.get("top_apply_ready_campaigns") or [] + ), "top_preview_ready_campaigns": list( operator_summary.get("top_preview_ready_campaigns") or [] ), "top_drift_review_campaigns": list( operator_summary.get("top_drift_review_campaigns") or [] ), - "top_blocked_campaigns": list(operator_summary.get("top_blocked_campaigns") or []), + "top_blocked_campaigns": list( + operator_summary.get("top_blocked_campaigns") or [] + ), "top_ready_to_apply_packets": list( operator_summary.get("top_ready_to_apply_packets") or [] ), "top_needs_approval_packets": list( operator_summary.get("top_needs_approval_packets") or [] ), - "top_review_drift_packets": list(operator_summary.get("top_review_drift_packets") or []), - "top_monitor_now_campaigns": list(operator_summary.get("top_monitor_now_campaigns") or []), + "top_review_drift_packets": list( + operator_summary.get("top_review_drift_packets") or [] + ), + "top_monitor_now_campaigns": list( + operator_summary.get("top_monitor_now_campaigns") or [] + ), "top_holding_clean_campaigns": list( operator_summary.get("top_holding_clean_campaigns") or [] ), - "top_reopened_campaigns": list(operator_summary.get("top_reopened_campaigns") or []), + "top_reopened_campaigns": list( + operator_summary.get("top_reopened_campaigns") or [] + ), "top_drift_returned_campaigns": list( operator_summary.get("top_drift_returned_campaigns") or [] ), - "top_proven_campaigns": list(operator_summary.get("top_proven_campaigns") or []), - "top_caution_campaigns": list(operator_summary.get("top_caution_campaigns") or []), + "top_proven_campaigns": list( + operator_summary.get("top_proven_campaigns") or [] + ), + "top_caution_campaigns": list( + operator_summary.get("top_caution_campaigns") or [] + ), "top_thin_evidence_campaigns": list( operator_summary.get("top_thin_evidence_campaigns") or [] ), @@ -1141,11 +1204,14 @@ def build_weekly_review_pack( "top_follow_up_safe_campaigns": list( operator_summary.get("top_follow_up_safe_campaigns") or [] ), - "top_manual_only_campaigns": list(operator_summary.get("top_manual_only_campaigns") or []), + "top_manual_only_campaigns": list( + operator_summary.get("top_manual_only_campaigns") or [] + ), "top_attention": top_attention, "repo_briefings": repo_briefings, "top_below_target_scorecard_items": list( - _mapping(data).get("scorecards_summary", {}).get("top_below_target_repos") or [] + _mapping(data).get("scorecards_summary", {}).get("top_below_target_repos") + or [] ), "what_to_do_this_week": what_to_do_this_week, "follow_through_summary": str( @@ -1160,7 +1226,8 @@ def build_weekly_review_pack( or NO_FOLLOW_THROUGH_ESCALATION ), "follow_through_recovery_summary": str( - operator_summary.get("follow_through_recovery_summary") or NO_FOLLOW_THROUGH_RECOVERY + operator_summary.get("follow_through_recovery_summary") + or NO_FOLLOW_THROUGH_RECOVERY ), "follow_through_recovery_persistence_summary": str( operator_summary.get("follow_through_recovery_persistence_summary") @@ -1191,11 +1258,15 @@ def build_weekly_review_pack( or NO_FOLLOW_THROUGH_RECOVERY_REACQUISITION ), "follow_through_reacquisition_durability_summary": str( - operator_summary.get("follow_through_recovery_reacquisition_durability_summary") + operator_summary.get( + "follow_through_recovery_reacquisition_durability_summary" + ) or NO_FOLLOW_THROUGH_REACQUISITION_DURABILITY ), "follow_through_reacquisition_consolidation_summary": str( - operator_summary.get("follow_through_recovery_reacquisition_consolidation_summary") + operator_summary.get( + "follow_through_recovery_reacquisition_consolidation_summary" + ) or NO_FOLLOW_THROUGH_REACQUISITION_CONSOLIDATION ), "follow_through_reacquisition_softening_decay_summary": str( @@ -1203,21 +1274,29 @@ def build_weekly_review_pack( or NO_FOLLOW_THROUGH_REACQUISITION_SOFTENING_DECAY ), "follow_through_reacquisition_confidence_retirement_summary": str( - operator_summary.get("follow_through_reacquisition_confidence_retirement_summary") + operator_summary.get( + "follow_through_reacquisition_confidence_retirement_summary" + ) or NO_FOLLOW_THROUGH_REACQUISITION_CONFIDENCE_RETIREMENT ), "follow_through_reacquisition_revalidation_recovery_summary": str( - operator_summary.get("follow_through_reacquisition_revalidation_recovery_summary") + operator_summary.get( + "follow_through_reacquisition_revalidation_recovery_summary" + ) or NO_FOLLOW_THROUGH_REACQUISITION_REVALIDATION_RECOVERY ), - "top_unattempted_items": list(operator_summary.get("top_unattempted_items") or []), + "top_unattempted_items": list( + operator_summary.get("top_unattempted_items") or [] + ), "top_stale_follow_through_items": list( operator_summary.get("top_stale_follow_through_items") or [] ), "top_overdue_follow_through_items": list( operator_summary.get("top_overdue_follow_through_items") or [] ), - "top_escalation_items": list(operator_summary.get("top_escalation_items") or []), + "top_escalation_items": list( + operator_summary.get("top_escalation_items") or [] + ), "top_recovering_follow_through_items": list( operator_summary.get("top_recovering_follow_through_items") or [] ), @@ -1236,12 +1315,18 @@ def build_weekly_review_pack( "top_churn_follow_through_items": list( operator_summary.get("top_churn_follow_through_items") or [] ), - "top_fresh_recovery_items": list(operator_summary.get("top_fresh_recovery_items") or []), - "top_stale_recovery_items": list(operator_summary.get("top_stale_recovery_items") or []), + "top_fresh_recovery_items": list( + operator_summary.get("top_fresh_recovery_items") or [] + ), + "top_stale_recovery_items": list( + operator_summary.get("top_stale_recovery_items") or [] + ), "top_softening_recovery_items": list( operator_summary.get("top_softening_recovery_items") or [] ), - "top_reset_recovery_items": list(operator_summary.get("top_reset_recovery_items") or []), + "top_reset_recovery_items": list( + operator_summary.get("top_reset_recovery_items") or [] + ), "top_rebuilding_recovery_items": list( operator_summary.get("top_rebuilding_recovery_items") or [] ), @@ -1257,7 +1342,9 @@ def build_weekly_review_pack( "top_fragile_reacquisition_items": list( operator_summary.get("top_fragile_reacquisition_items") or [] ), - "top_just_reacquired_items": list(operator_summary.get("top_just_reacquired_items") or []), + "top_just_reacquired_items": list( + operator_summary.get("top_just_reacquired_items") or [] + ), "top_holding_reacquired_items": list( operator_summary.get("top_holding_reacquired_items") or [] ), @@ -1300,7 +1387,9 @@ def build_weekly_review_pack( "top_fragile_items": grouped_focus_items["fragile"][:3], "top_revalidate_items": grouped_focus_items["revalidate"][:3], } - result = finalize_weekly_pack(apply_weekly_scheduling_overlay(weekly_pack, operator_summary)) + result = finalize_weekly_pack( + apply_weekly_scheduling_overlay(weekly_pack, operator_summary) + ) result["risk_posture"] = _extract_risk_posture(output_dir) return result @@ -1703,15 +1792,21 @@ def build_follow_through_recovery_summary(value: Any) -> str: def build_follow_through_recovery_persistence_status_label(value: Any) -> str: - return _follow_through_status_label(value, key="follow_through_recovery_persistence_status") + return _follow_through_status_label( + value, key="follow_through_recovery_persistence_status" + ) def build_follow_through_recovery_persistence_summary(value: Any) -> str: - return _follow_through_summary(value, key="follow_through_recovery_persistence_summary") + return _follow_through_summary( + value, key="follow_through_recovery_persistence_summary" + ) def build_follow_through_relapse_churn_status_label(value: Any) -> str: - return _follow_through_status_label(value, key="follow_through_relapse_churn_status") + return _follow_through_status_label( + value, key="follow_through_relapse_churn_status" + ) def build_follow_through_relapse_churn_summary(value: Any) -> str: @@ -1719,15 +1814,21 @@ def build_follow_through_relapse_churn_summary(value: Any) -> str: def build_follow_through_recovery_freshness_status_label(value: Any) -> str: - return _follow_through_status_label(value, key="follow_through_recovery_freshness_status") + return _follow_through_status_label( + value, key="follow_through_recovery_freshness_status" + ) def build_follow_through_recovery_freshness_summary(value: Any) -> str: - return _follow_through_summary(value, key="follow_through_recovery_freshness_summary") + return _follow_through_summary( + value, key="follow_through_recovery_freshness_summary" + ) def build_follow_through_recovery_decay_status_label(value: Any) -> str: - return _follow_through_status_label(value, key="follow_through_recovery_decay_status") + return _follow_through_status_label( + value, key="follow_through_recovery_decay_status" + ) def build_follow_through_recovery_decay_summary(value: Any) -> str: @@ -1735,11 +1836,15 @@ def build_follow_through_recovery_decay_summary(value: Any) -> str: def build_follow_through_recovery_memory_reset_status_label(value: Any) -> str: - return _follow_through_status_label(value, key="follow_through_recovery_memory_reset_status") + return _follow_through_status_label( + value, key="follow_through_recovery_memory_reset_status" + ) def build_follow_through_recovery_memory_reset_summary(value: Any) -> str: - return _follow_through_summary(value, key="follow_through_recovery_memory_reset_summary") + return _follow_through_summary( + value, key="follow_through_recovery_memory_reset_summary" + ) def build_follow_through_recovery_rebuild_strength_status_label(value: Any) -> str: @@ -1749,15 +1854,21 @@ def build_follow_through_recovery_rebuild_strength_status_label(value: Any) -> s def build_follow_through_recovery_rebuild_strength_summary(value: Any) -> str: - return _follow_through_summary(value, key="follow_through_recovery_rebuild_strength_summary") + return _follow_through_summary( + value, key="follow_through_recovery_rebuild_strength_summary" + ) def build_follow_through_recovery_reacquisition_status_label(value: Any) -> str: - return _follow_through_status_label(value, key="follow_through_recovery_reacquisition_status") + return _follow_through_status_label( + value, key="follow_through_recovery_reacquisition_status" + ) def build_follow_through_recovery_reacquisition_summary(value: Any) -> str: - return _follow_through_summary(value, key="follow_through_recovery_reacquisition_summary") + return _follow_through_summary( + value, key="follow_through_recovery_reacquisition_summary" + ) def build_follow_through_reacquisition_durability_status_label(value: Any) -> str: @@ -1796,7 +1907,9 @@ def build_follow_through_reacquisition_softening_decay_summary(value: Any) -> st ) -def build_follow_through_reacquisition_confidence_retirement_status_label(value: Any) -> str: +def build_follow_through_reacquisition_confidence_retirement_status_label( + value: Any, +) -> str: return _follow_through_status_label( value, key="follow_through_reacquisition_confidence_retirement_status" ) @@ -1808,7 +1921,9 @@ def build_follow_through_reacquisition_confidence_retirement_summary(value: Any) ) -def build_follow_through_reacquisition_revalidation_recovery_status_label(value: Any) -> str: +def build_follow_through_reacquisition_revalidation_recovery_status_label( + value: Any, +) -> str: return _follow_through_status_label( value, key="follow_through_reacquisition_revalidation_recovery_status" ) @@ -1823,9 +1938,15 @@ def build_follow_through_reacquisition_revalidation_recovery_summary(value: Any) def _operator_focus_bucket_key(value: Any) -> str: mapped = _mapping(value) lane = str(mapped.get("lane") or "").strip() - checkpoint_status = str(mapped.get("follow_through_checkpoint_status") or "").strip() - escalation_status = str(mapped.get("follow_through_escalation_status") or "").strip() - relapse_churn_status = str(mapped.get("follow_through_relapse_churn_status") or "").strip() + checkpoint_status = str( + mapped.get("follow_through_checkpoint_status") or "" + ).strip() + escalation_status = str( + mapped.get("follow_through_escalation_status") or "" + ).strip() + relapse_churn_status = str( + mapped.get("follow_through_relapse_churn_status") or "" + ).strip() recovery_persistence_status = str( mapped.get("follow_through_recovery_persistence_status") or "" ).strip() @@ -1852,10 +1973,14 @@ def _operator_focus_bucket_key(value: Any) -> str: or escalation_status == "escalate-now" ): return "act-now" - if confidence_retirement_status == "revalidation-needed" or revalidation_recovery_status in { - "under-revalidation", - "insufficient-evidence", - }: + if ( + confidence_retirement_status == "revalidation-needed" + or revalidation_recovery_status + in { + "under-revalidation", + "insufficient-evidence", + } + ): return "revalidate" if relapse_churn_status in {"fragile", "churn", "blocked"}: return "fragile" @@ -1909,8 +2034,12 @@ def build_operator_focus_summary(value: Any) -> str: if focus_key == "revalidate": return ( _first_nonempty( - build_follow_through_reacquisition_revalidation_recovery_summary(mapped), - build_follow_through_reacquisition_confidence_retirement_summary(mapped), + build_follow_through_reacquisition_revalidation_recovery_summary( + mapped + ), + build_follow_through_reacquisition_confidence_retirement_summary( + mapped + ), build_follow_through_checkpoint(mapped), ) or "This target still needs revalidation before confidence can be restored." @@ -1918,7 +2047,9 @@ def build_operator_focus_summary(value: Any) -> str: if focus_key == "fragile": return ( _first_nonempty( - build_follow_through_reacquisition_revalidation_recovery_summary(mapped), + build_follow_through_reacquisition_revalidation_recovery_summary( + mapped + ), build_follow_through_reacquisition_softening_decay_summary(mapped), build_follow_through_relapse_churn_summary(mapped), build_follow_through_recovery_persistence_summary(mapped), @@ -1929,7 +2060,9 @@ def build_operator_focus_summary(value: Any) -> str: if focus_key == "improving": return ( _first_nonempty( - build_follow_through_reacquisition_revalidation_recovery_summary(mapped), + build_follow_through_reacquisition_revalidation_recovery_summary( + mapped + ), build_follow_through_reacquisition_consolidation_summary(mapped), build_follow_through_reacquisition_durability_summary(mapped), build_follow_through_recovery_summary(mapped), @@ -1998,13 +2131,17 @@ def build_scorecard_line(value: Any) -> str: if not entry: return f"Scorecard: {NO_SCORECARD_SUMMARY}" program_label = str(entry.get("program_label") or "Default") - maturity_level = str(entry.get("maturity_level") or "missing-basics").replace("-", " ").title() + maturity_level = ( + str(entry.get("maturity_level") or "missing-basics").replace("-", " ").title() + ) target = str(entry.get("target_maturity") or "operating").replace("-", " ").title() return f"Scorecard: {program_label} — {maturity_level} (target {target})" def build_operating_path_line(value: Any) -> str: - from src.portfolio_pathing import build_operating_path_line as _build_operating_path_line + from src.portfolio_pathing import ( + build_operating_path_line as _build_operating_path_line, + ) entry = build_portfolio_catalog_entry(value) return _build_operating_path_line(entry) @@ -2019,7 +2156,9 @@ def build_maturity_gap_summary(value: Any) -> str: target = str(entry.get("target_maturity") or "operating").replace("-", " ").title() if status == "on-track": return f"No active maturity gap. {program_label} is already meeting the {target} target." - top_gaps = [str(item).strip() for item in entry.get("top_gaps", []) if str(item).strip()] + top_gaps = [ + str(item).strip() for item in entry.get("top_gaps", []) if str(item).strip() + ] if top_gaps: return f"{', '.join(top_gaps[:3]).lower()} are still below the {program_label.lower()} bar." return str(entry.get("summary") or NO_MATURITY_GAP_SUMMARY) @@ -2043,7 +2182,8 @@ def build_operator_effectiveness_line(report_data: Any) -> str: def build_high_pressure_queue_trend_line(report_data: Any) -> str: operator_summary = _mapping(_mapping(report_data).get("operator_summary")) return str( - operator_summary.get("high_pressure_queue_trend_summary") or NO_HIGH_PRESSURE_QUEUE_TREND + operator_summary.get("high_pressure_queue_trend_summary") + or NO_HIGH_PRESSURE_QUEUE_TREND ) @@ -2051,7 +2191,10 @@ def build_action_sync_summary(report_data: Any) -> str: summary = _mapping(_mapping(report_data).get("action_sync_summary")) if not summary: summary = ( - _mapping(_mapping(report_data).get("operator_summary")).get("action_sync_summary") or {} + _mapping(_mapping(report_data).get("operator_summary")).get( + "action_sync_summary" + ) + or {} ) return str(_mapping(summary).get("summary") or NO_ACTION_SYNC_SUMMARY) @@ -2078,7 +2221,9 @@ def build_apply_readiness_summary(report_data: Any) -> str: summary = _mapping(_mapping(report_data).get("apply_readiness_summary")) if not summary: summary = ( - _mapping(_mapping(report_data).get("operator_summary")).get("apply_readiness_summary") + _mapping(_mapping(report_data).get("operator_summary")).get( + "apply_readiness_summary" + ) or {} ) return str(_mapping(summary).get("summary") or NO_APPLY_READINESS_SUMMARY) @@ -2088,7 +2233,9 @@ def build_next_apply_candidate_line(report_data: Any) -> str: candidate = _mapping(_mapping(report_data).get("next_apply_candidate")) if not candidate: candidate = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_apply_candidate") + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_apply_candidate" + ) or {} ) return str(_mapping(candidate).get("summary") or NO_NEXT_APPLY_CANDIDATE) @@ -2098,7 +2245,9 @@ def build_action_sync_command_hint(report_data: Any) -> str: candidate = _mapping(_mapping(report_data).get("next_apply_candidate")) if not candidate: candidate = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_apply_candidate") + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_apply_candidate" + ) or {} ) return str( @@ -2112,7 +2261,9 @@ def build_campaign_outcomes_summary(report_data: Any) -> str: summary = _mapping(_mapping(report_data).get("campaign_outcomes_summary")) if not summary: summary = ( - _mapping(_mapping(report_data).get("operator_summary")).get("campaign_outcomes_summary") + _mapping(_mapping(report_data).get("operator_summary")).get( + "campaign_outcomes_summary" + ) or {} ) return str(_mapping(summary).get("summary") or NO_CAMPAIGN_OUTCOMES_SUMMARY) @@ -2122,7 +2273,9 @@ def build_next_monitoring_step_line(report_data: Any) -> str: step = _mapping(_mapping(report_data).get("next_monitoring_step")) if not step: step = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_monitoring_step") + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_monitoring_step" + ) or {} ) return str(_mapping(step).get("summary") or NO_NEXT_MONITORING_STEP) @@ -2132,7 +2285,9 @@ def build_campaign_tuning_summary(report_data: Any) -> str: summary = _mapping(_mapping(report_data).get("campaign_tuning_summary")) if not summary: summary = ( - _mapping(_mapping(report_data).get("operator_summary")).get("campaign_tuning_summary") + _mapping(_mapping(report_data).get("operator_summary")).get( + "campaign_tuning_summary" + ) or {} ) return str(_mapping(summary).get("summary") or NO_CAMPAIGN_TUNING_SUMMARY) @@ -2142,7 +2297,10 @@ def build_next_tuned_campaign_line(report_data: Any) -> str: campaign = _mapping(_mapping(report_data).get("next_tuned_campaign")) if not campaign: campaign = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_tuned_campaign") or {} + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_tuned_campaign" + ) + or {} ) return str(_mapping(campaign).get("summary") or NO_NEXT_TUNED_CAMPAIGN) @@ -2160,14 +2318,18 @@ def build_historical_portfolio_intelligence_summary(report_data: Any) -> str: ) or {} ) - return str(_mapping(summary).get("summary") or NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY) + return str( + _mapping(summary).get("summary") or NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY + ) def build_next_historical_focus_line(report_data: Any) -> str: focus = _mapping(_mapping(report_data).get("next_historical_focus")) if not focus: focus = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_historical_focus") + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_historical_focus" + ) or {} ) return str(_mapping(focus).get("summary") or NO_NEXT_HISTORICAL_FOCUS) @@ -2189,7 +2351,9 @@ def build_next_safe_automation_step_line(report_data: Any) -> str: step = _mapping(_mapping(report_data).get("next_safe_automation_step")) if not step: step = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_safe_automation_step") + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_safe_automation_step" + ) or {} ) return str(_mapping(step).get("summary") or NO_NEXT_SAFE_AUTOMATION_STEP) @@ -2199,7 +2363,9 @@ def build_approval_workflow_summary(report_data: Any) -> str: summary = _mapping(_mapping(report_data).get("approval_workflow_summary")) if not summary: summary = ( - _mapping(_mapping(report_data).get("operator_summary")).get("approval_workflow_summary") + _mapping(_mapping(report_data).get("operator_summary")).get( + "approval_workflow_summary" + ) or {} ) return str(_mapping(summary).get("summary") or NO_APPROVAL_WORKFLOW_SUMMARY) @@ -2209,7 +2375,9 @@ def build_next_approval_review_line(report_data: Any) -> str: step = _mapping(_mapping(report_data).get("next_approval_review")) if not step: step = ( - _mapping(_mapping(report_data).get("operator_summary")).get("next_approval_review") + _mapping(_mapping(report_data).get("operator_summary")).get( + "next_approval_review" + ) or {} ) return str(_mapping(step).get("summary") or NO_NEXT_APPROVAL_REVIEW) @@ -2251,9 +2419,7 @@ def build_automation_line(value: Any) -> str: return f"{ACTION_SYNC_CANONICAL_LABELS['automation_guidance']}: {summary}" posture = str(mapped.get("automation_posture") or "").strip() if posture: - return ( - f"{ACTION_SYNC_CANONICAL_LABELS['automation_guidance']}: {posture.replace('-', ' ')}." - ) + return f"{ACTION_SYNC_CANONICAL_LABELS['automation_guidance']}: {posture.replace('-', ' ')}." return NO_AUTOMATION_GUIDANCE_LINE @@ -2318,10 +2484,14 @@ def _build_operator_focus_item( ) -> dict[str, Any]: return { "repo": mapped.get("repo") or mapped.get("repo_name") or "Portfolio", - "title": str(mapped.get("title") or mapped.get("summary") or "Operator attention item"), + "title": str( + mapped.get("title") or mapped.get("summary") or "Operator attention item" + ), "lane": mapped.get("lane_label") or mapped.get("lane") or "ready", "why": str( - mapped.get("lane_reason") or mapped.get("summary") or "Operator pressure is active." + mapped.get("lane_reason") + or mapped.get("summary") + or "Operator pressure is active." ), "next_step": str( mapped.get("recommended_action") @@ -2332,26 +2502,40 @@ def _build_operator_focus_item( "follow_through_status": build_follow_through_status_label(mapped), "follow_through_summary": build_follow_through_summary(mapped), "follow_through_checkpoint": build_follow_through_checkpoint(mapped), - "follow_through_checkpoint_timing": build_follow_through_checkpoint_status_label(mapped), - "follow_through_escalation": build_follow_through_escalation_status_label(mapped), - "follow_through_escalation_summary": build_follow_through_escalation_summary(mapped), + "follow_through_checkpoint_timing": build_follow_through_checkpoint_status_label( + mapped + ), + "follow_through_escalation": build_follow_through_escalation_status_label( + mapped + ), + "follow_through_escalation_summary": build_follow_through_escalation_summary( + mapped + ), "follow_through_recovery": build_follow_through_recovery_status_label(mapped), - "follow_through_recovery_summary": build_follow_through_recovery_summary(mapped), + "follow_through_recovery_summary": build_follow_through_recovery_summary( + mapped + ), "follow_through_recovery_persistence": build_follow_through_recovery_persistence_status_label( mapped ), "follow_through_recovery_persistence_summary": build_follow_through_recovery_persistence_summary( mapped ), - "follow_through_relapse_churn": build_follow_through_relapse_churn_status_label(mapped), - "follow_through_relapse_churn_summary": build_follow_through_relapse_churn_summary(mapped), + "follow_through_relapse_churn": build_follow_through_relapse_churn_status_label( + mapped + ), + "follow_through_relapse_churn_summary": build_follow_through_relapse_churn_summary( + mapped + ), "follow_through_recovery_freshness": build_follow_through_recovery_freshness_status_label( mapped ), "follow_through_recovery_freshness_summary": build_follow_through_recovery_freshness_summary( mapped ), - "follow_through_recovery_decay": build_follow_through_recovery_decay_status_label(mapped), + "follow_through_recovery_decay": build_follow_through_recovery_decay_status_label( + mapped + ), "follow_through_recovery_decay_summary": build_follow_through_recovery_decay_summary( mapped ), @@ -2417,7 +2601,9 @@ def _build_operator_focus_item( or "No current Action Sync guidance is surfaced for this item." ), "suggested_campaign": str(mapped.get("suggested_campaign") or ""), - "suggested_writeback_target": str(mapped.get("suggested_writeback_target") or "none"), + "suggested_writeback_target": str( + mapped.get("suggested_writeback_target") or "none" + ), "action_sync_line": build_action_sync_line(mapped), "apply_packet_state": str(mapped.get("apply_packet_state") or "stay-local"), "apply_packet_summary": str( @@ -2442,7 +2628,8 @@ def _build_operator_focus_item( "campaign_tuning_line": build_campaign_tuning_line(mapped), "approval_state": str(mapped.get("approval_state") or "not-applicable"), "approval_summary": str( - mapped.get("approval_summary") or "No approval workflow is surfaced for this item yet." + mapped.get("approval_summary") + or "No approval workflow is surfaced for this item yet." ), "approval_line": build_approval_workflow_line(mapped), "automation_posture": str(mapped.get("automation_posture") or "manual-only"), @@ -2458,25 +2645,27 @@ def _build_operator_focus_item( def _build_operator_focus_summary_from_groups( grouped_items: dict[str, list[dict[str, Any]]], ) -> str: - counts = {bucket: len(grouped_items.get(bucket, [])) for bucket in OPERATOR_FOCUS_DISPLAY_ORDER} + counts = { + bucket: len(grouped_items.get(bucket, [])) + for bucket in OPERATOR_FOCUS_DISPLAY_ORDER + } def _labels(bucket: str) -> str: items = grouped_items.get(bucket, [])[:3] - labels = [str(item.get("repo") or item.get("title") or "operator item") for item in items] + labels = [ + str(item.get("repo") or item.get("title") or "operator item") + for item in items + ] return _string_list(labels, fallback="the current queue") if counts["act-now"]: - return ( - f"{counts['act-now']} item(s) need immediate action first, led by {_labels('act-now')}." - ) + return f"{counts['act-now']} item(s) need immediate action first, led by {_labels('act-now')}." if counts["revalidate"]: return f"{counts['revalidate']} item(s) are in a revalidation posture, led by {_labels('revalidate')}." if counts["fragile"]: return f"{counts['fragile']} item(s) are improving but still fragile, led by {_labels('fragile')}." if counts["improving"]: - return ( - f"{counts['improving']} item(s) are clearly improving, led by {_labels('improving')}." - ) + return f"{counts['improving']} item(s) are clearly improving, led by {_labels('improving')}." if counts["watch-closely"]: return f"{counts['watch-closely']} item(s) should stay visible while more evidence arrives, led by {_labels('watch-closely')}." return NO_OPERATOR_FOCUS_SUMMARY @@ -2493,13 +2682,17 @@ def build_follow_through_resurfacing_reason(value: Any) -> str: def build_action_handoff_summary(value: Any) -> str: mapped = _mapping(value) - action = str(mapped.get("recommended_action") or mapped.get("next_step") or "").strip() + action = str( + mapped.get("recommended_action") or mapped.get("next_step") or "" + ).strip() if action: return action return "Review the latest state and choose the next concrete follow-through step." -def build_queue_pressure_summary(report_data: Any, diff_data: dict | None = None) -> str: +def build_queue_pressure_summary( + report_data: Any, diff_data: dict | None = None +) -> str: data = _mapping(report_data) operator_summary = _mapping(data.get("operator_summary")) counts = _mapping(operator_summary.get("counts")) @@ -2511,7 +2704,9 @@ def build_queue_pressure_summary(report_data: Any, diff_data: dict | None = None f"{counts.get('deferred', 0)} deferred item(s) are currently in the queue." ) - run_change_counts = data.get("run_change_counts") or build_run_change_counts(diff_data) + run_change_counts = data.get("run_change_counts") or build_run_change_counts( + diff_data + ) return ( f"{run_change_counts.get('score_improvements', 0)} improving, " f"{run_change_counts.get('score_regressions', 0)} regressing, " diff --git a/src/report_operating_paths.py b/src/report_operating_paths.py new file mode 100644 index 0000000..b18b964 --- /dev/null +++ b/src/report_operating_paths.py @@ -0,0 +1,48 @@ +"""Operating-path enrichment for reconstructed audit reports.""" + +from __future__ import annotations + +from src.models import AuditReport +from src.portfolio_pathing import ( + build_operating_path_entry, + build_operating_path_line, + build_operating_paths_summary, +) + + +def apply_operating_paths(report: AuditReport) -> AuditReport: + for audit in report.audits: + catalog_entry = dict(audit.portfolio_catalog or {}) + if not catalog_entry: + continue + path_entry = build_operating_path_entry( + catalog_entry, + intent_alignment=catalog_entry.get("intent_alignment", ""), + archived=audit.metadata.archived, + completeness_tier=audit.completeness_tier, + decision_quality_status=(report.operator_summary or {}) + .get("decision_quality_v1", {}) + .get("decision_quality_status", ""), + ) + path_line = build_operating_path_line(path_entry) + audit.portfolio_catalog = { + **path_entry, + "operating_path_line": path_line, + "operator_focus": catalog_entry.get("operator_focus", ""), + } + if audit.scorecard: + audit.portfolio_catalog["scorecard"] = dict(audit.scorecard) + audit_lookup = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} + for item in report.operator_queue: + repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() + catalog_entry = audit_lookup.get(repo_name, {}) + if not catalog_entry: + continue + item["portfolio_catalog"] = dict(catalog_entry) + item["operating_path"] = catalog_entry.get("operating_path", "") + item["path_override"] = catalog_entry.get("path_override", "") + item["path_confidence"] = catalog_entry.get("path_confidence", "") + item["path_rationale"] = catalog_entry.get("path_rationale", "") + item["operating_path_line"] = catalog_entry.get("operating_path_line", "") + report.operating_paths_summary = build_operating_paths_summary(report.audits) + return report diff --git a/src/report_operator_state.py b/src/report_operator_state.py new file mode 100644 index 0000000..fd5e32d --- /dev/null +++ b/src/report_operator_state.py @@ -0,0 +1,60 @@ +"""Operator-state enrichment for reconstructed audit reports.""" + +from __future__ import annotations + +from pathlib import Path + +from src.governance_activation import build_governance_summary +from src.models import AuditReport +from src.operator_control_center import build_operator_snapshot, normalize_review_state + + +def enrich_report_with_operator_state( + report: AuditReport, + *, + output_dir: Path, + diff_dict: dict | None, + triage_view: str, + portfolio_profile: str, + collection: str | None, +) -> AuditReport: + normalized = normalize_review_state( + report.to_dict(), output_dir=output_dir, diff_data=diff_dict, + portfolio_profile=portfolio_profile, collection_name=collection, + ) + normalized["governance_summary"] = build_governance_summary(normalized) + snapshot = build_operator_snapshot(normalized, output_dir=output_dir, triage_view=triage_view) + report.governance_summary = normalized.get("governance_summary", {}) + report.review_summary = normalized.get("review_summary", {}) + report.review_alerts = normalized.get("review_alerts", []) + report.material_changes = normalized.get("material_changes", []) + report.review_targets = normalized.get("review_targets", []) + report.review_history = normalized.get("review_history", []) + report.watch_state = normalized.get("watch_state", {}) + report.operator_summary = snapshot.get("operator_summary", {}) + report.operator_queue = snapshot.get("operator_queue", []) + report.portfolio_outcomes_summary = snapshot.get("portfolio_outcomes_summary", {}) + report.operator_effectiveness_summary = snapshot.get("operator_effectiveness_summary", {}) + report.high_pressure_queue_history = snapshot.get("high_pressure_queue_history", []) + report.campaign_readiness_summary = snapshot.get("campaign_readiness_summary", {}) + report.action_sync_summary = snapshot.get("action_sync_summary", {}) + report.next_action_sync_step = snapshot.get("next_action_sync_step", "") + report.action_sync_packets = snapshot.get("action_sync_packets", []) + report.apply_readiness_summary = snapshot.get("apply_readiness_summary", {}) + report.next_apply_candidate = snapshot.get("next_apply_candidate", {}) + report.action_sync_outcomes = snapshot.get("action_sync_outcomes", []) + report.campaign_outcomes_summary = snapshot.get("campaign_outcomes_summary", {}) + report.next_monitoring_step = snapshot.get("next_monitoring_step", {}) + report.action_sync_tuning = snapshot.get("action_sync_tuning", []) + report.campaign_tuning_summary = snapshot.get("campaign_tuning_summary", {}) + report.next_tuned_campaign = snapshot.get("next_tuned_campaign", {}) + report.historical_portfolio_intelligence = snapshot.get("historical_portfolio_intelligence", []) + report.intervention_ledger_summary = snapshot.get("intervention_ledger_summary", {}) + report.next_historical_focus = snapshot.get("next_historical_focus", {}) + report.action_sync_automation = snapshot.get("action_sync_automation", []) + report.automation_guidance_summary = snapshot.get("automation_guidance_summary", {}) + report.next_safe_automation_step = snapshot.get("next_safe_automation_step", {}) + report.approval_ledger = snapshot.get("approval_ledger", []) + report.approval_workflow_summary = snapshot.get("approval_workflow_summary", {}) + report.next_approval_review = snapshot.get("next_approval_review", {}) + return report diff --git a/src/report_portfolio_catalog.py b/src/report_portfolio_catalog.py new file mode 100644 index 0000000..92e4546 --- /dev/null +++ b/src/report_portfolio_catalog.py @@ -0,0 +1,63 @@ +"""Portfolio-catalog enrichment for audit reports.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.models import AuditReport +from src.portfolio_catalog import ( + DEFAULT_CATALOG_PATH, + build_catalog_line, + build_intent_alignment_summary, + build_portfolio_catalog_summary, + catalog_entry_for_repo, + evaluate_intent_alignment, + load_portfolio_catalog, +) +from src.report_enrichment import build_operator_focus + + +def apply_portfolio_catalog(report: AuditReport, args: Any) -> AuditReport: + catalog_path = getattr(args, "catalog", None) or DEFAULT_CATALOG_PATH + catalog_data = load_portfolio_catalog(Path(catalog_path)) + queue_by_repo = { + str(item.get("repo") or item.get("repo_name") or "").strip(): item + for item in (report.operator_queue or []) + if str(item.get("repo") or item.get("repo_name") or "").strip() + } + for audit in report.audits: + base_entry = catalog_entry_for_repo(audit.metadata.to_dict(), catalog_data) + operator_focus = build_operator_focus(queue_by_repo.get(audit.metadata.name, {})) + intent_alignment, intent_alignment_reason = evaluate_intent_alignment( + base_entry, + completeness_tier=audit.completeness_tier, + archived=audit.metadata.archived, + operator_focus=operator_focus, + ) + audit.portfolio_catalog = { + **base_entry, + "catalog_line": build_catalog_line(base_entry), + "intent_alignment": intent_alignment, + "intent_alignment_reason": intent_alignment_reason, + "intent_alignment_line": f"{intent_alignment}: {intent_alignment_reason}", + "operator_focus": operator_focus, + } + audit_lookup = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} + for item in report.operator_queue: + repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() + catalog_entry = audit_lookup.get(repo_name, {}) + if catalog_entry: + item["portfolio_catalog"] = dict(catalog_entry) + item["catalog_line"] = catalog_entry.get("catalog_line", "") + item["intent_alignment"] = catalog_entry.get("intent_alignment", "missing-contract") + item["intent_alignment_reason"] = catalog_entry.get("intent_alignment_reason", "") + report.portfolio_catalog_summary = build_portfolio_catalog_summary( + report.audits, + catalog_path=str(catalog_path), + ) + report.portfolio_catalog_summary["catalog_exists"] = catalog_data.get("exists", False) + report.portfolio_catalog_summary["errors"] = catalog_data.get("errors", []) + report.portfolio_catalog_summary["warnings"] = catalog_data.get("warnings", []) + report.intent_alignment_summary = build_intent_alignment_summary(report.audits) + return report diff --git a/src/report_scorecards.py b/src/report_scorecards.py new file mode 100644 index 0000000..3207a55 --- /dev/null +++ b/src/report_scorecards.py @@ -0,0 +1,72 @@ +"""Scorecard enrichment for audit reports.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.models import AuditReport +from src.portfolio_catalog import build_intent_alignment_summary, evaluate_intent_alignment +from src.report_enrichment import ( + build_maturity_gap_summary, + build_operator_focus, + build_scorecard_line, +) +from src.scorecards import ( + DEFAULT_SCORECARDS_PATH, + evaluate_scorecards_for_report, + load_scorecards, +) + + +def apply_scorecards(report: AuditReport, args: Any) -> AuditReport: + scorecards_path = getattr(args, "scorecards", None) or DEFAULT_SCORECARDS_PATH + scorecards_data = load_scorecards(Path(scorecards_path)) + repo_results, summary, programs = evaluate_scorecards_for_report(report, scorecards_data) + by_repo = {result.get("repo", ""): result for result in repo_results} + queue_by_repo = { + str(item.get("repo") or item.get("repo_name") or "").strip(): item + for item in (report.operator_queue or []) + if str(item.get("repo") or item.get("repo_name") or "").strip() + } + for audit in report.audits: + result = by_repo.get(audit.metadata.name, {}) + audit.scorecard = dict(result) + if audit.portfolio_catalog: + audit.portfolio_catalog["scorecard"] = dict(result) + operator_focus = audit.portfolio_catalog.get("operator_focus", "") + if not operator_focus: + operator_focus = build_operator_focus( + queue_by_repo.get(audit.metadata.name, {}) + ) + intent_alignment, intent_alignment_reason = evaluate_intent_alignment( + audit.portfolio_catalog, + completeness_tier=audit.completeness_tier, + archived=audit.metadata.archived, + operator_focus=operator_focus, + ) + audit.portfolio_catalog.update( + { + "intent_alignment": intent_alignment, + "intent_alignment_reason": intent_alignment_reason, + "intent_alignment_line": f"{intent_alignment}: {intent_alignment_reason}", + "operator_focus": operator_focus, + } + ) + catalog_by_repo = {audit.metadata.name: audit.portfolio_catalog for audit in report.audits} + for item in report.operator_queue: + repo_name = str(item.get("repo") or item.get("repo_name") or "").strip() + result = by_repo.get(repo_name, {}) + catalog_entry = catalog_by_repo.get(repo_name, {}) + if catalog_entry: + item["portfolio_catalog"] = dict(catalog_entry) + item["intent_alignment"] = catalog_entry.get("intent_alignment", "") + item["intent_alignment_reason"] = catalog_entry.get("intent_alignment_reason", "") + if result: + item["scorecard"] = dict(result) + item["scorecard_line"] = build_scorecard_line(item) + item["maturity_gap_summary"] = build_maturity_gap_summary(item) + report.scorecards_summary = summary + report.scorecard_programs = programs + report.intent_alignment_summary = build_intent_alignment_summary(report.audits) + return report diff --git a/src/report_shared_artifacts.py b/src/report_shared_artifacts.py new file mode 100644 index 0000000..4e3cbb5 --- /dev/null +++ b/src/report_shared_artifacts.py @@ -0,0 +1,66 @@ +"""Regenerate shared operator artifacts from an enriched audit report.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from src.excel_export import export_excel +from src.history import load_repo_score_history, load_trend_data +from src.models import AuditReport +from src.operator_approval_artifacts import write_approval_center_artifacts +from src.operator_control_center_artifacts import write_control_center_artifacts +from src.report_state import report_artifact_datetime +from src.reporter import ( + write_json_report, + write_markdown_report, + write_pcc_export, + write_raw_metadata, +) +from src.review_pack import export_review_pack +from src.warehouse import write_warehouse_snapshot +from src.web_export import export_html_dashboard + + +def refresh_shared_artifacts_from_report( + report: AuditReport, + output_dir: Path, + args: Any, + *, + diff_dict: dict | None = None, +) -> dict[str, Path]: + approval_json, approval_md, _payload = write_approval_center_artifacts( + report, output_dir, approval_view=getattr(args, "approval_view", "all") + ) + json_path = write_json_report(report, output_dir) + write_markdown_report(report, output_dir, diff_data=diff_dict) + write_pcc_export(report, output_dir) + write_raw_metadata(report, output_dir) + trend_data = load_trend_data() + score_history = load_repo_score_history() + export_excel( + json_path, + output_dir / f"audit-dashboard-{report.username}-{report.generated_at.strftime('%Y-%m-%d')}.xlsx", + trend_data=trend_data, diff_data=diff_dict, score_history=score_history, + portfolio_profile=args.portfolio_profile, collection=args.collection, + excel_mode=args.excel_mode, truth_dir=output_dir, + ) + export_review_pack(report.to_dict(), output_dir, diff_data=diff_dict, + portfolio_profile=args.portfolio_profile, collection=args.collection) + export_html_dashboard(report.to_dict(), output_dir, trend_data, score_history, + diff_data=diff_dict, portfolio_profile=args.portfolio_profile, + collection=args.collection) + artifact_generated_at = report_artifact_datetime(json_path, report.generated_at) + snapshot = {"operator_summary": report.operator_summary, "operator_queue": report.operator_queue} + control_json, control_md, weekly_json, weekly_md, _control_payload = write_control_center_artifacts( + report.to_dict(), snapshot, output_dir, username=report.username, + generated_at=artifact_generated_at, report_reference=str(json_path), diff_dict=diff_dict, + ) + report.operator_summary["control_center_reference"] = str(control_json) + write_warehouse_snapshot(report, output_dir, json_path) + return { + "json_path": json_path, "control_center_json": control_json, + "control_center_md": control_md, "weekly_command_center_json": weekly_json, + "weekly_command_center_md": weekly_md, "approval_center_json": approval_json, + "approval_center_md": approval_md, + } diff --git a/src/report_state.py b/src/report_state.py new file mode 100644 index 0000000..9757c80 --- /dev/null +++ b/src/report_state.py @@ -0,0 +1,131 @@ +"""Leaf report-discovery and artifact-time helpers.""" + +from __future__ import annotations + +import json +from datetime import datetime, timezone +from pathlib import Path + +from src.models import AnalyzerResult, AuditReport, RepoAudit, RepoMetadata +from src.registry_parser import RegistryReconciliation + + +def parse_iso_datetime(value: str | None) -> datetime | None: + if not value: + return None + return datetime.fromisoformat(value.replace("Z", "+00:00")) + + +def audit_from_dict(data: dict) -> RepoAudit: + meta_data = data.get("metadata", {}) + metadata = RepoMetadata( + name=meta_data["name"], + full_name=meta_data["full_name"], + description=meta_data.get("description"), + language=meta_data.get("language"), + languages=meta_data.get("languages", {}), + private=meta_data["private"], + fork=meta_data["fork"], + archived=meta_data["archived"], + created_at=parse_iso_datetime(meta_data.get("created_at")), # type: ignore[arg-type] + updated_at=parse_iso_datetime(meta_data.get("updated_at")), # type: ignore[arg-type] + pushed_at=parse_iso_datetime(meta_data.get("pushed_at")), + default_branch=meta_data.get("default_branch", "main"), + stars=meta_data.get("stars", 0), + forks=meta_data.get("forks", 0), + open_issues=meta_data.get("open_issues", 0), + size_kb=meta_data.get("size_kb", 0), + html_url=meta_data.get("html_url", ""), + clone_url=meta_data.get("clone_url", ""), + topics=meta_data.get("topics", []), + ) + analyzer_results = [ + AnalyzerResult( + dimension=result["dimension"], + score=result["score"], + max_score=result["max_score"], + findings=result["findings"], + details=result.get("details", {}), + ) + for result in data.get("analyzer_results", []) + ] + return RepoAudit( + metadata=metadata, + analyzer_results=analyzer_results, + overall_score=data.get("overall_score", 0), + completeness_tier=data.get("completeness_tier", "abandoned"), + interest_score=data.get("interest_score", 0), + interest_tier=data.get("interest_tier", "mundane"), + grade=data.get("grade", "F"), interest_grade=data.get("interest_grade", "F"), + badges=data.get("badges", []), next_badges=data.get("next_badges", []), + flags=data.get("flags", []), lenses=data.get("lenses", {}), hotspots=data.get("hotspots", []), + action_candidates=data.get("action_candidates", []), security_posture=data.get("security_posture", {}), + score_explanation=data.get("score_explanation", {}), portfolio_catalog=data.get("portfolio_catalog", {}), + scorecard=data.get("scorecard", {}), ossf_scorecard=data.get("ossf_scorecard", {}), + ) + + +def report_from_dict(data: dict) -> AuditReport: + reconciliation = ( + RegistryReconciliation(**data["reconciliation"]) + if data.get("reconciliation") + else None + ) + summary = data.get("summary", {}) + return AuditReport( + username=data["username"], + generated_at=parse_iso_datetime(data.get("generated_at")) or datetime.now(timezone.utc), + total_repos=data.get("total_repos", 0), repos_audited=data.get("repos_audited", 0), + tier_distribution=data.get("tier_distribution", {}), average_score=data.get("average_score", 0), + language_distribution=data.get("language_distribution", {}), + audits=[audit_from_dict(audit) for audit in data.get("audits", [])], errors=data.get("errors", []), + portfolio_grade=data.get("portfolio_grade", "F"), portfolio_health_score=data.get("portfolio_health_score", 0), + tech_stack=data.get("tech_stack", {}), best_work=data.get("best_work", []), + most_active=summary.get("most_active", []), most_neglected=summary.get("most_neglected", []), + highest_scored=summary.get("highest_scored", []), lowest_scored=summary.get("lowest_scored", []), + scoring_profile=data.get("scoring_profile", "default"), run_mode=data.get("run_mode", "full"), + portfolio_baseline_size=data.get("portfolio_baseline_size", len(data.get("audits", []))), + baseline_signature=data.get("baseline_signature", ""), baseline_context=data.get("baseline_context", {}), + schema_version=data.get("schema_version", "3.7"), lenses=data.get("lenses", {}), hotspots=data.get("hotspots", []), + implementation_hotspots=data.get("implementation_hotspots", []), implementation_hotspots_summary=data.get("implementation_hotspots_summary", {}), + portfolio_outcomes_summary=data.get("portfolio_outcomes_summary", {}), operator_effectiveness_summary=data.get("operator_effectiveness_summary", {}), + high_pressure_queue_history=data.get("high_pressure_queue_history", []), campaign_readiness_summary=data.get("campaign_readiness_summary", {}), + action_sync_summary=data.get("action_sync_summary", {}), next_action_sync_step=data.get("next_action_sync_step", ""), action_sync_packets=data.get("action_sync_packets", []), + apply_readiness_summary=data.get("apply_readiness_summary", {}), next_apply_candidate=data.get("next_apply_candidate", {}), action_sync_outcomes=data.get("action_sync_outcomes", []), + campaign_outcomes_summary=data.get("campaign_outcomes_summary", {}), next_monitoring_step=data.get("next_monitoring_step", {}), + action_sync_tuning=data.get("action_sync_tuning", []), campaign_tuning_summary=data.get("campaign_tuning_summary", {}), next_tuned_campaign=data.get("next_tuned_campaign", {}), + historical_portfolio_intelligence=data.get("historical_portfolio_intelligence", []), intervention_ledger_summary=data.get("intervention_ledger_summary", {}), next_historical_focus=data.get("next_historical_focus", {}), + action_sync_automation=data.get("action_sync_automation", []), automation_guidance_summary=data.get("automation_guidance_summary", {}), next_safe_automation_step=data.get("next_safe_automation_step", {}), + approval_ledger=data.get("approval_ledger", []), approval_workflow_summary=data.get("approval_workflow_summary", {}), next_approval_review=data.get("next_approval_review", {}), + security_posture=data.get("security_posture", {}), security_governance_preview=data.get("security_governance_preview", []), collections=data.get("collections", {}), profiles=data.get("profiles", {}), + scenario_summary=data.get("scenario_summary", {}), action_backlog=data.get("action_backlog", []), campaign_summary=data.get("campaign_summary", {}), + writeback_preview=data.get("writeback_preview", {}), writeback_results=data.get("writeback_results", {}), action_runs=data.get("action_runs", []), external_refs=data.get("external_refs", {}), + managed_state_drift=data.get("managed_state_drift", []), rollback_preview=data.get("rollback_preview", {}), campaign_history=data.get("campaign_history", []), + governance_preview=data.get("governance_preview", {}), governance_approval=data.get("governance_approval", {}), governance_results=data.get("governance_results", {}), + governance_history=data.get("governance_history", []), governance_drift=data.get("governance_drift", []), governance_summary=data.get("governance_summary", {}), + preflight_summary=data.get("preflight_summary", {}), review_summary=data.get("review_summary", {}), review_alerts=data.get("review_alerts", []), + material_changes=data.get("material_changes", []), review_targets=data.get("review_targets", []), review_history=data.get("review_history", []), + watch_state=data.get("watch_state", {}), operator_summary=data.get("operator_summary", {}), operator_queue=data.get("operator_queue", []), + portfolio_catalog_summary=data.get("portfolio_catalog_summary", {}), operating_paths_summary=data.get("operating_paths_summary", {}), + intent_alignment_summary=data.get("intent_alignment_summary", {}), scorecards_summary=data.get("scorecards_summary", {}), + scorecard_programs=data.get("scorecard_programs", {}), reconciliation=reconciliation, + ) +def load_latest_report(output_dir: Path) -> tuple[Path | None, dict | None]: + reports = sorted( + output_dir.glob("audit-report-*.json"), + key=lambda path: path.stat().st_mtime, + reverse=True, + ) + if not reports: + return None, None + latest = reports[0] + return latest, json.loads(latest.read_text()) + + +def report_artifact_datetime(report_path: Path | None, fallback: datetime) -> datetime: + if report_path: + stem = report_path.stem + if len(stem) >= 10: + parsed = datetime.fromisoformat(f"{stem[-10:]}T00:00:00+00:00") + return parsed + return fallback diff --git a/src/weekly_packaging.py b/src/weekly_packaging.py index ffd4d4f..51c8d04 100644 --- a/src/weekly_packaging.py +++ b/src/weekly_packaging.py @@ -2,46 +2,39 @@ from typing import Any +from src.report_contracts import ( + WeeklyStoryEvidenceItem, + WeeklyStorySection, + WeeklyStoryV1, +) from src.terminology import ACTION_SYNC_CANONICAL_LABELS -NO_FOLLOW_THROUGH_CHECKPOINT = "Use the next run or linked artifact to confirm whether the recommendation moved." +NO_FOLLOW_THROUGH_CHECKPOINT = ( + "Use the next run or linked artifact to confirm whether the recommendation moved." +) NO_OPERATOR_FOCUS_SUMMARY = "No operator focus bucket is currently surfaced." -NO_WHERE_TO_START_SUMMARY = "No meaningful implementation hotspot is currently surfaced." -NO_OPERATOR_OUTCOMES_SUMMARY = ( - "Not enough operator history is recorded yet to judge whether recent actions are improving portfolio outcomes." +NO_WHERE_TO_START_SUMMARY = ( + "No meaningful implementation hotspot is currently surfaced." ) +NO_OPERATOR_OUTCOMES_SUMMARY = "Not enough operator history is recorded yet to judge whether recent actions are improving portfolio outcomes." NO_ACTION_SYNC_SUMMARY = "No current campaign needs Action Sync yet, so the safest next move is to keep the story local." NO_ACTION_SYNC_STEP = "Stay local for now; no current campaign needs preview or apply." -NO_ACTION_SYNC_LINE = ( - "Action Sync: stay local until a campaign has meaningful actions and healthy writeback prerequisites." -) -NO_APPLY_READINESS_SUMMARY = ( - "No current campaign has a safe execution handoff yet, so the local story should stay local for now." -) -NO_NEXT_APPLY_CANDIDATE = "Stay local for now; no current campaign has a safe execution handoff." -NO_CAMPAIGN_OUTCOMES_SUMMARY = ( - "No recent Action Sync apply needs post-apply monitoring yet, so the local weekly story can stay local." +NO_ACTION_SYNC_LINE = "Action Sync: stay local until a campaign has meaningful actions and healthy writeback prerequisites." +NO_APPLY_READINESS_SUMMARY = "No current campaign has a safe execution handoff yet, so the local story should stay local for now." +NO_NEXT_APPLY_CANDIDATE = ( + "Stay local for now; no current campaign has a safe execution handoff." ) -NO_NEXT_MONITORING_STEP = "Stay local for now; no recent Action Sync apply needs post-apply follow-up yet." -NO_CAMPAIGN_TUNING_SUMMARY = ( - "Campaign tuning stays neutral until there is enough outcome history to bias tied recommendations." +NO_CAMPAIGN_OUTCOMES_SUMMARY = "No recent Action Sync apply needs post-apply monitoring yet, so the local weekly story can stay local." +NO_NEXT_MONITORING_STEP = ( + "Stay local for now; no recent Action Sync apply needs post-apply follow-up yet." ) +NO_CAMPAIGN_TUNING_SUMMARY = "Campaign tuning stays neutral until there is enough outcome history to bias tied recommendations." NO_NEXT_TUNED_CAMPAIGN = "No current campaign needs a tie-break candidate yet." -NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY = ( - "Historical portfolio intelligence is still thin, so the weekly story should stay grounded in the current run and recent operator queue." -) -NO_NEXT_HISTORICAL_FOCUS = ( - "Stay local for now; no repo has enough cross-run intervention evidence to demand a historical follow-up read yet." -) -NO_AUTOMATION_GUIDANCE_SUMMARY = ( - "Automation guidance stays quiet until a campaign has a clearly safe preview, follow-up, or manual-only posture." -) -NO_NEXT_SAFE_AUTOMATION_STEP = ( - "Stay local for now; no current campaign has a stronger safe automation posture than manual review." -) -NO_AUTOMATION_GUIDANCE_LINE = ( - "Automation Guidance: keep the next step human-led until a bounded safe posture is surfaced." -) +NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY = "Historical portfolio intelligence is still thin, so the weekly story should stay grounded in the current run and recent operator queue." +NO_NEXT_HISTORICAL_FOCUS = "Stay local for now; no repo has enough cross-run intervention evidence to demand a historical follow-up read yet." +NO_AUTOMATION_GUIDANCE_SUMMARY = "Automation guidance stays quiet until a campaign has a clearly safe preview, follow-up, or manual-only posture." +NO_NEXT_SAFE_AUTOMATION_STEP = "Stay local for now; no current campaign has a stronger safe automation posture than manual review." +NO_AUTOMATION_GUIDANCE_LINE = "Automation Guidance: keep the next step human-led until a bounded safe posture is surfaced." NO_APPROVAL_WORKFLOW_SUMMARY = "No current approval needs review yet, so the approval workflow can stay local for now." NO_NEXT_APPROVAL_REVIEW = "Stay local for now; no current approval needs review." NO_APPROVAL_WORKFLOW_LINE = "Approval Workflow: no current approval needs review yet." @@ -55,7 +48,9 @@ def _first_command_hint(*values: Any) -> str | None: return None -def _safe_posture_for_command(command_hint: str | None, *, default: str = "read-only") -> str: +def _safe_posture_for_command( + command_hint: str | None, *, default: str = "read-only" +) -> str: if not command_hint: return default if "--writeback-apply" in command_hint: @@ -74,8 +69,8 @@ def _build_story_evidence_item( *, safe_posture: str = "read-only", command_hint: str | None = None, -) -> dict[str, Any]: - item: dict[str, Any] = { +) -> WeeklyStoryEvidenceItem: + item: WeeklyStoryEvidenceItem = { "label": label, "summary": str(summary), "kind": kind, @@ -139,7 +134,9 @@ def _build_repo_briefing_explainability(briefing: dict[str, Any]) -> dict[str, A "Action Sync", briefing.get("action_sync_line", NO_ACTION_SYNC_LINE), "action-sync", - safe_posture=_safe_posture_for_command(briefing.get("apply_packet_command")), + safe_posture=_safe_posture_for_command( + briefing.get("apply_packet_command") + ), command_hint=_first_command_hint(briefing.get("apply_packet_command")), ), _build_story_evidence_item( @@ -157,8 +154,13 @@ def _build_repo_briefing_explainability(briefing: dict[str, Any]) -> dict[str, A ] return { **briefing, - "why_it_won": str(briefing.get("why_it_matters_line") or "No explanation summary is recorded yet."), - "next_step": str(briefing.get("what_to_do_next_line") or "No next action is recorded yet."), + "why_it_won": str( + briefing.get("why_it_matters_line") + or "No explanation summary is recorded yet." + ), + "next_step": str( + briefing.get("what_to_do_next_line") or "No next action is recorded yet." + ), "evidence_strip": evidence_strip, } @@ -173,8 +175,8 @@ def _campaign_evidence_items( label_prefix: str | None = None, command_keys: tuple[str, ...] = (), extra_formatter: Any | None = None, -) -> list[dict[str, Any]]: - evidence_items: list[dict[str, Any]] = [] +) -> list[WeeklyStoryEvidenceItem]: + evidence_items: list[WeeklyStoryEvidenceItem] = [] for item in items[:3]: label = str(item.get(label_key) or item.get(fallback_label_key) or "Campaign") if label_prefix: @@ -195,8 +197,10 @@ def _campaign_evidence_items( return evidence_items -def _approval_evidence_items(items: list[dict[str, Any]], *, label_prefix: str | None = None) -> list[dict[str, Any]]: - evidence_items: list[dict[str, Any]] = [] +def _approval_evidence_items( + items: list[dict[str, Any]], *, label_prefix: str | None = None +) -> list[WeeklyStoryEvidenceItem]: + evidence_items: list[WeeklyStoryEvidenceItem] = [] for item in items[:3]: label = str(item.get("label") or item.get("subject_key") or "Approval") if label_prefix: @@ -212,53 +216,75 @@ def _approval_evidence_items(items: list[dict[str, Any]], *, label_prefix: str | label, summary, "approval-workflow", - safe_posture=_safe_posture_for_command(command_hint, default="approval-review"), + safe_posture=_safe_posture_for_command( + command_hint, default="approval-review" + ), command_hint=command_hint, ) ) return evidence_items -def _repo_evidence_items(items: list[dict[str, Any]], *, label_prefix: str | None = None) -> list[dict[str, Any]]: +def _repo_evidence_items( + items: list[dict[str, Any]], *, label_prefix: str | None = None +) -> list[WeeklyStoryEvidenceItem]: return [ _build_story_evidence_item( - f"{label_prefix}: {item.get('repo') or 'Repo'}" if label_prefix else str(item.get("repo") or "Repo"), - str(item.get("summary") or "No historical intelligence summary is recorded yet."), + f"{label_prefix}: {item.get('repo') or 'Repo'}" + if label_prefix + else str(item.get("repo") or "Repo"), + str( + item.get("summary") + or "No historical intelligence summary is recorded yet." + ), "historical-portfolio-intelligence", ) for item in items[:3] ] -def _determine_section_state(weekly_pack: dict[str, Any], options: list[tuple[str, str]]) -> str: +def _determine_section_state( + weekly_pack: dict[str, Any], options: list[tuple[str, str]] +) -> str: for key, state in options: if weekly_pack.get(key): return state return "idle" -def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: - weekly_priority_evidence_items = list(weekly_pack.get("weekly_priority_evidence_items") or []) +def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> WeeklyStoryV1: + weekly_priority_evidence_items = list( + weekly_pack.get("weekly_priority_evidence_items") or [] + ) if not weekly_priority_evidence_items: weekly_priority_evidence_items = [ _build_story_evidence_item( "Trust / Actionability", - str(weekly_pack.get("trust_actionability_summary") or "No trust summary is recorded yet."), + str( + weekly_pack.get("trust_actionability_summary") + or "No trust summary is recorded yet." + ), "weekly-priority", ), _build_story_evidence_item( "Operator Focus", - str(weekly_pack.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), + str( + weekly_pack.get("operator_focus_summary") + or NO_OPERATOR_FOCUS_SUMMARY + ), "operator-focus", ), _build_story_evidence_item( "Operator Outcomes", - str(weekly_pack.get("operator_outcomes_summary") or NO_OPERATOR_OUTCOMES_SUMMARY), + str( + weekly_pack.get("operator_outcomes_summary") + or NO_OPERATOR_OUTCOMES_SUMMARY + ), "operator-outcomes", ), ] - sections = [ + sections: list[WeeklyStorySection] = [ { "id": "weekly-priority", "label": "Weekly Priority", @@ -274,7 +300,10 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: or "Continue the normal operator review loop." ), "next_label": "Decision", - "reason_codes": list(weekly_pack.get("weekly_priority_reason_codes") or ["queue-pressure", "operator-priority"]), + "reason_codes": list( + weekly_pack.get("weekly_priority_reason_codes") + or ["queue-pressure", "operator-priority"] + ), "evidence_items": weekly_priority_evidence_items, }, { @@ -289,8 +318,12 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_preview_ready_campaigns", "preview-ready"), ], ), - "headline": str(weekly_pack.get("action_sync_summary") or NO_ACTION_SYNC_SUMMARY), - "next_step": str(weekly_pack.get("next_action_sync_step") or NO_ACTION_SYNC_STEP), + "headline": str( + weekly_pack.get("action_sync_summary") or NO_ACTION_SYNC_SUMMARY + ), + "next_step": str( + weekly_pack.get("next_action_sync_step") or NO_ACTION_SYNC_STEP + ), "next_label": "Next Step", "reason_codes": ["action-sync", "readiness"], "evidence_items": ( @@ -299,14 +332,18 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: summary_key="reason", kind="action-sync-readiness", label_prefix="Apply Ready", - extra_formatter=lambda item, summary: f"{summary} (target {item.get('recommended_target', 'none')})", + extra_formatter=lambda item, summary: ( + f"{summary} (target {item.get('recommended_target', 'none')})" + ), ) + _campaign_evidence_items( list(weekly_pack.get("top_preview_ready_campaigns") or []), summary_key="reason", kind="action-sync-readiness", label_prefix="Preview Ready", - extra_formatter=lambda item, summary: f"{summary} (target {item.get('recommended_target', 'none')})", + extra_formatter=lambda item, summary: ( + f"{summary} (target {item.get('recommended_target', 'none')})" + ), ) + _campaign_evidence_items( list(weekly_pack.get("top_drift_review_campaigns") or []), @@ -333,8 +370,12 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_ready_to_apply_packets", "ready-to-apply"), ], ), - "headline": str(weekly_pack.get("apply_readiness_summary") or NO_APPLY_READINESS_SUMMARY), - "next_step": str(weekly_pack.get("next_apply_candidate") or NO_NEXT_APPLY_CANDIDATE), + "headline": str( + weekly_pack.get("apply_readiness_summary") or NO_APPLY_READINESS_SUMMARY + ), + "next_step": str( + weekly_pack.get("next_apply_candidate") or NO_NEXT_APPLY_CANDIDATE + ), "next_label": "Next Candidate", "reason_codes": ["action-sync", "apply-packet"], "evidence_items": ( @@ -373,8 +414,13 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_holding_clean_campaigns", "holding-clean"), ], ), - "headline": str(weekly_pack.get("campaign_outcomes_summary") or NO_CAMPAIGN_OUTCOMES_SUMMARY), - "next_step": str(weekly_pack.get("next_monitoring_step") or NO_NEXT_MONITORING_STEP), + "headline": str( + weekly_pack.get("campaign_outcomes_summary") + or NO_CAMPAIGN_OUTCOMES_SUMMARY + ), + "next_step": str( + weekly_pack.get("next_monitoring_step") or NO_NEXT_MONITORING_STEP + ), "next_label": "Next Step", "reason_codes": ["action-sync", "post-apply-monitoring"], "evidence_items": ( @@ -414,9 +460,13 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_thin_evidence_campaigns", "thin-evidence"), ], ), - "headline": str(weekly_pack.get("campaign_tuning_summary") or NO_CAMPAIGN_TUNING_SUMMARY), + "headline": str( + weekly_pack.get("campaign_tuning_summary") or NO_CAMPAIGN_TUNING_SUMMARY + ), "next_step": str( - weekly_pack.get("next_tie_break_candidate") or weekly_pack.get("next_tuned_campaign") or NO_NEXT_TUNED_CAMPAIGN + weekly_pack.get("next_tie_break_candidate") + or weekly_pack.get("next_tuned_campaign") + or NO_NEXT_TUNED_CAMPAIGN ), "next_label": ACTION_SYNC_CANONICAL_LABELS["next_tie_break_candidate"], "reason_codes": ["action-sync", "campaign-tuning"], @@ -453,12 +503,20 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_holding_repos", "holding-steady"), ], ), - "headline": str(weekly_pack.get("historical_portfolio_intelligence") or NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY), - "next_step": str(weekly_pack.get("next_historical_focus") or NO_NEXT_HISTORICAL_FOCUS), + "headline": str( + weekly_pack.get("historical_portfolio_intelligence") + or NO_HISTORICAL_PORTFOLIO_INTELLIGENCE_SUMMARY + ), + "next_step": str( + weekly_pack.get("next_historical_focus") or NO_NEXT_HISTORICAL_FOCUS + ), "next_label": "Next Focus", "reason_codes": ["historical-intelligence", "portfolio"], "evidence_items": ( - _repo_evidence_items(list(weekly_pack.get("top_relapsing_repos") or []), label_prefix="Relapsing") + _repo_evidence_items( + list(weekly_pack.get("top_relapsing_repos") or []), + label_prefix="Relapsing", + ) + _repo_evidence_items( list(weekly_pack.get("top_persistent_pressure_repos") or []), label_prefix="Persistent Pressure", @@ -467,7 +525,10 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: list(weekly_pack.get("top_improving_repos") or []), label_prefix="Improving After Intervention", ) - + _repo_evidence_items(list(weekly_pack.get("top_holding_repos") or []), label_prefix="Holding Steady") + + _repo_evidence_items( + list(weekly_pack.get("top_holding_repos") or []), + label_prefix="Holding Steady", + ) ), }, { @@ -483,8 +544,14 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_manual_only_campaigns", "manual-only"), ], ), - "headline": str(weekly_pack.get("automation_guidance_summary") or NO_AUTOMATION_GUIDANCE_SUMMARY), - "next_step": str(weekly_pack.get("next_safe_automation_step") or NO_NEXT_SAFE_AUTOMATION_STEP), + "headline": str( + weekly_pack.get("automation_guidance_summary") + or NO_AUTOMATION_GUIDANCE_SUMMARY + ), + "next_step": str( + weekly_pack.get("next_safe_automation_step") + or NO_NEXT_SAFE_AUTOMATION_STEP + ), "next_label": "Next Step", "reason_codes": ["automation-guidance", "safe-posture"], "evidence_items": ( @@ -539,8 +606,13 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_blocked_approvals", "blocked"), ], ), - "headline": str(weekly_pack.get("approval_workflow_summary") or NO_APPROVAL_WORKFLOW_SUMMARY), - "next_step": str(weekly_pack.get("next_approval_review") or NO_NEXT_APPROVAL_REVIEW), + "headline": str( + weekly_pack.get("approval_workflow_summary") + or NO_APPROVAL_WORKFLOW_SUMMARY + ), + "next_step": str( + weekly_pack.get("next_approval_review") or NO_NEXT_APPROVAL_REVIEW + ), "next_label": ACTION_SYNC_CANONICAL_LABELS["next_approval_review"], "reason_codes": ["approval-workflow", "local-only"], "evidence_items": ( @@ -564,7 +636,10 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: list(weekly_pack.get("top_approved_manual_approvals") or []), label_prefix="Approved But Manual", ) - + _approval_evidence_items(list(weekly_pack.get("top_blocked_approvals") or []), label_prefix="Blocked") + + _approval_evidence_items( + list(weekly_pack.get("top_blocked_approvals") or []), + label_prefix="Blocked", + ) ), }, { @@ -580,15 +655,23 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: ("top_revalidate_items", "revalidate"), ], ), - "headline": str(weekly_pack.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), - "next_step": str(weekly_pack.get("follow_through_checkpoint_summary") or NO_FOLLOW_THROUGH_CHECKPOINT), + "headline": str( + weekly_pack.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY + ), + "next_step": str( + weekly_pack.get("follow_through_checkpoint_summary") + or NO_FOLLOW_THROUGH_CHECKPOINT + ), "next_label": "Next Checkpoint", "reason_codes": ["operator-focus", "follow-through"], "evidence_items": ( [ _build_story_evidence_item( str(item.get("repo") or item.get("title") or "Operator item"), - str(item.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), + str( + item.get("operator_focus_summary") + or NO_OPERATOR_FOCUS_SUMMARY + ), "operator-focus", ) for item in list(weekly_pack.get("top_act_now_items") or [])[:3] @@ -596,15 +679,23 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: + [ _build_story_evidence_item( str(item.get("repo") or item.get("title") or "Operator item"), - str(item.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), + str( + item.get("operator_focus_summary") + or NO_OPERATOR_FOCUS_SUMMARY + ), "operator-focus", ) - for item in list(weekly_pack.get("top_watch_closely_items") or [])[:3] + for item in list(weekly_pack.get("top_watch_closely_items") or [])[ + :3 + ] ] + [ _build_story_evidence_item( str(item.get("repo") or item.get("title") or "Operator item"), - str(item.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), + str( + item.get("operator_focus_summary") + or NO_OPERATOR_FOCUS_SUMMARY + ), "operator-focus", ) for item in list(weekly_pack.get("top_improving_items") or [])[:3] @@ -612,7 +703,10 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: + [ _build_story_evidence_item( str(item.get("repo") or item.get("title") or "Operator item"), - str(item.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), + str( + item.get("operator_focus_summary") + or NO_OPERATOR_FOCUS_SUMMARY + ), "operator-focus", ) for item in list(weekly_pack.get("top_fragile_items") or [])[:3] @@ -620,7 +714,10 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: + [ _build_story_evidence_item( str(item.get("repo") or item.get("title") or "Operator item"), - str(item.get("operator_focus_summary") or NO_OPERATOR_FOCUS_SUMMARY), + str( + item.get("operator_focus_summary") + or NO_OPERATOR_FOCUS_SUMMARY + ), "operator-focus", ) for item in list(weekly_pack.get("top_revalidate_items") or [])[:3] @@ -631,9 +728,18 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: return { "version": 1, - "headline": str(weekly_pack.get("portfolio_headline") or "No weekly headline is recorded yet."), - "decision": str(weekly_pack.get("what_to_do_this_week") or "Continue the normal operator review loop."), - "why_this_week": str(weekly_pack.get("queue_pressure_summary") or "No queue-pressure summary is recorded yet."), + "headline": str( + weekly_pack.get("portfolio_headline") + or "No weekly headline is recorded yet." + ), + "decision": str( + weekly_pack.get("what_to_do_this_week") + or "Continue the normal operator review loop." + ), + "why_this_week": str( + weekly_pack.get("queue_pressure_summary") + or "No queue-pressure summary is recorded yet." + ), "next_step": str( weekly_pack.get("next_best_workflow_step") or "Open the standard workbook first, then use --control-center for read-only triage." @@ -646,10 +752,12 @@ def _build_weekly_story_v1(weekly_pack: dict[str, Any]) -> dict[str, Any]: def finalize_weekly_pack(weekly_pack: dict[str, Any]) -> dict[str, Any]: finalized = dict(weekly_pack) finalized["top_attention"] = [ - _build_attention_explainability(item) for item in list(finalized.get("top_attention") or []) + _build_attention_explainability(item) + for item in list(finalized.get("top_attention") or []) ] finalized["repo_briefings"] = [ - _build_repo_briefing_explainability(item) for item in list(finalized.get("repo_briefings") or []) + _build_repo_briefing_explainability(item) + for item in list(finalized.get("repo_briefings") or []) ] finalized["weekly_story_v1"] = _build_weekly_story_v1(finalized) return finalized diff --git a/tests/golden/composer_contract.golden.json b/tests/golden/composer_contract.golden.json index 0772bbe..d67df54 100644 --- a/tests/golden/composer_contract.golden.json +++ b/tests/golden/composer_contract.golden.json @@ -1,74 +1,74 @@ { "closure_forecast_reset_reentry_freshness_for_target": { "clamp-divergence": { - "closure_forecast_reset_reentry_freshness_reason": "stale:1.8:0.0", - "closure_forecast_reset_reentry_freshness_status": "stale", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, "decayed_reset_reentered_clearance_rate": 0.0, - "decayed_reset_reentered_confirmation_rate": 1.0, + "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "confirmation-leaning", - "recent_reset_reentry_signal_path": "confirmation -> confirmation" + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_signal_path": "" }, "clearance-hold": { - "closure_forecast_reset_reentry_freshness_reason": "stale:1.8:0.0", - "closure_forecast_reset_reentry_freshness_status": "stale", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, - "decayed_reset_reentered_clearance_rate": 1.0, + "decayed_reset_reentered_clearance_rate": 0.0, "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "clearance-leaning", - "recent_reset_reentry_signal_path": "clearance -> clearance" + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_signal_path": "" }, "empty": { - "closure_forecast_reset_reentry_freshness_reason": "insufficient-data:0.0:0.0", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, "decayed_reset_reentered_clearance_rate": 0.0, "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "balanced", + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", "recent_reset_reentry_signal_path": "" }, "reversing": { - "closure_forecast_reset_reentry_freshness_reason": "stale:1.8:0.0", - "closure_forecast_reset_reentry_freshness_status": "stale", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, "decayed_reset_reentered_clearance_rate": 0.0, - "decayed_reset_reentered_confirmation_rate": 1.0, + "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "confirmation-leaning", - "recent_reset_reentry_signal_path": "confirmation -> confirmation" + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_signal_path": "" }, "single-event": { - "closure_forecast_reset_reentry_freshness_reason": "stale:1.0:0.0", - "closure_forecast_reset_reentry_freshness_status": "stale", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, "decayed_reset_reentered_clearance_rate": 0.0, - "decayed_reset_reentered_confirmation_rate": 1.0, + "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "confirmation-leaning", - "recent_reset_reentry_signal_path": "confirmation" + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_signal_path": "" }, "sparse": { - "closure_forecast_reset_reentry_freshness_reason": "stale:1.8:0.0", - "closure_forecast_reset_reentry_freshness_status": "stale", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, "decayed_reset_reentered_clearance_rate": 0.0, - "decayed_reset_reentered_confirmation_rate": 1.0, + "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "confirmation-leaning", - "recent_reset_reentry_signal_path": "confirmation -> confirmation" + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_signal_path": "" }, "sustained-confirmation": { - "closure_forecast_reset_reentry_freshness_reason": "stale:2.4:0.0", - "closure_forecast_reset_reentry_freshness_status": "stale", + "closure_forecast_reset_reentry_freshness_reason": "Reset re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted reset re-entry run(s), 0% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_memory_weight": 0.0, "decayed_reset_reentered_clearance_rate": 0.0, - "decayed_reset_reentered_confirmation_rate": 1.0, + "decayed_reset_reentered_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_signal_mix": "confirmation-leaning", - "recent_reset_reentry_signal_path": "confirmation -> confirmation -> confirmation" + "recent_reset_reentry_signal_mix": "0.00 weighted reset re-entry run(s) with 0.00 confirmation-like, 0.00 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_signal_path": "" } }, "closure_forecast_reset_reentry_freshness_hotspots": { @@ -87,46 +87,46 @@ }, "closure_forecast_reset_reentry_rebuild_churn_for_target": { "clamp-divergence": { + "closure_forecast_reset_reentry_rebuild_churn_reason": "", + "closure_forecast_reset_reentry_rebuild_churn_score": 0.1, + "closure_forecast_reset_reentry_rebuild_churn_status": "none", + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilding-confirmation-reentry" + }, + "clearance-hold": { "closure_forecast_reset_reentry_rebuild_churn_reason": "Rebuilt reset re-entry is wobbling and may lose its restored strength soon.", "closure_forecast_reset_reentry_rebuild_churn_score": 0.2, "closure_forecast_reset_reentry_rebuild_churn_status": "watch", - "recent_reset_reentry_rebuild_churn_path": "strong-conf -> decrement-conf" - }, - "clearance-hold": { - "closure_forecast_reset_reentry_rebuild_churn_reason": "", - "closure_forecast_reset_reentry_rebuild_churn_score": 0.0, - "closure_forecast_reset_reentry_rebuild_churn_status": "none", - "recent_reset_reentry_rebuild_churn_path": "sustained-clearance -> sustained-clearance" + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> rebuilt-clearance-reentry -> rebuilt-clearance-reentry" }, "empty": { "closure_forecast_reset_reentry_rebuild_churn_reason": "", "closure_forecast_reset_reentry_rebuild_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_churn_status": "none", - "recent_reset_reentry_rebuild_churn_path": "" + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry" }, "reversing": { - "closure_forecast_reset_reentry_rebuild_churn_reason": "Local target instability is preventing positive confirmation-side rebuild persistence.", + "closure_forecast_reset_reentry_rebuild_churn_reason": "", "closure_forecast_reset_reentry_rebuild_churn_score": 0.0, - "closure_forecast_reset_reentry_rebuild_churn_status": "blocked", - "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> strong-conf" + "closure_forecast_reset_reentry_rebuild_churn_status": "none", + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry" }, "single-event": { "closure_forecast_reset_reentry_rebuild_churn_reason": "", "closure_forecast_reset_reentry_rebuild_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_churn_status": "none", - "recent_reset_reentry_rebuild_churn_path": "strong-conf" + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry" }, "sparse": { - "closure_forecast_reset_reentry_rebuild_churn_reason": "Rebuilt reset re-entry is wobbling and may lose its restored strength soon.", - "closure_forecast_reset_reentry_rebuild_churn_score": 0.2, - "closure_forecast_reset_reentry_rebuild_churn_status": "watch", - "recent_reset_reentry_rebuild_churn_path": "sparse-none -> strong-conf -> decrement-conf" + "closure_forecast_reset_reentry_rebuild_churn_reason": "", + "closure_forecast_reset_reentry_rebuild_churn_score": 0.1, + "closure_forecast_reset_reentry_rebuild_churn_status": "none", + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> hold -> rebuilt-confirmation-reentry -> rebuilding-confirmation-reentry" }, "sustained-confirmation": { "closure_forecast_reset_reentry_rebuild_churn_reason": "", "closure_forecast_reset_reentry_rebuild_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_churn_status": "none", - "recent_reset_reentry_rebuild_churn_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_churn_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry" } }, "closure_forecast_reset_reentry_rebuild_churn_summary": { @@ -134,8 +134,8 @@ }, "closure_forecast_reset_reentry_rebuild_freshness_for_target": { "clamp-divergence": { - "closure_forecast_reset_reentry_rebuild_freshness_reason": "Recent rebuilt reset re-entry evidence is still current enough to keep the restored posture trusted, with 100% of the weighted signal coming from the latest 4 runs.", - "closure_forecast_reset_reentry_rebuild_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_freshness_reason": "Rebuilt reset re-entry memory is still too lightly exercised to judge freshness, with 1.00 weighted rebuilt run(s), 100% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_rebuild_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_rebuild_memory_weight": 1.0, "decayed_rebuilt_clearance_reentry_rate": 0.0, "decayed_rebuilt_confirmation_reentry_rate": 1.0, @@ -150,7 +150,7 @@ "decayed_rebuilt_clearance_reentry_rate": 1.0, "decayed_rebuilt_confirmation_reentry_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_rebuild_signal_mix": "1.80 weighted rebuilt run(s) with 0.00 confirmation-like, 1.80 clearance-like, and 0% of the signal from the freshest runs.", + "recent_reset_reentry_rebuild_signal_mix": "2.00 weighted rebuilt run(s) with 0.00 confirmation-like, 2.00 clearance-like, and 0% of the signal from the freshest runs.", "recent_reset_reentry_rebuild_signal_path": "clearance-like -> clearance-like" }, "empty": { @@ -170,12 +170,12 @@ "decayed_rebuilt_clearance_reentry_rate": 0.0, "decayed_rebuilt_confirmation_reentry_rate": 1.0, "has_fresh_aligned_recent_evidence": true, - "recent_reset_reentry_rebuild_signal_mix": "1.80 weighted rebuilt run(s) with 1.80 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs.", + "recent_reset_reentry_rebuild_signal_mix": "2.00 weighted rebuilt run(s) with 2.00 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs.", "recent_reset_reentry_rebuild_signal_path": "confirmation-like -> confirmation-like" }, "single-event": { - "closure_forecast_reset_reentry_rebuild_freshness_reason": "Recent rebuilt reset re-entry evidence is still current enough to keep the restored posture trusted, with 100% of the weighted signal coming from the latest 4 runs.", - "closure_forecast_reset_reentry_rebuild_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_freshness_reason": "Rebuilt reset re-entry memory is still too lightly exercised to judge freshness, with 1.00 weighted rebuilt run(s), 100% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_rebuild_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_rebuild_memory_weight": 1.0, "decayed_rebuilt_clearance_reentry_rate": 0.0, "decayed_rebuilt_confirmation_reentry_rate": 1.0, @@ -184,8 +184,8 @@ "recent_reset_reentry_rebuild_signal_path": "confirmation-like" }, "sparse": { - "closure_forecast_reset_reentry_rebuild_freshness_reason": "Recent rebuilt reset re-entry evidence is still current enough to keep the restored posture trusted, with 100% of the weighted signal coming from the latest 4 runs.", - "closure_forecast_reset_reentry_rebuild_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_freshness_reason": "Rebuilt reset re-entry memory is still too lightly exercised to judge freshness, with 1.00 weighted rebuilt run(s), 100% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_rebuild_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_rebuild_memory_weight": 1.0, "decayed_rebuilt_clearance_reentry_rate": 0.0, "decayed_rebuilt_confirmation_reentry_rate": 1.0, @@ -200,7 +200,7 @@ "decayed_rebuilt_clearance_reentry_rate": 0.0, "decayed_rebuilt_confirmation_reentry_rate": 1.0, "has_fresh_aligned_recent_evidence": true, - "recent_reset_reentry_rebuild_signal_mix": "2.40 weighted rebuilt run(s) with 2.40 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs.", + "recent_reset_reentry_rebuild_signal_mix": "2.70 weighted rebuilt run(s) with 2.70 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs.", "recent_reset_reentry_rebuild_signal_path": "confirmation-like -> confirmation-like -> confirmation-like" } }, @@ -339,53 +339,53 @@ }, "closure_forecast_reset_reentry_rebuild_persistence_for_target": { "clamp-divergence": { - "closure_forecast_reset_reentry_rebuild_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_persistence_reason": "Confirmation-side rebuild has stayed aligned long enough to keep the restored forecast in place.", - "closure_forecast_reset_reentry_rebuild_persistence_score": 0.31, - "closure_forecast_reset_reentry_rebuild_persistence_status": "holding-confirmation-rebuild", - "recent_reset_reentry_rebuild_persistence_path": "strong-conf -> decrement-conf" + "closure_forecast_reset_reentry_rebuild_age_runs": 3, + "closure_forecast_reset_reentry_rebuild_persistence_reason": "Confirmation-side rebuild is now holding with enough follow-through to trust the restored forecast more.", + "closure_forecast_reset_reentry_rebuild_persistence_score": 0.37, + "closure_forecast_reset_reentry_rebuild_persistence_status": "sustained-confirmation-rebuild", + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilding-confirmation-reentry" }, "clearance-hold": { - "closure_forecast_reset_reentry_rebuild_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_persistence_reason": "Clearance-side rebuild has stayed aligned long enough to keep the restored caution in place.", - "closure_forecast_reset_reentry_rebuild_persistence_score": -0.55, - "closure_forecast_reset_reentry_rebuild_persistence_status": "holding-clearance-rebuild", - "recent_reset_reentry_rebuild_persistence_path": "sustained-clearance -> sustained-clearance" + "closure_forecast_reset_reentry_rebuild_age_runs": 1, + "closure_forecast_reset_reentry_rebuild_persistence_reason": "Stronger reset re-entry posture has been rebuilt, but it has not yet proved it can hold.", + "closure_forecast_reset_reentry_rebuild_persistence_score": -0.17, + "closure_forecast_reset_reentry_rebuild_persistence_status": "just-rebuilt", + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> rebuilt-clearance-reentry -> rebuilt-clearance-reentry" }, "empty": { - "closure_forecast_reset_reentry_rebuild_age_runs": 0, - "closure_forecast_reset_reentry_rebuild_persistence_reason": "", - "closure_forecast_reset_reentry_rebuild_persistence_score": 0.0, - "closure_forecast_reset_reentry_rebuild_persistence_status": "none", - "recent_reset_reentry_rebuild_persistence_path": "" + "closure_forecast_reset_reentry_rebuild_age_runs": 1, + "closure_forecast_reset_reentry_rebuild_persistence_reason": "Stronger reset re-entry posture has been rebuilt, but it has not yet proved it can hold.", + "closure_forecast_reset_reentry_rebuild_persistence_score": 0.45, + "closure_forecast_reset_reentry_rebuild_persistence_status": "just-rebuilt", + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry" }, "reversing": { - "closure_forecast_reset_reentry_rebuild_age_runs": 2, + "closure_forecast_reset_reentry_rebuild_age_runs": 3, "closure_forecast_reset_reentry_rebuild_persistence_reason": "The rebuilt posture is already weakening, so it is being softened again.", - "closure_forecast_reset_reentry_rebuild_persistence_score": 0.27, + "closure_forecast_reset_reentry_rebuild_persistence_score": 0.24, "closure_forecast_reset_reentry_rebuild_persistence_status": "reversing", - "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> strong-conf" + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry" }, "single-event": { + "closure_forecast_reset_reentry_rebuild_age_runs": 2, + "closure_forecast_reset_reentry_rebuild_persistence_reason": "Confirmation-side rebuild has stayed aligned long enough to keep the restored forecast in place.", + "closure_forecast_reset_reentry_rebuild_persistence_score": 0.49, + "closure_forecast_reset_reentry_rebuild_persistence_status": "holding-confirmation-rebuild", + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry" + }, + "sparse": { "closure_forecast_reset_reentry_rebuild_age_runs": 1, "closure_forecast_reset_reentry_rebuild_persistence_reason": "Stronger reset re-entry posture has been rebuilt, but it has not yet proved it can hold.", - "closure_forecast_reset_reentry_rebuild_persistence_score": 0.55, + "closure_forecast_reset_reentry_rebuild_persistence_score": 0.37, "closure_forecast_reset_reentry_rebuild_persistence_status": "just-rebuilt", - "recent_reset_reentry_rebuild_persistence_path": "strong-conf" - }, - "sparse": { - "closure_forecast_reset_reentry_rebuild_age_runs": 0, - "closure_forecast_reset_reentry_rebuild_persistence_reason": "", - "closure_forecast_reset_reentry_rebuild_persistence_score": 0.31, - "closure_forecast_reset_reentry_rebuild_persistence_status": "none", - "recent_reset_reentry_rebuild_persistence_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> hold -> rebuilt-confirmation-reentry -> rebuilding-confirmation-reentry" }, "sustained-confirmation": { - "closure_forecast_reset_reentry_rebuild_age_runs": 3, + "closure_forecast_reset_reentry_rebuild_age_runs": 4, "closure_forecast_reset_reentry_rebuild_persistence_reason": "Confirmation-side rebuild is now holding with enough follow-through to trust the restored forecast more.", - "closure_forecast_reset_reentry_rebuild_persistence_score": 0.55, + "closure_forecast_reset_reentry_rebuild_persistence_score": 0.51, "closure_forecast_reset_reentry_rebuild_persistence_status": "sustained-confirmation-rebuild", - "recent_reset_reentry_rebuild_persistence_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_persistence_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry" } }, "closure_forecast_reset_reentry_rebuild_persistence_summary": { @@ -410,7 +410,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold -> hold -> hold" }, "clearance-hold": { "aligned_fresh_runs_after_latest_rebuild_reentry_reset": 0, @@ -419,7 +419,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "sustained-clearance -> sustained-clearance" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold -> hold -> hold" }, "empty": { "aligned_fresh_runs_after_latest_rebuild_reentry_reset": 0, @@ -428,7 +428,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold" }, "reversing": { "aligned_fresh_runs_after_latest_rebuild_reentry_reset": 0, @@ -437,7 +437,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "rebuilt-confirmation-reentry -> strong-conf" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold -> hold -> hold" }, "single-event": { "aligned_fresh_runs_after_latest_rebuild_reentry_reset": 0, @@ -446,7 +446,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "strong-conf" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold -> hold" }, "sparse": { "aligned_fresh_runs_after_latest_rebuild_reentry_reset": 0, @@ -455,7 +455,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold -> hold -> hold -> hold" }, "sustained-confirmation": { "aligned_fresh_runs_after_latest_rebuild_reentry_reset": 0, @@ -464,7 +464,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_status": "none", "recent_rebuild_reentry_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_refresh_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_reentry_refresh_path": "hold -> hold -> hold -> hold" } }, "closure_forecast_reset_reentry_rebuild_reentry_refresh_recovery_summary": { @@ -475,43 +475,43 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold -> hold -> hold" }, "clearance-hold": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "sustained-clearance -> sustained-clearance" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold -> hold -> hold" }, "empty": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold" }, "reversing": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "Local target instability is preventing positive confirmation-side re-re-re-restored hold.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.1, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "blocked", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "rebuilt-confirmation-reentry -> strong-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold -> hold -> hold" }, "single-event": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold -> hold" }, "sparse": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold -> hold -> hold -> hold" }, "sustained-confirmation": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_churn_path": "hold -> hold -> hold -> hold" } }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_summary": { @@ -614,53 +614,53 @@ }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target": { "clamp-divergence": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "Confirmation-side re-re-re-restored posture has stayed aligned long enough to keep the stronger rerestored forecast in place.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.11, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "holding-confirmation-rebuild-reentry-rerererestore", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "strong-conf -> decrement-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold -> hold -> hold" }, "clearance-hold": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "Clearance-side re-re-re-restored posture has stayed aligned long enough to keep the stronger rerestored caution in place.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": -0.2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "holding-clearance-rebuild-reentry-rerererestore", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "sustained-clearance -> sustained-clearance" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold -> hold -> hold" }, "empty": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold" }, "reversing": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "The re-re-re-restored rebuilt re-entry posture is already weakening, so it is being softened again.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.09, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "reversing", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "rebuilt-confirmation-reentry -> strong-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold -> hold -> hold" }, "single-event": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 1, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "Re-re-re-restored rebuilt re-entry is still too lightly exercised to say whether the stronger posture can hold.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "insufficient-data", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "strong-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold -> hold" }, "sparse": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.11, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold -> hold -> hold -> hold" }, "sustained-confirmation": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 3, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "Confirmation-side re-re-re-restored posture has stayed aligned long enough to keep the stronger rerestored forecast in place.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "holding-confirmation-rebuild-reentry-rerererestore", - "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "strong-conf -> strong-conf -> strong-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_age_runs": 0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_score": 0.0, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path": "hold -> hold -> hold -> hold" } }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary": { @@ -674,43 +674,43 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "Re-re-restored rebuilt re-entry is wobbling and may lose its stronger posture soon.", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.2, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "watch", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestoring-confirmation-rebuild-reentry" }, "clearance-hold": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.0, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "sustained-clearance -> sustained-clearance" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "Re-re-restored rebuilt re-entry is wobbling and may lose its stronger posture soon.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.2, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "watch", + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry -> rererestored-clearance-rebuild-reentry -> rererestored-clearance-rebuild-reentry" }, "empty": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry" }, "reversing": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "Local target instability is preventing positive confirmation-side re-re-restored hold.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.0, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "blocked", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rebuilt-confirmation-reentry -> strong-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.1, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "none", + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" }, "single-event": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" }, "sparse": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "Re-re-restored rebuilt re-entry is wobbling and may lose its stronger posture soon.", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.2, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "watch", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry -> hold -> rererestored-confirmation-rebuild-reentry -> rererestoring-confirmation-rebuild-reentry" }, "sustained-confirmation": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_reason": "", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_churn_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" } }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary": { @@ -718,8 +718,8 @@ }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target": { "clamp-divergence": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Recent re-re-restored rebuilt re-entry evidence is still current enough to keep the stronger re-re-restored posture trusted, with 100% of the weighted signal coming from the latest 4 runs.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Re-re-restored rebuilt re-entry memory is still too lightly exercised to judge freshness, with 1.00 weighted re-re-restored run(s), 100% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_memory_weight": 1.0, "decayed_rererestored_rebuild_reentry_clearance_rate": 0.0, "decayed_rererestored_rebuild_reentry_confirmation_rate": 1.0, @@ -733,7 +733,7 @@ "decayed_rererestored_rebuild_reentry_clearance_rate": 1.0, "decayed_rererestored_rebuild_reentry_confirmation_rate": 0.0, "has_fresh_aligned_recent_evidence": false, - "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "1.80 weighted re-re-restored run(s) with 0.00 confirmation-like, 1.80 clearance-like, and 0% of the signal from the freshest runs." + "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "2.00 weighted re-re-restored run(s) with 0.00 confirmation-like, 2.00 clearance-like, and 0% of the signal from the freshest runs." }, "empty": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Re-re-restored rebuilt re-entry memory is still too lightly exercised to judge freshness, with 0.00 weighted re-re-restored run(s), 0% confirmation-like signal, and 0% clearance-like signal.", @@ -751,11 +751,11 @@ "decayed_rererestored_rebuild_reentry_clearance_rate": 0.0, "decayed_rererestored_rebuild_reentry_confirmation_rate": 1.0, "has_fresh_aligned_recent_evidence": true, - "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "1.80 weighted re-re-restored run(s) with 1.80 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs." + "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "2.00 weighted re-re-restored run(s) with 2.00 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs." }, "single-event": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Recent re-re-restored rebuilt re-entry evidence is still current enough to keep the stronger re-re-restored posture trusted, with 100% of the weighted signal coming from the latest 4 runs.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Re-re-restored rebuilt re-entry memory is still too lightly exercised to judge freshness, with 1.00 weighted re-re-restored run(s), 100% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_memory_weight": 1.0, "decayed_rererestored_rebuild_reentry_clearance_rate": 0.0, "decayed_rererestored_rebuild_reentry_confirmation_rate": 1.0, @@ -763,8 +763,8 @@ "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "1.00 weighted re-re-restored run(s) with 1.00 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs." }, "sparse": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Recent re-re-restored rebuilt re-entry evidence is still current enough to keep the stronger re-re-restored posture trusted, with 100% of the weighted signal coming from the latest 4 runs.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reason": "Re-re-restored rebuilt re-entry memory is still too lightly exercised to judge freshness, with 1.00 weighted re-re-restored run(s), 100% confirmation-like signal, and 0% clearance-like signal.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "insufficient-data", "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_memory_weight": 1.0, "decayed_rererestored_rebuild_reentry_clearance_rate": 0.0, "decayed_rererestored_rebuild_reentry_confirmation_rate": 1.0, @@ -778,7 +778,7 @@ "decayed_rererestored_rebuild_reentry_clearance_rate": 0.0, "decayed_rererestored_rebuild_reentry_confirmation_rate": 1.0, "has_fresh_aligned_recent_evidence": true, - "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "2.40 weighted re-re-restored run(s) with 2.40 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs." + "recent_reset_reentry_rebuild_reentry_restore_rererestore_signal_mix": "2.70 weighted re-re-restored run(s) with 2.70 confirmation-like, 0.00 clearance-like, and 100% of the signal from the freshest runs." } }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots": { @@ -892,53 +892,53 @@ }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target": { "clamp-divergence": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Confirmation-side re-re-restored posture has stayed aligned long enough to keep the stronger rerestored forecast in place.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.31, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "holding-confirmation-rebuild-reentry-rererestore", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "strong-conf -> decrement-conf" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 3, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Confirmation-side re-re-restored posture is now holding with enough follow-through to trust the stronger rerestored forecast more.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.33, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "sustained-confirmation-rebuild-reentry-rererestore", + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestoring-confirmation-rebuild-reentry" }, "clearance-hold": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Clearance-side re-re-restored posture has stayed aligned long enough to keep the stronger rerestored caution in place.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": -0.55, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "holding-clearance-rebuild-reentry-rererestore", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "sustained-clearance -> sustained-clearance" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 1, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Stronger rerestored rebuilt re-entry posture has been re-re-restored, but it has not yet proved it can hold.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": -0.22, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "just-rererestored", + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry -> rererestored-clearance-rebuild-reentry -> rererestored-clearance-rebuild-reentry" }, "empty": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 0, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.0, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "" + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 1, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Stronger rerestored rebuilt re-entry posture has been re-re-restored, but it has not yet proved it can hold.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.35, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "just-rererestored", + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry" }, "reversing": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 2, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 3, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "The re-re-restored rebuilt re-entry posture is already weakening, so it is being softened again.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.27, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.2, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "reversing", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rebuilt-confirmation-reentry -> strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" }, "single-event": { + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 2, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Confirmation-side re-re-restored posture has stayed aligned long enough to keep the stronger rerestored forecast in place.", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.44, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "holding-confirmation-rebuild-reentry-rererestore", + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" + }, + "sparse": { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 1, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Stronger rerestored rebuilt re-entry posture has been re-re-restored, but it has not yet proved it can hold.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.55, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.33, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "just-rererestored", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "strong-conf" - }, - "sparse": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 0, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.31, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry -> hold -> rererestored-confirmation-rebuild-reentry -> rererestoring-confirmation-rebuild-reentry" }, "sustained-confirmation": { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 3, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 4, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": "Confirmation-side re-re-restored posture is now holding with enough follow-through to trust the stronger rerestored forecast more.", - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.55, + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.48, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": "sustained-confirmation-rebuild-reentry-rererestore", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" } }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary": { @@ -963,7 +963,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> hold" }, "clearance-hold": { "aligned_fresh_runs_after_latest_rererestore_reset": 0, @@ -972,7 +972,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "sustained-clearance -> sustained-clearance" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry -> rererestored-clearance-rebuild-reentry -> rererestored-clearance-rebuild-reentry" }, "empty": { "aligned_fresh_runs_after_latest_rererestore_reset": 0, @@ -981,7 +981,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry" }, "reversing": { "aligned_fresh_runs_after_latest_rererestore_reset": 0, @@ -990,7 +990,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rebuilt-confirmation-reentry -> strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" }, "single-event": { "aligned_fresh_runs_after_latest_rererestore_reset": 0, @@ -999,7 +999,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" }, "sparse": { "aligned_fresh_runs_after_latest_rererestore_reset": 0, @@ -1008,7 +1008,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "sparse-none -> strong-conf -> decrement-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry -> hold -> rererestored-confirmation-rebuild-reentry -> hold" }, "sustained-confirmation": { "aligned_fresh_runs_after_latest_rererestore_reset": 0, @@ -1017,7 +1017,7 @@ "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_status": "none", "recent_rererestore_reset_side": "none", - "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "strong-conf -> strong-conf -> strong-conf" + "recent_reset_reentry_rebuild_reentry_restore_rererestore_refresh_path": "rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry -> rererestored-confirmation-rebuild-reentry" } }, "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_refresh_recovery_summary": { @@ -1053,7 +1053,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "strong-conf -> decrement-conf", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilding-confirmation-reentry", "recent_reset_reentry_side": "confirmation" }, "clearance-hold": { @@ -1062,7 +1062,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "sustained-clearance -> sustained-clearance", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> rebuilt-clearance-reentry -> rebuilt-clearance-reentry", "recent_reset_reentry_side": "none" }, "empty": { @@ -1071,7 +1071,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry", "recent_reset_reentry_side": "none" }, "reversing": { @@ -1080,7 +1080,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> strong-conf", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry", "recent_reset_reentry_side": "none" }, "single-event": { @@ -1089,7 +1089,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "strong-conf", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry", "recent_reset_reentry_side": "none" }, "sparse": { @@ -1098,7 +1098,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "sparse-none -> strong-conf -> decrement-conf", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> hold -> rebuilt-confirmation-reentry -> rebuilding-confirmation-reentry", "recent_reset_reentry_side": "confirmation" }, "sustained-confirmation": { @@ -1107,7 +1107,7 @@ "closure_forecast_reset_reentry_rebuild_status": "none", "closure_forecast_reset_reentry_refresh_recovery_score": 0.0, "closure_forecast_reset_reentry_refresh_recovery_status": "none", - "recent_reset_reentry_refresh_path": "strong-conf -> strong-conf -> strong-conf", + "recent_reset_reentry_refresh_path": "rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry -> rebuilt-confirmation-reentry", "recent_reset_reentry_side": "none" } }, @@ -1143,7 +1143,7 @@ "closure_forecast_reset_reentry_status": "none", "closure_forecast_reset_refresh_recovery_score": 0.0, "closure_forecast_reset_refresh_recovery_status": "none", - "recent_reset_refresh_path": "strong-conf -> decrement-conf", + "recent_reset_refresh_path": "hold -> hold", "recent_reset_side": "none" }, "clearance-hold": { @@ -1152,7 +1152,7 @@ "closure_forecast_reset_reentry_status": "none", "closure_forecast_reset_refresh_recovery_score": 0.0, "closure_forecast_reset_refresh_recovery_status": "none", - "recent_reset_refresh_path": "sustained-clearance -> sustained-clearance", + "recent_reset_refresh_path": "hold -> hold", "recent_reset_side": "none" }, "empty": { @@ -1170,7 +1170,7 @@ "closure_forecast_reset_reentry_status": "none", "closure_forecast_reset_refresh_recovery_score": 0.0, "closure_forecast_reset_refresh_recovery_status": "none", - "recent_reset_refresh_path": "rebuilt-confirmation-reentry -> strong-conf", + "recent_reset_refresh_path": "hold -> hold", "recent_reset_side": "none" }, "single-event": { @@ -1179,7 +1179,7 @@ "closure_forecast_reset_reentry_status": "none", "closure_forecast_reset_refresh_recovery_score": 0.0, "closure_forecast_reset_refresh_recovery_status": "none", - "recent_reset_refresh_path": "strong-conf", + "recent_reset_refresh_path": "hold", "recent_reset_side": "none" }, "sparse": { @@ -1188,7 +1188,7 @@ "closure_forecast_reset_reentry_status": "none", "closure_forecast_reset_refresh_recovery_score": 0.0, "closure_forecast_reset_refresh_recovery_status": "none", - "recent_reset_refresh_path": "sparse-none -> strong-conf -> decrement-conf", + "recent_reset_refresh_path": "hold -> hold -> hold", "recent_reset_side": "none" }, "sustained-confirmation": { @@ -1197,7 +1197,7 @@ "closure_forecast_reset_reentry_status": "none", "closure_forecast_reset_refresh_recovery_score": 0.0, "closure_forecast_reset_refresh_recovery_status": "none", - "recent_reset_refresh_path": "strong-conf -> strong-conf -> strong-conf", + "recent_reset_refresh_path": "hold -> hold -> hold", "recent_reset_side": "none" } }, diff --git a/tests/golden/enumerate_composer_contract.py b/tests/golden/enumerate_composer_contract.py index a7f33f3..47ddff3 100644 --- a/tests/golden/enumerate_composer_contract.py +++ b/tests/golden/enumerate_composer_contract.py @@ -29,13 +29,22 @@ fail. Any future change to these families must reproduce THIS golden byte-for-byte; an intentional behavior change shows up here as a reviewed diff, never a silent one. -Fixed-harness validity: the injected callables below are deterministic stand-ins, -not the production wiring (which threads ~15 helpers per composer). The golden's -validity does NOT depend on production-identical callables -- it pins composer -behavior under a FIXED harness, and the collapse must reproduce it under the SAME -harness. The harness only has to be (a) held constant between generation and check -(it is -- one enumerator) and (b) rich enough to exercise the real branches (the -companion test guards a non-degenerate branch count and the magnitude-floor fix). +2026-07-10: re-pinned under production collaborators after the no-callable- +threading unwind (reset_controls satellite). Composers used to receive every +dependency (side/path classifiers, clamp_round, window constants, ...) as an +injected kwonly Callable/constant, and this enumerator swapped in deterministic +stand-ins for them via kwargs -- a semantics artifact of the injection idiom +itself, since production call sites never actually received those stand-ins. +The composers now resolve those dependencies directly (sibling call within this +module, or import from ``operator_trend_support`` / +``operator_trend_closure_forecast_freshness_controls``), so there is no longer a +kwarg to inject through, and determinism comes from the input corpus below +instead of from fixed-harness substitution. This is a harness-semantics re-pin, +not a production behavior change: the 34 composers whose output never depended +on a stand-in (i.e. never referenced a classifier/path-label dependency that the +old harness swapped) are byte-identical to the prior golden; only the 13 whose +recorded output depended on a stand-in value changed, and each was hand-verified +against the real function before the golden was refrozen. Regenerate only with an intentional, reviewed behavior change:: @@ -44,7 +53,6 @@ from __future__ import annotations -import functools import inspect import json from pathlib import Path @@ -71,224 +79,6 @@ ) -# --------------------------------------------------------------------------- # -# Fixed faithful callables (deterministic stand-ins for the injected helpers). -# --------------------------------------------------------------------------- # -def _clamp_round(value: float, lower: float, upper: float) -> float: - return round(max(lower, min(upper, value)), 2) - - -def _side_from_event(event: dict[str, Any]) -> str: - # Mirrors the production discriminator shape: confirmation wins over clearance, - # scanning the event's status-bearing values in insertion order. - for value in event.values(): - if isinstance(value, str): - if "confirmation" in value: - return "confirmation" - if "clearance" in value: - return "clearance" - return "none" - - -def _side_from_status(status: str) -> str: - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - return "none" - - -def _path_label(event: dict[str, Any]) -> str: - for value in event.values(): - if isinstance(value, str) and "-" in value: - return value - return "hold" - - -def _direction_majority(directions: list[str]) -> str: - confirmation = directions.count("supporting-confirmation") - clearance = directions.count("supporting-clearance") - if confirmation > clearance: - return "supporting-confirmation" - if clearance > confirmation: - return "supporting-clearance" - return "neutral" - - -def _direction_reversing(current_direction: str, earlier_majority: str) -> bool: - if current_direction == "neutral" or earlier_majority == "neutral": - return False - return current_direction != earlier_majority - - -def _flip_count(directions: list[str]) -> int: - return sum( - 1 - for previous, current in zip(directions, directions[1:]) - if previous != current - ) - - -def _normalization_noise(target: dict[str, Any], history_meta: dict[str, Any]) -> bool: - return bool( - target.get("local_noise") or history_meta.get("current_transition_reversed") - ) - - -def _class_key(item: dict[str, Any]) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _label(item: dict[str, Any]) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - -def _ordered_events( - target: dict[str, Any], events: list[dict[str, Any]] -) -> list[dict[str, Any]]: - key = _class_key(target) - return [event for event in events if event.get("class_key") == key] - - -def _normalized_direction(direction: str, value: float) -> str: - return direction - - -def _freshness_status(weighted_evidence: float, recent_share: float) -> str: - if weighted_evidence <= 0.0: - return "insufficient-data" - if recent_share >= 0.5: - return "fresh" - if recent_share >= 0.25: - return "mixed-age" - return "stale" - - -def _freshness_reason( - freshness_status: str, - weighted_evidence: float, - recent_share: float, - decayed_confirmation: float, - decayed_clearance: float, -) -> str: - return f"{freshness_status}:{round(weighted_evidence, 2)}:{round(recent_share, 2)}" - - -def _signal_mix( - weighted_evidence: float, - weighted_confirmation: float, - weighted_clearance: float, - recent_share: float, -) -> str: - if weighted_confirmation > weighted_clearance: - return "confirmation-leaning" - if weighted_clearance > weighted_confirmation: - return "clearance-leaning" - return "balanced" - - -def _has_evidence(event: dict[str, Any]) -> bool: - return _side_from_event(event) != "none" - - -def _is_confirmation_like(event: dict[str, Any]) -> bool: - return _side_from_event(event) == "confirmation" - - -def _is_clearance_like(event: dict[str, Any]) -> bool: - return _side_from_event(event) == "clearance" - - -def _signal_label(event: dict[str, Any]) -> str: - return _side_from_event(event) - - -# --------------------------------------------------------------------------- # -# Kwarg registry: resolve each injected callable/constant by parameter name. -# Real module functions (str classifiers; the rererestore composers injected into -# the rerererestore wrappers) are bound recursively for faithfulness. -# --------------------------------------------------------------------------- # -def _resolve_kwargs( - fn: object, *, skip: frozenset[str] = frozenset() -) -> dict[str, Any]: - resolved: dict[str, Any] = {} - for name, param in inspect.signature(fn).parameters.items(): - if param.kind is not inspect.Parameter.KEYWORD_ONLY or name in skip: - continue - resolved[name] = _resolve_one(name) - return resolved - - -def _resolve_one(name: str) -> Any: - if name.endswith("window_runs"): - return 4 - if name == "class_memory_recency_weights": - return (1.0, 0.8, 0.6, 0.4) - - # Explicit fixed stand-ins take priority over real module functions of the same - # name (F3): e.g. `closure_forecast_reset_side_from_status` is a real str->str - # module fn injected into four composers, but the net must use the fixed - # `_side_from_status` stand-in so it never silently tracks the live function as - # the collapse refactors it. - if name.endswith(("side_from_event", "memory_side_from_event")): - return _side_from_event - if name.endswith( - ( - "side_from_status", - "side_from_persistence_status", - "side_from_recovery_status", - ) - ): - return _side_from_status - if name.endswith("path_label"): - return _path_label - if name == "clamp_round": - return _clamp_round - if name == "closure_forecast_direction_majority": - return _direction_majority - if name == "closure_forecast_direction_reversing": - return _direction_reversing - if name == "class_direction_flip_count": - return _flip_count - if name == "target_specific_normalization_noise": - return _normalization_noise - if name == "target_class_key": - return _class_key - if name == "target_label": - return _label - if name == "ordered_reset_reentry_events_for_target": - return _ordered_events - if name == "normalized_closure_forecast_direction": - return _normalized_direction - if name == "closure_forecast_freshness_status": - return _freshness_status - if name.endswith("freshness_reason"): - return _freshness_reason - if name == "recent_reset_reentry_signal_mix": - return _signal_mix - if name.endswith("event_has_evidence"): - return _has_evidence - if name.endswith("event_is_confirmation_like"): - return _is_confirmation_like - if name.endswith("event_is_clearance_like"): - return _is_clearance_like - if name.endswith("event_signal_label"): - return _signal_label - - # Fallback: a kwarg that names a real module composer. The rerererestore wrappers - # inject the live rererestore `*_for_target` builder (no suffix stand-in matches - # it); bind it recursively under the same stand-in harness so the wrapper - # genuinely delegates to the real tier it wraps. - real = getattr(m, name, None) - if callable(real) and getattr(real, "__module__", None) == m.__name__: - sub = _resolve_kwargs(real) - return functools.partial(real, **sub) if sub else real - - raise KeyError( - f"composer enumerator: no fixed stand-in for injected kwarg {name!r}" - ) - - # --------------------------------------------------------------------------- # # Corpus. Events carry every tier's status keys at once, so one archetype # meaningfully drives whichever tier composer consumes it. `decrement` events @@ -452,9 +242,9 @@ def _summary_inputs() -> tuple[ # presence reaches its real branch instead of a degenerate fallback whose output # the golden would otherwise pin as if correct. rich = _hotspot_targets() - primary = {**rich[0], "label": _class_key(rich[0])} - list_a = [{**rich[0], "label": _class_key(rich[0])}] - list_b = [{**rich[1], "label": _class_key(rich[1])}] + primary = {**rich[0], "label": m.target_class_key(rich[0])} + list_a = [{**rich[0], "label": m.target_class_key(rich[0])}] + list_b = [{**rich[1], "label": m.target_class_key(rich[1])}] return primary, list_a, list_b @@ -511,32 +301,28 @@ def _drive(name: str, fn: object) -> dict[str, Any]: results: dict[str, Any] = {} if role == "for_target": - kwargs = _resolve_kwargs(fn) for label, target, events, history_meta in _for_target_scenarios(): args = ( (target, events, history_meta) if len(positional) == 3 else (target, events) ) - results[label] = fn(*args, **kwargs) + results[label] = fn(*args) elif role == "hotspots": - kwargs = _resolve_kwargs(fn, skip=frozenset({"mode"})) targets = _hotspot_targets() for mode in HOTSPOT_MODES: - results[f"mode={mode}"] = fn(targets, mode=mode, **kwargs) + results[f"mode={mode}"] = fn(targets, mode=mode) elif role == "summary": - kwargs = _resolve_kwargs(fn) primary, list_a, list_b = _summary_inputs() args = (primary, list_a, list_b) if len(positional) == 3 else (primary, list_a) - results["summary"] = fn(*args, **kwargs) + results["summary"] = fn(*args) elif role == "path_label": - kwargs = _resolve_kwargs(fn) for label, event in { "confirmation": _event("c", "confirmation"), "clearance": _event("k", "clearance"), "none": _event("n", "none"), }.items(): - results[label] = fn(event, **kwargs) + results[label] = fn(event) else: # pragma: no cover - guards an unclassified composer shape raise KeyError(f"composer enumerator: unclassified composer {name!r}") return results diff --git a/tests/golden/enumerate_recovery_state_contract.py b/tests/golden/enumerate_recovery_state_contract.py index 796df46..a60c2a5 100644 --- a/tests/golden/enumerate_recovery_state_contract.py +++ b/tests/golden/enumerate_recovery_state_contract.py @@ -24,6 +24,7 @@ import src.operator_snapshot_packaging as m_pkg import src.operator_trend_closure_forecast_reacquisition_controls as m_reacq import src.operator_trend_closure_forecast_reset_controls as m_reset +import src.operator_trend_support as m_support # scanned since 2026-07-10: classifiers moved here by the callable-threading unwind REPO = Path(__file__).resolve().parents[2] GOLDEN_PATH = REPO / "tests" / "golden" / "recovery_state_contract.golden.json" @@ -84,7 +85,7 @@ def _harvest_status_literals(modules: tuple[ModuleType, ...]) -> set[str]: return harvested -_MODULES: tuple[ModuleType, ...] = (m_resolution, m_reset, m_reacq, m_pkg) +_MODULES: tuple[ModuleType, ...] = (m_resolution, m_reset, m_reacq, m_pkg, m_support) VOCAB: tuple[str, ...] = tuple( sorted( diff --git a/tests/golden/recovery_state_contract.golden.json b/tests/golden/recovery_state_contract.golden.json index 8ee950a..06a3a62 100644 --- a/tests/golden/recovery_state_contract.golden.json +++ b/tests/golden/recovery_state_contract.golden.json @@ -1,5 +1,5 @@ { - "src.operator_resolution_trend._closure_forecast_reacquisition_side_from_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_persistence_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -38,8 +38,8 @@ "confirmation-softened": "none", "confirmed": "none", "confirmed-caution": "none", - "confirmed-clearance": "clearance", - "confirmed-confirmation": "confirmation", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", "confirmed-support": "none", "counts": "none", "debt": "none", @@ -60,20 +60,20 @@ "high": "none", "hold": "none", "holding": "none", - "holding-clearance": "clearance", + "holding-clearance": "none", "holding-clearance-rebuild": "none", "holding-clearance-rebuild-reentry": "none", "holding-clearance-rebuild-reentry-rerererestore": "none", "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "clearance", "holding-clearance-rebuild-reentry-restore": "none", "holding-clearance-reentry": "none", - "holding-confirmation": "confirmation", + "holding-confirmation": "none", "holding-confirmation-rebuild": "none", "holding-confirmation-rebuild-reentry": "none", "holding-confirmation-rebuild-reentry-rerererestore": "none", "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "confirmation", "holding-confirmation-rebuild-reentry-restore": "none", "holding-confirmation-reentry": "none", "improving": "none", @@ -114,7 +114,7 @@ "oscillating": "none", "overcautious": "none", "pending-caution": "none", - "pending-clearance": "clearance", + "pending-clearance": "none", "pending-clearance-reacquisition": "none", "pending-clearance-rebuild": "none", "pending-clearance-rebuild-reentry": "none", @@ -123,7 +123,7 @@ "pending-clearance-rebuild-reentry-rerestore": "none", "pending-clearance-rebuild-reentry-restore": "none", "pending-clearance-reentry": "none", - "pending-confirmation": "confirmation", + "pending-confirmation": "none", "pending-confirmation-reacquisition": "none", "pending-confirmation-rebuild": "none", "pending-confirmation-rebuild-reentry": "none", @@ -142,6 +142,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -228,6 +229,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -237,20 +241,20 @@ "supporting-normalization": "none", "sustained": "none", "sustained-caution": "none", - "sustained-clearance": "clearance", + "sustained-clearance": "none", "sustained-clearance-rebuild": "none", "sustained-clearance-rebuild-reentry": "none", "sustained-clearance-rebuild-reentry-rerererestore": "none", "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "clearance", "sustained-clearance-rebuild-reentry-restore": "none", "sustained-clearance-reentry": "none", - "sustained-confirmation": "confirmation", + "sustained-confirmation": "none", "sustained-confirmation-rebuild": "none", "sustained-confirmation-rebuild-reentry": "none", "sustained-confirmation-rebuild-reentry-rerererestore": "none", "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "confirmation", "sustained-confirmation-rebuild-reentry-restore": "none", "sustained-confirmation-reentry": "none", "sustained-support": "none", @@ -266,379 +270,112 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_text": { - "": "", - "act-now": "act-now", - "act-with-review": "act-with-review", - "active-debt": "active-debt", - "applied": "applied", - "archived": "archived", - "attempted": "attempted", - "audits": "audits", - "blocked": "blocked", - "blocked-operator-item": "blocked-operator-item", - "building": "building", - "campaign": "campaign", - "candidate": "candidate", - "caution": "caution", - "chronic": "chronic", - "churn": "churn", - "class": "class", - "class-debt": "class-debt", - "clear-risk": "clear-risk", - "clear-risk-softened": "clear-risk-softened", - "clear-risk-strengthened": "clear-risk-strengthened", - "clearance": "clearance", - "clearance-decayed": "clearance-decayed", - "clearance-like": "clearance-like", - "clearance-reset": "clearance-reset", - "clearance-softened": "clearance-softened", - "cleared": "cleared", - "clearing": "clearing", - "confirm-soon": "confirm-soon", - "confirm-support-softened": "confirm-support-softened", - "confirm-support-strengthened": "confirm-support-strengthened", - "confirmation": "confirmation", - "confirmation-decayed": "confirmation-decayed", - "confirmation-like": "confirmation-like", - "confirmation-reset": "confirmation-reset", - "confirmation-softened": "confirmation-softened", - "confirmed": "confirmed", - "confirmed-caution": "confirmed-caution", - "confirmed-clearance": "confirmed-clearance", - "confirmed-confirmation": "confirmed-confirmation", - "confirmed-support": "confirmed-support", - "counts": "counts", - "debt": "debt", - "deferred": "deferred", - "direction": "direction", - "drift-or-regression": "drift-or-regression", - "drifting": "drifting", - "earned": "earned", - "effect": "effect", - "expire-risk": "expire-risk", - "expired": "expired", - "filter-or-profile-changed": "filter-or-profile-changed", - "fresh": "fresh", - "full-refresh-due": "full-refresh-due", - "governance": "governance", - "headline": "headline", - "healthy": "healthy", - "high": "high", - "hold": "hold", - "holding": "holding", - "holding-clearance": "holding-clearance", - "holding-clearance-rebuild": "holding-clearance-rebuild", - "holding-clearance-rebuild-reentry": "holding-clearance-rebuild-reentry", - "holding-clearance-rebuild-reentry-rerererestore": "holding-clearance-rebuild-reentry-rererererestore", - "holding-clearance-rebuild-reentry-rererestore": "holding-clearance-rebuild-reentry-rerererestore", - "holding-clearance-rebuild-reentry-rerestore": "holding-clearance-rebuild-reentry-rerestore", - "holding-clearance-rebuild-reentry-restore": "holding-clearance-rebuild-reentry-restore", - "holding-clearance-reentry": "holding-clearance-reentry", - "holding-confirmation": "holding-confirmation", - "holding-confirmation-rebuild": "holding-confirmation-rebuild", - "holding-confirmation-rebuild-reentry": "holding-confirmation-rebuild-reentry", - "holding-confirmation-rebuild-reentry-rerererestore": "holding-confirmation-rebuild-reentry-rererererestore", - "holding-confirmation-rebuild-reentry-rererestore": "holding-confirmation-rebuild-reentry-rerererestore", - "holding-confirmation-rebuild-reentry-rerestore": "holding-confirmation-rebuild-reentry-rerestore", - "holding-confirmation-rebuild-reentry-restore": "holding-confirmation-rebuild-reentry-restore", - "holding-confirmation-reentry": "holding-confirmation-reentry", - "improving": "improving", - "incremental": "incremental", - "insufficient-data": "insufficient-data", - "items": "items", - "just-reacquired": "just-reacquired", - "just-rebuilt": "just-rebuilt", - "just-reentered": "just-reentered", - "just-rerererestored": "just-rererererestored", - "just-rererestored": "just-rerererestored", - "just-rerestored": "just-rerestored", - "just-restored": "just-restored", - "key": "key", - "kind": "kind", - "label": "label", - "lane": "lane", - "low": "low", - "manual": "manual", - "manual-review-ready": "manual-review-ready", - "medium": "medium", - "metadata": "metadata", - "missing-trustworthy-baseline": "missing-trustworthy-baseline", - "mixed": "mixed", - "mixed-age": "mixed-age", - "monitor": "monitor", - "name": "name", - "neutral": "neutral", - "new": "new", - "no-change": "no-change", - "noisy": "noisy", - "none": "none", - "normalization-boosted": "normalization-boosted", - "normalization-decayed": "normalization-decayed", - "normalization-softened": "normalization-softened", - "normalized": "normalized", - "one-off-noise": "one-off-noise", - "oscillating": "oscillating", - "overcautious": "overcautious", - "pending-caution": "pending-caution", - "pending-clearance": "pending-clearance", - "pending-clearance-reacquisition": "pending-clearance-reacquisition", - "pending-clearance-rebuild": "pending-clearance-rebuild", - "pending-clearance-rebuild-reentry": "pending-clearance-rebuild-reentry", - "pending-clearance-rebuild-reentry-rerererestore": "pending-clearance-rebuild-reentry-rererererestore", - "pending-clearance-rebuild-reentry-rererestore": "pending-clearance-rebuild-reentry-rerererestore", - "pending-clearance-rebuild-reentry-rerestore": "pending-clearance-rebuild-reentry-rerestore", - "pending-clearance-rebuild-reentry-restore": "pending-clearance-rebuild-reentry-restore", - "pending-clearance-reentry": "pending-clearance-reentry", - "pending-confirmation": "pending-confirmation", - "pending-confirmation-reacquisition": "pending-confirmation-reacquisition", - "pending-confirmation-rebuild": "pending-confirmation-rebuild", - "pending-confirmation-rebuild-reentry": "pending-confirmation-rebuild-reentry", - "pending-confirmation-rebuild-reentry-rerererestore": "pending-confirmation-rebuild-reentry-rererererestore", - "pending-confirmation-rebuild-reentry-rererestore": "pending-confirmation-rebuild-reentry-rerererestore", - "pending-confirmation-rebuild-reentry-rerestore": "pending-confirmation-rebuild-reentry-rerestore", - "pending-confirmation-rebuild-reentry-restore": "pending-confirmation-rebuild-reentry-restore", - "pending-confirmation-reentry": "pending-confirmation-reentry", - "pending-support": "pending-support", - "persisting": "persisting", - "policy-debt": "policy-debt", - "policy-debt-decayed": "policy-debt-decayed", - "policy-debt-softened": "policy-debt-softened", - "policy-debt-strengthened": "policy-debt-strengthened", - "portfolio": "portfolio", - "priority": "priority", - "quiet": "quiet", - "quieted": "quieted", - "re-re-re-restore": "re-re-re-re-restore", - "re-re-re-restored": "re-re-re-re-restored", - "re-re-re-restoring": "re-re-re-re-restoring", - "re-re-restore": "re-re-re-restore", - "re-re-restored": "re-re-re-restored", - "re-re-restoring": "re-re-re-restoring", - "reacquired": "reacquired", - "reacquired-clearance": "reacquired-clearance", - "reacquired-confirmation": "reacquired-confirmation", - "reacquiring-clearance": "reacquiring-clearance", - "reacquiring-confirmation": "reacquiring-confirmation", - "ready": "ready", - "reason": "reason", - "rebuilding-clearance-reentry": "rebuilding-clearance-reentry", - "rebuilding-confirmation-reentry": "rebuilding-confirmation-reentry", - "rebuilt-clearance-reentry": "rebuilt-clearance-reentry", - "rebuilt-confirmation-reentry": "rebuilt-confirmation-reentry", - "recovering": "recovering", - "recovering-clearance": "recovering-clearance", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "recovering-clearance-rebuild-reentry-rererererestore-reset", - "recovering-clearance-rebuild-reentry-rererestore-reset": "recovering-clearance-rebuild-reentry-rerererestore-reset", - "recovering-clearance-rebuild-reentry-rerestore-reset": "recovering-clearance-rebuild-reentry-rerestore-reset", - "recovering-clearance-rebuild-reentry-reset": "recovering-clearance-rebuild-reentry-reset", - "recovering-clearance-rebuild-reentry-restore-reset": "recovering-clearance-rebuild-reentry-restore-reset", - "recovering-clearance-rebuild-reset": "recovering-clearance-rebuild-reset", - "recovering-clearance-reentry-reset": "recovering-clearance-reentry-reset", - "recovering-clearance-reset": "recovering-clearance-reset", - "recovering-confirmation": "recovering-confirmation", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "recovering-confirmation-rebuild-reentry-rererererestore-reset", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "recovering-confirmation-rebuild-reentry-rerererestore-reset", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "recovering-confirmation-rebuild-reentry-rerestore-reset", - "recovering-confirmation-rebuild-reentry-reset": "recovering-confirmation-rebuild-reentry-reset", - "recovering-confirmation-rebuild-reentry-restore-reset": "recovering-confirmation-rebuild-reentry-restore-reset", - "recovering-confirmation-rebuild-reset": "recovering-confirmation-rebuild-reset", - "recovering-confirmation-reentry-reset": "recovering-confirmation-reentry-reset", - "recovering-confirmation-reset": "recovering-confirmation-reset", - "reentered-clearance": "reentered-clearance", - "reentered-clearance-rebuild": "reentered-clearance-rebuild", - "reentered-confirmation": "reentered-confirmation", - "reentered-confirmation-rebuild": "reentered-confirmation-rebuild", - "reentering-clearance": "reentering-clearance", - "reentering-clearance-rebuild": "reentering-clearance-rebuild", - "reentering-confirmation": "reentering-confirmation", - "reentering-confirmation-rebuild": "reentering-confirmation-rebuild", - "reopened": "reopened", - "repo": "repo", - "rerererestore": "rererererestore", - "rerererestored": "rererererestored", - "rerererestored-clearance-rebuild-reentry": "rererererestored-clearance-rebuild-reentry", - "rerererestored-confirmation-rebuild-reentry": "rererererestored-confirmation-rebuild-reentry", - "rerererestoring": "rererererestoring", - "rerererestoring-clearance-rebuild-reentry": "rererererestoring-clearance-rebuild-reentry", - "rerererestoring-confirmation-rebuild-reentry": "rererererestoring-confirmation-rebuild-reentry", - "rererestore": "rerererestore", - "rererestored": "rerererestored", - "rererestored-clearance-rebuild-reentry": "rerererestored-clearance-rebuild-reentry", - "rererestored-confirmation-rebuild-reentry": "rerererestored-confirmation-rebuild-reentry", - "rererestoring": "rerererestoring", - "rererestoring-clearance-rebuild-reentry": "rerererestoring-clearance-rebuild-reentry", - "rererestoring-confirmation-rebuild-reentry": "rerererestoring-confirmation-rebuild-reentry", - "rerestored-clearance-rebuild-reentry": "rerestored-clearance-rebuild-reentry", - "rerestored-confirmation-rebuild-reentry": "rerestored-confirmation-rebuild-reentry", - "rerestoring-clearance-rebuild-reentry": "rerestoring-clearance-rebuild-reentry", - "rerestoring-confirmation-rebuild-reentry": "rerestoring-confirmation-rebuild-reentry", - "resolving": "resolving", - "restored-clearance-rebuild-reentry": "restored-clearance-rebuild-reentry", - "restored-confirmation-rebuild-reentry": "restored-confirmation-rebuild-reentry", - "restoring-clearance-rebuild-reentry": "restoring-clearance-rebuild-reentry", - "restoring-confirmation-rebuild-reentry": "restoring-confirmation-rebuild-reentry", - "retired": "retired", - "reversing": "reversing", - "safe-to-defer": "safe-to-defer", - "scheduled-full-refresh": "scheduled-full-refresh", - "scope": "scope", - "scorecard": "scorecard", - "setup": "setup", - "setup-blocker": "setup-blocker", - "softened-for-flip-churn": "softened-for-flip-churn", - "softened-for-noise": "softened-for-noise", - "softened-for-reopen-risk": "softened-for-reopen-risk", - "stable": "stable", - "stale": "stale", - "stale-baseline": "stale-baseline", - "stalled": "stalled", - "status": "status", - "sticky": "sticky", - "summary": "summary", - "support": "support", - "supporting": "supporting", - "supporting-caution": "supporting-caution", - "supporting-clearance": "supporting-clearance", - "supporting-confirmation": "supporting-confirmation", - "supporting-normalization": "supporting-normalization", - "sustained": "sustained", - "sustained-caution": "sustained-caution", - "sustained-clearance": "sustained-clearance", - "sustained-clearance-rebuild": "sustained-clearance-rebuild", - "sustained-clearance-rebuild-reentry": "sustained-clearance-rebuild-reentry", - "sustained-clearance-rebuild-reentry-rerererestore": "sustained-clearance-rebuild-reentry-rererererestore", - "sustained-clearance-rebuild-reentry-rererestore": "sustained-clearance-rebuild-reentry-rerererestore", - "sustained-clearance-rebuild-reentry-rerestore": "sustained-clearance-rebuild-reentry-rerestore", - "sustained-clearance-rebuild-reentry-restore": "sustained-clearance-rebuild-reentry-restore", - "sustained-clearance-reentry": "sustained-clearance-reentry", - "sustained-confirmation": "sustained-confirmation", - "sustained-confirmation-rebuild": "sustained-confirmation-rebuild", - "sustained-confirmation-rebuild-reentry": "sustained-confirmation-rebuild-reentry", - "sustained-confirmation-rebuild-reentry-rerererestore": "sustained-confirmation-rebuild-reentry-rererererestore", - "sustained-confirmation-rebuild-reentry-rererestore": "sustained-confirmation-rebuild-reentry-rerererestore", - "sustained-confirmation-rebuild-reentry-rerestore": "sustained-confirmation-rebuild-reentry-rerestore", - "sustained-confirmation-rebuild-reentry-restore": "sustained-confirmation-rebuild-reentry-restore", - "sustained-confirmation-reentry": "sustained-confirmation-reentry", - "sustained-support": "sustained-support", - "title": "title", - "unavailable": "unavailable", - "unknown": "unknown", - "unstable": "unstable", - "urgency": "urgency", - "urgent": "urgent", - "useful-caution": "useful-caution", - "username": "username", - "verify-first": "verify-first", - "watch": "watch", - "worsening": "worsening" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "clearance", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "confirmation", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "confirmation", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", "none": "none", "normalization-boosted": "none", "normalization-decayed": "none", @@ -654,7 +391,7 @@ "pending-clearance-rebuild-reentry": "none", "pending-clearance-rebuild-reentry-rerererestore": "none", "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "clearance", "pending-clearance-rebuild-reentry-restore": "none", "pending-clearance-reentry": "none", "pending-confirmation": "none", @@ -663,7 +400,7 @@ "pending-confirmation-rebuild-reentry": "none", "pending-confirmation-rebuild-reentry-rerererestore": "none", "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "confirmation", "pending-confirmation-rebuild-reentry-restore": "none", "pending-confirmation-reentry": "none", "pending-support": "none", @@ -676,6 +413,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -736,8 +474,8 @@ "rererestoring": "none", "rererestoring-clearance-rebuild-reentry": "none", "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "clearance", + "rerestored-confirmation-rebuild-reentry": "confirmation", "rerestoring-clearance-rebuild-reentry": "none", "rerestoring-confirmation-rebuild-reentry": "none", "resolving": "none", @@ -762,6 +500,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -775,7 +516,7 @@ "sustained-clearance-rebuild": "none", "sustained-clearance-rebuild-reentry": "none", "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "clearance", + "sustained-clearance-rebuild-reentry-rererestore": "none", "sustained-clearance-rebuild-reentry-rerestore": "none", "sustained-clearance-rebuild-reentry-restore": "none", "sustained-clearance-reentry": "none", @@ -783,7 +524,7 @@ "sustained-confirmation-rebuild": "none", "sustained-confirmation-rebuild-reentry": "none", "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "confirmation", + "sustained-confirmation-rebuild-reentry-rererestore": "none", "sustained-confirmation-rebuild-reentry-rerestore": "none", "sustained-confirmation-rebuild-reentry-restore": "none", "sustained-confirmation-reentry": "none", @@ -800,7 +541,7 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_persistence_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -863,7 +604,7 @@ "holding": "none", "holding-clearance": "none", "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry": "clearance", "holding-clearance-rebuild-reentry-rerererestore": "none", "holding-clearance-rebuild-reentry-rererestore": "none", "holding-clearance-rebuild-reentry-rerestore": "none", @@ -871,7 +612,7 @@ "holding-clearance-reentry": "none", "holding-confirmation": "none", "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry": "confirmation", "holding-confirmation-rebuild-reentry-rerererestore": "none", "holding-confirmation-rebuild-reentry-rererestore": "none", "holding-confirmation-rebuild-reentry-rerestore": "none", @@ -920,7 +661,7 @@ "pending-clearance-rebuild": "none", "pending-clearance-rebuild-reentry": "none", "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "clearance", + "pending-clearance-rebuild-reentry-rererestore": "none", "pending-clearance-rebuild-reentry-rerestore": "none", "pending-clearance-rebuild-reentry-restore": "none", "pending-clearance-reentry": "none", @@ -929,7 +670,7 @@ "pending-confirmation-rebuild": "none", "pending-confirmation-rebuild-reentry": "none", "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "confirmation", + "pending-confirmation-rebuild-reentry-rererestore": "none", "pending-confirmation-rebuild-reentry-rerestore": "none", "pending-confirmation-rebuild-reentry-restore": "none", "pending-confirmation-reentry": "none", @@ -943,6 +684,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -998,8 +740,8 @@ "rerererestoring-confirmation-rebuild-reentry": "none", "rererestore": "none", "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "clearance", - "rererestored-confirmation-rebuild-reentry": "confirmation", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", "rererestoring": "none", "rererestoring-clearance-rebuild-reentry": "none", "rererestoring-confirmation-rebuild-reentry": "none", @@ -1029,6 +771,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -1040,7 +785,7 @@ "sustained-caution": "none", "sustained-clearance": "none", "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry": "clearance", "sustained-clearance-rebuild-reentry-rerererestore": "none", "sustained-clearance-rebuild-reentry-rererestore": "none", "sustained-clearance-rebuild-reentry-rerestore": "none", @@ -1048,7 +793,7 @@ "sustained-clearance-reentry": "none", "sustained-confirmation": "none", "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry": "confirmation", "sustained-confirmation-rebuild-reentry-rerererestore": "none", "sustained-confirmation-rebuild-reentry-rererestore": "none", "sustained-confirmation-rebuild-reentry-rerestore": "none", @@ -1067,7 +812,7 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_persistence_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_refresh_recovery_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -1133,7 +878,7 @@ "holding-clearance-rebuild-reentry": "none", "holding-clearance-rebuild-reentry-rerererestore": "none", "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "clearance", + "holding-clearance-rebuild-reentry-rerestore": "none", "holding-clearance-rebuild-reentry-restore": "none", "holding-clearance-reentry": "none", "holding-confirmation": "none", @@ -1141,7 +886,7 @@ "holding-confirmation-rebuild-reentry": "none", "holding-confirmation-rebuild-reentry-rerererestore": "none", "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "confirmation", + "holding-confirmation-rebuild-reentry-rerestore": "none", "holding-confirmation-rebuild-reentry-restore": "none", "holding-confirmation-reentry": "none", "improving": "none", @@ -1210,6 +955,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -1232,7 +978,7 @@ "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", "recovering-clearance-rebuild-reentry-rererestore-reset": "none", "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "clearance", "recovering-clearance-rebuild-reentry-restore-reset": "none", "recovering-clearance-rebuild-reset": "none", "recovering-clearance-reentry-reset": "none", @@ -1241,7 +987,7 @@ "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "confirmation", "recovering-confirmation-rebuild-reentry-restore-reset": "none", "recovering-confirmation-rebuild-reset": "none", "recovering-confirmation-reentry-reset": "none", @@ -1277,8 +1023,8 @@ "resolving": "none", "restored-clearance-rebuild-reentry": "none", "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "clearance", + "restoring-confirmation-rebuild-reentry": "confirmation", "retired": "none", "reversing": "none", "safe-to-defer": "none", @@ -1296,6 +1042,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -1310,7 +1059,7 @@ "sustained-clearance-rebuild-reentry": "none", "sustained-clearance-rebuild-reentry-rerererestore": "none", "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "clearance", + "sustained-clearance-rebuild-reentry-rerestore": "none", "sustained-clearance-rebuild-reentry-restore": "none", "sustained-clearance-reentry": "none", "sustained-confirmation": "none", @@ -1318,7 +1067,7 @@ "sustained-confirmation-rebuild-reentry": "none", "sustained-confirmation-rebuild-reentry-rerererestore": "none", "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "confirmation", + "sustained-confirmation-rebuild-reentry-rerestore": "none", "sustained-confirmation-rebuild-reentry-restore": "none", "sustained-confirmation-reentry": "none", "sustained-support": "none", @@ -1334,7 +1083,7 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -1401,7 +1150,7 @@ "holding-clearance-rebuild-reentry-rerererestore": "none", "holding-clearance-rebuild-reentry-rererestore": "none", "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-rebuild-reentry-restore": "clearance", "holding-clearance-reentry": "none", "holding-confirmation": "none", "holding-confirmation-rebuild": "none", @@ -1409,7 +1158,7 @@ "holding-confirmation-rebuild-reentry-rerererestore": "none", "holding-confirmation-rebuild-reentry-rererestore": "none", "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-rebuild-reentry-restore": "confirmation", "holding-confirmation-reentry": "none", "improving": "none", "incremental": "none", @@ -1477,6 +1226,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -1498,7 +1248,7 @@ "recovering-clearance": "none", "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "clearance", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", "recovering-clearance-rebuild-reentry-reset": "none", "recovering-clearance-rebuild-reentry-restore-reset": "none", "recovering-clearance-rebuild-reset": "none", @@ -1507,7 +1257,7 @@ "recovering-confirmation": "none", "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "confirmation", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", "recovering-confirmation-rebuild-reentry-reset": "none", "recovering-confirmation-rebuild-reentry-restore-reset": "none", "recovering-confirmation-rebuild-reset": "none", @@ -1535,8 +1285,8 @@ "rererestored-clearance-rebuild-reentry": "none", "rererestored-confirmation-rebuild-reentry": "none", "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "clearance", - "rererestoring-confirmation-rebuild-reentry": "confirmation", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", "rerestored-clearance-rebuild-reentry": "none", "rerestored-confirmation-rebuild-reentry": "none", "rerestoring-clearance-rebuild-reentry": "none", @@ -1563,6 +1313,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -1578,7 +1331,7 @@ "sustained-clearance-rebuild-reentry-rerererestore": "none", "sustained-clearance-rebuild-reentry-rererestore": "none", "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-rebuild-reentry-restore": "clearance", "sustained-clearance-reentry": "none", "sustained-confirmation": "none", "sustained-confirmation-rebuild": "none", @@ -1586,7 +1339,7 @@ "sustained-confirmation-rebuild-reentry-rerererestore": "none", "sustained-confirmation-rebuild-reentry-rererestore": "none", "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-rebuild-reentry-restore": "confirmation", "sustained-confirmation-reentry": "none", "sustained-support": "none", "title": "none", @@ -1601,7 +1354,7 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -1722,8 +1475,8 @@ "pending-clearance-rebuild-reentry": "none", "pending-clearance-rebuild-reentry-rerererestore": "none", "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "clearance", - "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "clearance", "pending-clearance-reentry": "none", "pending-confirmation": "none", "pending-confirmation-reacquisition": "none", @@ -1731,8 +1484,8 @@ "pending-confirmation-rebuild-reentry": "none", "pending-confirmation-rebuild-reentry-rerererestore": "none", "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "confirmation", - "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "confirmation", "pending-confirmation-reentry": "none", "pending-support": "none", "persisting": "none", @@ -1744,6 +1497,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -1804,13 +1558,13 @@ "rererestoring": "none", "rererestoring-clearance-rebuild-reentry": "none", "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "clearance", - "rerestored-confirmation-rebuild-reentry": "confirmation", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", "rerestoring-clearance-rebuild-reentry": "none", "rerestoring-confirmation-rebuild-reentry": "none", "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", + "restored-clearance-rebuild-reentry": "clearance", + "restored-confirmation-rebuild-reentry": "confirmation", "restoring-clearance-rebuild-reentry": "none", "restoring-confirmation-rebuild-reentry": "none", "retired": "none", @@ -1830,6 +1584,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -1868,7 +1625,7 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_persistence_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_reentry_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -1931,7 +1688,7 @@ "holding": "none", "holding-clearance": "none", "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "clearance", + "holding-clearance-rebuild-reentry": "none", "holding-clearance-rebuild-reentry-rerererestore": "none", "holding-clearance-rebuild-reentry-rererestore": "none", "holding-clearance-rebuild-reentry-rerestore": "none", @@ -1939,7 +1696,7 @@ "holding-clearance-reentry": "none", "holding-confirmation": "none", "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "confirmation", + "holding-confirmation-rebuild-reentry": "none", "holding-confirmation-rebuild-reentry-rerererestore": "none", "holding-confirmation-rebuild-reentry-rererestore": "none", "holding-confirmation-rebuild-reentry-rerestore": "none", @@ -1986,7 +1743,7 @@ "pending-clearance": "none", "pending-clearance-reacquisition": "none", "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry": "clearance", "pending-clearance-rebuild-reentry-rerererestore": "none", "pending-clearance-rebuild-reentry-rererestore": "none", "pending-clearance-rebuild-reentry-rerestore": "none", @@ -1995,7 +1752,7 @@ "pending-confirmation": "none", "pending-confirmation-reacquisition": "none", "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry": "confirmation", "pending-confirmation-rebuild-reentry-rerererestore": "none", "pending-confirmation-rebuild-reentry-rererestore": "none", "pending-confirmation-rebuild-reentry-rerestore": "none", @@ -2011,6 +1768,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -2048,9 +1806,9 @@ "recovering-confirmation-reentry-reset": "none", "recovering-confirmation-reset": "none", "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", + "reentered-clearance-rebuild": "clearance", "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", + "reentered-confirmation-rebuild": "confirmation", "reentering-clearance": "none", "reentering-clearance-rebuild": "none", "reentering-confirmation": "none", @@ -2097,6 +1855,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -2108,7 +1869,7 @@ "sustained-caution": "none", "sustained-clearance": "none", "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "clearance", + "sustained-clearance-rebuild-reentry": "none", "sustained-clearance-rebuild-reentry-rerererestore": "none", "sustained-clearance-rebuild-reentry-rererestore": "none", "sustained-clearance-rebuild-reentry-rerestore": "none", @@ -2116,7 +1877,7 @@ "sustained-clearance-reentry": "none", "sustained-confirmation": "none", "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "confirmation", + "sustained-confirmation-rebuild-reentry": "none", "sustained-confirmation-rebuild-reentry-rerererestore": "none", "sustained-confirmation-rebuild-reentry-rererestore": "none", "sustained-confirmation-rebuild-reentry-rerestore": "none", @@ -2135,7 +1896,7 @@ "watch": "none", "worsening": "none" }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_refresh_recovery_status": { + "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_refresh_recovery_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -2278,6 +2039,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -2300,18 +2062,18 @@ "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", "recovering-clearance-rebuild-reentry-rererestore-reset": "none", "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "clearance", + "recovering-clearance-rebuild-reentry-reset": "none", "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-rebuild-reset": "clearance", "recovering-clearance-reentry-reset": "none", "recovering-clearance-reset": "none", "recovering-confirmation": "none", "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "confirmation", + "recovering-confirmation-rebuild-reentry-reset": "none", "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-rebuild-reset": "confirmation", "recovering-confirmation-reentry-reset": "none", "recovering-confirmation-reset": "none", "reentered-clearance": "none", @@ -2319,9 +2081,9 @@ "reentered-confirmation": "none", "reentered-confirmation-rebuild": "none", "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", + "reentering-clearance-rebuild": "clearance", "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", + "reentering-confirmation-rebuild": "confirmation", "reopened": "none", "repo": "none", "rerererestore": "none", @@ -2345,2945 +2107,8 @@ "resolving": "none", "restored-clearance-rebuild-reentry": "none", "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "clearance", - "restoring-confirmation-rebuild-reentry": "confirmation", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_persistence_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "clearance", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "confirmation", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "clearance", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "confirmation", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_reentry_side_from_restore_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "clearance", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "confirmation", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "clearance", - "restored-confirmation-rebuild-reentry": "confirmation", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_persistence_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "clearance", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "confirmation", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "clearance", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "confirmation", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_recovery_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "clearance", - "rebuilding-confirmation-reentry": "confirmation", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "clearance", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "confirmation", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_reentry_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "clearance", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "confirmation", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "clearance", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "confirmation", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_refresh_recovery_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "clearance", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "confirmation", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "clearance", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "confirmation", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_rebuild_side_from_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "clearance", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "confirmation", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "clearance", - "rebuilt-confirmation-reentry": "confirmation", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_side_from_persistence_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "clearance", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "confirmation", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "clearance", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "confirmation", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_side_from_recovery_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "clearance", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "confirmation", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "clearance", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "confirmation", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_reentry_side_from_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "none", - "clearance-softened": "none", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "none", - "confirmation-softened": "none", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "clearance", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "confirmation", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "clearance", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "confirmation", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", - "retired": "none", - "reversing": "none", - "safe-to-defer": "none", - "scheduled-full-refresh": "none", - "scope": "none", - "scorecard": "none", - "setup": "none", - "setup-blocker": "none", - "softened-for-flip-churn": "none", - "softened-for-noise": "none", - "softened-for-reopen-risk": "none", - "stable": "none", - "stale": "none", - "stale-baseline": "none", - "stalled": "none", - "status": "none", - "sticky": "none", - "summary": "none", - "support": "none", - "supporting": "none", - "supporting-caution": "none", - "supporting-clearance": "none", - "supporting-confirmation": "none", - "supporting-normalization": "none", - "sustained": "none", - "sustained-caution": "none", - "sustained-clearance": "none", - "sustained-clearance-rebuild": "none", - "sustained-clearance-rebuild-reentry": "none", - "sustained-clearance-rebuild-reentry-rerererestore": "none", - "sustained-clearance-rebuild-reentry-rererestore": "none", - "sustained-clearance-rebuild-reentry-rerestore": "none", - "sustained-clearance-rebuild-reentry-restore": "none", - "sustained-clearance-reentry": "none", - "sustained-confirmation": "none", - "sustained-confirmation-rebuild": "none", - "sustained-confirmation-rebuild-reentry": "none", - "sustained-confirmation-rebuild-reentry-rerererestore": "none", - "sustained-confirmation-rebuild-reentry-rererestore": "none", - "sustained-confirmation-rebuild-reentry-rerestore": "none", - "sustained-confirmation-rebuild-reentry-restore": "none", - "sustained-confirmation-reentry": "none", - "sustained-support": "none", - "title": "none", - "unavailable": "none", - "unknown": "none", - "unstable": "none", - "urgency": "none", - "urgent": "none", - "useful-caution": "none", - "username": "none", - "verify-first": "none", - "watch": "none", - "worsening": "none" - }, - "src.operator_resolution_trend._closure_forecast_reset_side_from_status": { - "": "none", - "act-now": "none", - "act-with-review": "none", - "active-debt": "none", - "applied": "none", - "archived": "none", - "attempted": "none", - "audits": "none", - "blocked": "none", - "blocked-operator-item": "none", - "building": "none", - "campaign": "none", - "candidate": "none", - "caution": "none", - "chronic": "none", - "churn": "none", - "class": "none", - "class-debt": "none", - "clear-risk": "none", - "clear-risk-softened": "none", - "clear-risk-strengthened": "none", - "clearance": "none", - "clearance-decayed": "none", - "clearance-like": "none", - "clearance-reset": "clearance", - "clearance-softened": "clearance", - "cleared": "none", - "clearing": "none", - "confirm-soon": "none", - "confirm-support-softened": "none", - "confirm-support-strengthened": "none", - "confirmation": "none", - "confirmation-decayed": "none", - "confirmation-like": "none", - "confirmation-reset": "confirmation", - "confirmation-softened": "confirmation", - "confirmed": "none", - "confirmed-caution": "none", - "confirmed-clearance": "none", - "confirmed-confirmation": "none", - "confirmed-support": "none", - "counts": "none", - "debt": "none", - "deferred": "none", - "direction": "none", - "drift-or-regression": "none", - "drifting": "none", - "earned": "none", - "effect": "none", - "expire-risk": "none", - "expired": "none", - "filter-or-profile-changed": "none", - "fresh": "none", - "full-refresh-due": "none", - "governance": "none", - "headline": "none", - "healthy": "none", - "high": "none", - "hold": "none", - "holding": "none", - "holding-clearance": "none", - "holding-clearance-rebuild": "none", - "holding-clearance-rebuild-reentry": "none", - "holding-clearance-rebuild-reentry-rerererestore": "none", - "holding-clearance-rebuild-reentry-rererestore": "none", - "holding-clearance-rebuild-reentry-rerestore": "none", - "holding-clearance-rebuild-reentry-restore": "none", - "holding-clearance-reentry": "none", - "holding-confirmation": "none", - "holding-confirmation-rebuild": "none", - "holding-confirmation-rebuild-reentry": "none", - "holding-confirmation-rebuild-reentry-rerererestore": "none", - "holding-confirmation-rebuild-reentry-rererestore": "none", - "holding-confirmation-rebuild-reentry-rerestore": "none", - "holding-confirmation-rebuild-reentry-restore": "none", - "holding-confirmation-reentry": "none", - "improving": "none", - "incremental": "none", - "insufficient-data": "none", - "items": "none", - "just-reacquired": "none", - "just-rebuilt": "none", - "just-reentered": "none", - "just-rerererestored": "none", - "just-rererestored": "none", - "just-rerestored": "none", - "just-restored": "none", - "key": "none", - "kind": "none", - "label": "none", - "lane": "none", - "low": "none", - "manual": "none", - "manual-review-ready": "none", - "medium": "none", - "metadata": "none", - "missing-trustworthy-baseline": "none", - "mixed": "none", - "mixed-age": "none", - "monitor": "none", - "name": "none", - "neutral": "none", - "new": "none", - "no-change": "none", - "noisy": "none", - "none": "none", - "normalization-boosted": "none", - "normalization-decayed": "none", - "normalization-softened": "none", - "normalized": "none", - "one-off-noise": "none", - "oscillating": "none", - "overcautious": "none", - "pending-caution": "none", - "pending-clearance": "none", - "pending-clearance-reacquisition": "none", - "pending-clearance-rebuild": "none", - "pending-clearance-rebuild-reentry": "none", - "pending-clearance-rebuild-reentry-rerererestore": "none", - "pending-clearance-rebuild-reentry-rererestore": "none", - "pending-clearance-rebuild-reentry-rerestore": "none", - "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", - "pending-confirmation": "none", - "pending-confirmation-reacquisition": "none", - "pending-confirmation-rebuild": "none", - "pending-confirmation-rebuild-reentry": "none", - "pending-confirmation-rebuild-reentry-rerererestore": "none", - "pending-confirmation-rebuild-reentry-rererestore": "none", - "pending-confirmation-rebuild-reentry-rerestore": "none", - "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", - "pending-support": "none", - "persisting": "none", - "policy-debt": "none", - "policy-debt-decayed": "none", - "policy-debt-softened": "none", - "policy-debt-strengthened": "none", - "portfolio": "none", - "priority": "none", - "quiet": "none", - "quieted": "none", - "re-re-re-restore": "none", - "re-re-re-restored": "none", - "re-re-re-restoring": "none", - "re-re-restore": "none", - "re-re-restored": "none", - "re-re-restoring": "none", - "reacquired": "none", - "reacquired-clearance": "none", - "reacquired-confirmation": "none", - "reacquiring-clearance": "none", - "reacquiring-confirmation": "none", - "ready": "none", - "reason": "none", - "rebuilding-clearance-reentry": "none", - "rebuilding-confirmation-reentry": "none", - "rebuilt-clearance-reentry": "none", - "rebuilt-confirmation-reentry": "none", - "recovering": "none", - "recovering-clearance": "none", - "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rererestore-reset": "none", - "recovering-clearance-rebuild-reentry-rerestore-reset": "none", - "recovering-clearance-rebuild-reentry-reset": "none", - "recovering-clearance-rebuild-reentry-restore-reset": "none", - "recovering-clearance-rebuild-reset": "none", - "recovering-clearance-reentry-reset": "none", - "recovering-clearance-reset": "none", - "recovering-confirmation": "none", - "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", - "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", - "recovering-confirmation-rebuild-reentry-reset": "none", - "recovering-confirmation-rebuild-reentry-restore-reset": "none", - "recovering-confirmation-rebuild-reset": "none", - "recovering-confirmation-reentry-reset": "none", - "recovering-confirmation-reset": "none", - "reentered-clearance": "none", - "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", - "reentered-confirmation-rebuild": "none", - "reentering-clearance": "none", - "reentering-clearance-rebuild": "none", - "reentering-confirmation": "none", - "reentering-confirmation-rebuild": "none", - "reopened": "none", - "repo": "none", - "rerererestore": "none", - "rerererestored": "none", - "rerererestored-clearance-rebuild-reentry": "none", - "rerererestored-confirmation-rebuild-reentry": "none", - "rerererestoring": "none", - "rerererestoring-clearance-rebuild-reentry": "none", - "rerererestoring-confirmation-rebuild-reentry": "none", - "rererestore": "none", - "rererestored": "none", - "rererestored-clearance-rebuild-reentry": "none", - "rererestored-confirmation-rebuild-reentry": "none", - "rererestoring": "none", - "rererestoring-clearance-rebuild-reentry": "none", - "rererestoring-confirmation-rebuild-reentry": "none", - "rerestored-clearance-rebuild-reentry": "none", - "rerestored-confirmation-rebuild-reentry": "none", - "rerestoring-clearance-rebuild-reentry": "none", - "rerestoring-confirmation-rebuild-reentry": "none", - "resolving": "none", - "restored-clearance-rebuild-reentry": "none", - "restored-confirmation-rebuild-reentry": "none", - "restoring-clearance-rebuild-reentry": "none", - "restoring-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", "retired": "none", "reversing": "none", "safe-to-defer": "none", @@ -5301,6 +2126,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -5482,6 +2310,7 @@ "priority": "neutral", "quiet": "neutral", "quieted": "neutral", + "re": "neutral", "re-re-re-restore": "neutral", "re-re-re-restored": "neutral", "re-re-re-restoring": "neutral", @@ -5568,6 +2397,9 @@ "stalled": "neutral", "status": "neutral", "sticky": "neutral", + "store": "neutral", + "stored": "neutral", + "storing": "neutral", "summary": "neutral", "support": "neutral", "supporting": "neutral", @@ -5749,6 +2581,7 @@ "priority": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "quiet": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "quieted": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", + "re": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "re-re-re-restore": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "re-re-re-restored": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "re-re-re-restoring": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", @@ -5835,6 +2668,9 @@ "stalled": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "status": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "sticky": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", + "store": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", + "stored": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", + "storing": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "summary": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "support": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", "supporting": "The confidence model is still too lightly exercised to judge whether the current signal is earning trust.", @@ -6016,6 +2852,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -6102,6 +2939,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -6283,6 +3123,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -6369,6 +3210,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -6550,6 +3394,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -6636,6 +3481,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -6817,6 +3665,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -6903,6 +3752,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -7084,6 +3936,7 @@ "priority": "priority", "quiet": "quiet", "quieted": "quieted", + "re": "re", "re-re-re-restore": "re-re-re-re-restore", "re-re-re-restored": "re-re-re-re-restored", "re-re-re-restoring": "re-re-re-re-restoring", @@ -7170,6 +4023,9 @@ "stalled": "stalled", "status": "status", "sticky": "sticky", + "store": "store", + "stored": "stored", + "storing": "storing", "summary": "summary", "support": "support", "supporting": "supporting", @@ -7351,6 +4207,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -7437,6 +4294,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", @@ -7618,6 +4478,7 @@ "priority": "priority", "quiet": "quiet", "quieted": "quieted", + "re": "re", "re-re-re-restore": "re-re-re-re-restore", "re-re-re-restored": "re-re-re-re-restored", "re-re-re-restoring": "re-re-re-re-restoring", @@ -7704,6 +4565,9 @@ "stalled": "stalled", "status": "status", "sticky": "sticky", + "store": "store", + "stored": "stored", + "storing": "storing", "summary": "summary", "support": "support", "supporting": "supporting", @@ -7742,7 +4606,2446 @@ "watch": "watch", "worsening": "worsening" }, - "src.operator_trend_closure_forecast_reset_controls.closure_forecast_reset_side_from_status": { + "src.operator_trend_closure_forecast_reset_controls.closure_forecast_reset_side_from_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "clearance", + "clearance-softened": "clearance", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "confirmation", + "confirmation-softened": "confirmation", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "clearance", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "confirmation", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "confirmation", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "clearance", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "confirmation", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "clearance", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "confirmation", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "clearance", + "rererestored-confirmation-rebuild-reentry": "confirmation", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_side_from_refresh_recovery_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "clearance", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "confirmation", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "clearance", + "rererestoring-confirmation-rebuild-reentry": "confirmation", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_rebuild_side_from_persistence_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "clearance", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "confirmation", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "clearance", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "confirmation", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_rebuild_side_from_recovery_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "clearance", + "rebuilding-confirmation-reentry": "confirmation", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "clearance", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "confirmation", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_rebuild_side_from_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "clearance", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "confirmation", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "clearance", + "rebuilt-confirmation-reentry": "confirmation", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_side_from_persistence_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "clearance", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "confirmation", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "none", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "none", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "none", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "none", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "clearance", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "confirmation", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_side_from_recovery_status": { + "": "none", + "act-now": "none", + "act-with-review": "none", + "active-debt": "none", + "applied": "none", + "archived": "none", + "attempted": "none", + "audits": "none", + "blocked": "none", + "blocked-operator-item": "none", + "building": "none", + "campaign": "none", + "candidate": "none", + "caution": "none", + "chronic": "none", + "churn": "none", + "class": "none", + "class-debt": "none", + "clear-risk": "none", + "clear-risk-softened": "none", + "clear-risk-strengthened": "none", + "clearance": "none", + "clearance-decayed": "none", + "clearance-like": "none", + "clearance-reset": "none", + "clearance-softened": "none", + "cleared": "none", + "clearing": "none", + "confirm-soon": "none", + "confirm-support-softened": "none", + "confirm-support-strengthened": "none", + "confirmation": "none", + "confirmation-decayed": "none", + "confirmation-like": "none", + "confirmation-reset": "none", + "confirmation-softened": "none", + "confirmed": "none", + "confirmed-caution": "none", + "confirmed-clearance": "none", + "confirmed-confirmation": "none", + "confirmed-support": "none", + "counts": "none", + "debt": "none", + "deferred": "none", + "direction": "none", + "drift-or-regression": "none", + "drifting": "none", + "earned": "none", + "effect": "none", + "expire-risk": "none", + "expired": "none", + "filter-or-profile-changed": "none", + "fresh": "none", + "full-refresh-due": "none", + "governance": "none", + "headline": "none", + "healthy": "none", + "high": "none", + "hold": "none", + "holding": "none", + "holding-clearance": "none", + "holding-clearance-rebuild": "none", + "holding-clearance-rebuild-reentry": "none", + "holding-clearance-rebuild-reentry-rerererestore": "none", + "holding-clearance-rebuild-reentry-rererestore": "none", + "holding-clearance-rebuild-reentry-rerestore": "none", + "holding-clearance-rebuild-reentry-restore": "none", + "holding-clearance-reentry": "none", + "holding-confirmation": "none", + "holding-confirmation-rebuild": "none", + "holding-confirmation-rebuild-reentry": "none", + "holding-confirmation-rebuild-reentry-rerererestore": "none", + "holding-confirmation-rebuild-reentry-rererestore": "none", + "holding-confirmation-rebuild-reentry-rerestore": "none", + "holding-confirmation-rebuild-reentry-restore": "none", + "holding-confirmation-reentry": "none", + "improving": "none", + "incremental": "none", + "insufficient-data": "none", + "items": "none", + "just-reacquired": "none", + "just-rebuilt": "none", + "just-reentered": "none", + "just-rerererestored": "none", + "just-rererestored": "none", + "just-rerestored": "none", + "just-restored": "none", + "key": "none", + "kind": "none", + "label": "none", + "lane": "none", + "low": "none", + "manual": "none", + "manual-review-ready": "none", + "medium": "none", + "metadata": "none", + "missing-trustworthy-baseline": "none", + "mixed": "none", + "mixed-age": "none", + "monitor": "none", + "name": "none", + "neutral": "none", + "new": "none", + "no-change": "none", + "noisy": "none", + "none": "none", + "normalization-boosted": "none", + "normalization-decayed": "none", + "normalization-softened": "none", + "normalized": "none", + "one-off-noise": "none", + "oscillating": "none", + "overcautious": "none", + "pending-caution": "none", + "pending-clearance": "none", + "pending-clearance-reacquisition": "none", + "pending-clearance-rebuild": "none", + "pending-clearance-rebuild-reentry": "none", + "pending-clearance-rebuild-reentry-rerererestore": "none", + "pending-clearance-rebuild-reentry-rererestore": "none", + "pending-clearance-rebuild-reentry-rerestore": "none", + "pending-clearance-rebuild-reentry-restore": "none", + "pending-clearance-reentry": "none", + "pending-confirmation": "none", + "pending-confirmation-reacquisition": "none", + "pending-confirmation-rebuild": "none", + "pending-confirmation-rebuild-reentry": "none", + "pending-confirmation-rebuild-reentry-rerererestore": "none", + "pending-confirmation-rebuild-reentry-rererestore": "none", + "pending-confirmation-rebuild-reentry-rerestore": "none", + "pending-confirmation-rebuild-reentry-restore": "none", + "pending-confirmation-reentry": "none", + "pending-support": "none", + "persisting": "none", + "policy-debt": "none", + "policy-debt-decayed": "none", + "policy-debt-softened": "none", + "policy-debt-strengthened": "none", + "portfolio": "none", + "priority": "none", + "quiet": "none", + "quieted": "none", + "re": "none", + "re-re-re-restore": "none", + "re-re-re-restored": "none", + "re-re-re-restoring": "none", + "re-re-restore": "none", + "re-re-restored": "none", + "re-re-restoring": "none", + "reacquired": "none", + "reacquired-clearance": "none", + "reacquired-confirmation": "none", + "reacquiring-clearance": "none", + "reacquiring-confirmation": "none", + "ready": "none", + "reason": "none", + "rebuilding-clearance-reentry": "none", + "rebuilding-confirmation-reentry": "none", + "rebuilt-clearance-reentry": "none", + "rebuilt-confirmation-reentry": "none", + "recovering": "none", + "recovering-clearance": "none", + "recovering-clearance-rebuild-reentry-rerererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rererestore-reset": "none", + "recovering-clearance-rebuild-reentry-rerestore-reset": "none", + "recovering-clearance-rebuild-reentry-reset": "none", + "recovering-clearance-rebuild-reentry-restore-reset": "none", + "recovering-clearance-rebuild-reset": "none", + "recovering-clearance-reentry-reset": "none", + "recovering-clearance-reset": "clearance", + "recovering-confirmation": "none", + "recovering-confirmation-rebuild-reentry-rerererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rererestore-reset": "none", + "recovering-confirmation-rebuild-reentry-rerestore-reset": "none", + "recovering-confirmation-rebuild-reentry-reset": "none", + "recovering-confirmation-rebuild-reentry-restore-reset": "none", + "recovering-confirmation-rebuild-reset": "none", + "recovering-confirmation-reentry-reset": "none", + "recovering-confirmation-reset": "confirmation", + "reentered-clearance": "none", + "reentered-clearance-rebuild": "none", + "reentered-confirmation": "none", + "reentered-confirmation-rebuild": "none", + "reentering-clearance": "clearance", + "reentering-clearance-rebuild": "none", + "reentering-confirmation": "confirmation", + "reentering-confirmation-rebuild": "none", + "reopened": "none", + "repo": "none", + "rerererestore": "none", + "rerererestored": "none", + "rerererestored-clearance-rebuild-reentry": "none", + "rerererestored-confirmation-rebuild-reentry": "none", + "rerererestoring": "none", + "rerererestoring-clearance-rebuild-reentry": "none", + "rerererestoring-confirmation-rebuild-reentry": "none", + "rererestore": "none", + "rererestored": "none", + "rererestored-clearance-rebuild-reentry": "none", + "rererestored-confirmation-rebuild-reentry": "none", + "rererestoring": "none", + "rererestoring-clearance-rebuild-reentry": "none", + "rererestoring-confirmation-rebuild-reentry": "none", + "rerestored-clearance-rebuild-reentry": "none", + "rerestored-confirmation-rebuild-reentry": "none", + "rerestoring-clearance-rebuild-reentry": "none", + "rerestoring-confirmation-rebuild-reentry": "none", + "resolving": "none", + "restored-clearance-rebuild-reentry": "none", + "restored-confirmation-rebuild-reentry": "none", + "restoring-clearance-rebuild-reentry": "none", + "restoring-confirmation-rebuild-reentry": "none", + "retired": "none", + "reversing": "none", + "safe-to-defer": "none", + "scheduled-full-refresh": "none", + "scope": "none", + "scorecard": "none", + "setup": "none", + "setup-blocker": "none", + "softened-for-flip-churn": "none", + "softened-for-noise": "none", + "softened-for-reopen-risk": "none", + "stable": "none", + "stale": "none", + "stale-baseline": "none", + "stalled": "none", + "status": "none", + "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", + "summary": "none", + "support": "none", + "supporting": "none", + "supporting-caution": "none", + "supporting-clearance": "none", + "supporting-confirmation": "none", + "supporting-normalization": "none", + "sustained": "none", + "sustained-caution": "none", + "sustained-clearance": "none", + "sustained-clearance-rebuild": "none", + "sustained-clearance-rebuild-reentry": "none", + "sustained-clearance-rebuild-reentry-rerererestore": "none", + "sustained-clearance-rebuild-reentry-rererestore": "none", + "sustained-clearance-rebuild-reentry-rerestore": "none", + "sustained-clearance-rebuild-reentry-restore": "none", + "sustained-clearance-reentry": "none", + "sustained-confirmation": "none", + "sustained-confirmation-rebuild": "none", + "sustained-confirmation-rebuild-reentry": "none", + "sustained-confirmation-rebuild-reentry-rerererestore": "none", + "sustained-confirmation-rebuild-reentry-rererestore": "none", + "sustained-confirmation-rebuild-reentry-rerestore": "none", + "sustained-confirmation-rebuild-reentry-restore": "none", + "sustained-confirmation-reentry": "none", + "sustained-support": "none", + "title": "none", + "unavailable": "none", + "unknown": "none", + "unstable": "none", + "urgency": "none", + "urgent": "none", + "useful-caution": "none", + "username": "none", + "verify-first": "none", + "watch": "none", + "worsening": "none" + }, + "src.operator_trend_support.closure_forecast_reset_reentry_side_from_status": { "": "none", "act-now": "none", "act-with-review": "none", @@ -7767,8 +7070,8 @@ "clearance": "none", "clearance-decayed": "none", "clearance-like": "none", - "clearance-reset": "clearance", - "clearance-softened": "clearance", + "clearance-reset": "none", + "clearance-softened": "none", "cleared": "none", "clearing": "none", "confirm-soon": "none", @@ -7777,8 +7080,8 @@ "confirmation": "none", "confirmation-decayed": "none", "confirmation-like": "none", - "confirmation-reset": "confirmation", - "confirmation-softened": "confirmation", + "confirmation-reset": "none", + "confirmation-softened": "none", "confirmed": "none", "confirmed-caution": "none", "confirmed-clearance": "none", @@ -7865,7 +7168,7 @@ "pending-clearance-rebuild-reentry-rererestore": "none", "pending-clearance-rebuild-reentry-rerestore": "none", "pending-clearance-rebuild-reentry-restore": "none", - "pending-clearance-reentry": "none", + "pending-clearance-reentry": "clearance", "pending-confirmation": "none", "pending-confirmation-reacquisition": "none", "pending-confirmation-rebuild": "none", @@ -7874,7 +7177,7 @@ "pending-confirmation-rebuild-reentry-rererestore": "none", "pending-confirmation-rebuild-reentry-rerestore": "none", "pending-confirmation-rebuild-reentry-restore": "none", - "pending-confirmation-reentry": "none", + "pending-confirmation-reentry": "confirmation", "pending-support": "none", "persisting": "none", "policy-debt": "none", @@ -7885,6 +7188,7 @@ "priority": "none", "quiet": "none", "quieted": "none", + "re": "none", "re-re-re-restore": "none", "re-re-re-restored": "none", "re-re-re-restoring": "none", @@ -7921,9 +7225,9 @@ "recovering-confirmation-rebuild-reset": "none", "recovering-confirmation-reentry-reset": "none", "recovering-confirmation-reset": "none", - "reentered-clearance": "none", + "reentered-clearance": "clearance", "reentered-clearance-rebuild": "none", - "reentered-confirmation": "none", + "reentered-confirmation": "confirmation", "reentered-confirmation-rebuild": "none", "reentering-clearance": "none", "reentering-clearance-rebuild": "none", @@ -7971,6 +7275,9 @@ "stalled": "none", "status": "none", "sticky": "none", + "store": "none", + "stored": "none", + "storing": "none", "summary": "none", "support": "none", "supporting": "none", diff --git a/tests/test_app_cli_boundary.py b/tests/test_app_cli_boundary.py new file mode 100644 index 0000000..da2efcf --- /dev/null +++ b/tests/test_app_cli_boundary.py @@ -0,0 +1,33 @@ +"""Architecture guardrail for the CLI-to-application dependency direction.""" + +from __future__ import annotations + +import ast +from pathlib import Path + + +APP_ROOT = Path(__file__).parent.parent / "src" / "app" + + +def _cli_imports(path: Path) -> list[str]: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + violations: list[str] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + violations.extend(alias.name for alias in node.names if alias.name == "src.cli") + elif isinstance(node, ast.ImportFrom): + if node.module == "src.cli": + violations.append("from src.cli") + elif node.module == "src" and any(alias.name == "cli" for alias in node.names): + violations.append("from src import cli") + return violations + + +def test_app_layer_does_not_depend_on_cli() -> None: + """CLI dispatches into app flows; app flows must not import the dispatcher.""" + violations = { + path.relative_to(APP_ROOT).as_posix(): _cli_imports(path) + for path in APP_ROOT.rglob("*.py") + if _cli_imports(path) + } + assert violations == {} diff --git a/tests/test_cache.py b/tests/test_cache.py index ebe89da..0cb0fec 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -53,6 +53,27 @@ def test_params_differentiate_keys(self, tmp_path): assert result1 == [{"sha": "abc"}] assert result2 == [{"sha": "def"}] + def test_put_skips_payloads_that_contain_credentials(self, tmp_path): + cache = ResponseCache(cache_dir=tmp_path / "cache", ttl=3600) + url = "https://api.github.com/repos/user/repo" + + cache.put( + url, + {"access_token": "secret-param", "per_page": "10"}, + {"name": "repo", "nested": {"client_secret": "secret-value"}}, + ) + + assert not cache._path(url, {"access_token": "secret-param", "per_page": "10"}).exists() + + def test_put_preserves_noncredential_secret_scanning_shape(self, tmp_path): + cache = ResponseCache(cache_dir=tmp_path / "cache", ttl=3600) + url = "https://api.github.com/repos/user/repo" + response = {"security_and_analysis": {"secret_scanning": {"status": "enabled"}}} + + cache.put(url, None, response) + + assert cache.get(url, None) == response + def test_cache_creates_dir(self, tmp_path): cache_dir = tmp_path / "deep" / "nested" / "cache" ResponseCache(cache_dir=cache_dir, ttl=3600) diff --git a/tests/test_cli_hardening.py b/tests/test_cli_hardening.py index ef7f004..4b6bf78 100644 --- a/tests/test_cli_hardening.py +++ b/tests/test_cli_hardening.py @@ -9,8 +9,11 @@ import pytest from src import cli +from src.app import auto_apply, run_audit from src.baseline_context import build_baseline_context from src.models import AnalyzerResult, AuditReport, RepoAudit +from src.report_scorecards import apply_scorecards +from src.report_state import report_from_dict def _make_args(**overrides) -> Namespace: @@ -90,34 +93,34 @@ def _make_args(**overrides) -> Namespace: def test_analysis_worker_count_defaults_to_reliable_single_worker(monkeypatch): monkeypatch.delenv("GITHUB_REPO_AUDITOR_ANALYSIS_WORKERS", raising=False) - assert cli._analysis_worker_count(_make_args()) == 1 + assert run_audit._analysis_worker_count(_make_args()) == 1 def test_analysis_worker_count_uses_bounded_cli_value(): - assert cli._analysis_worker_count(_make_args(analysis_workers=2)) == 2 - assert cli._analysis_worker_count(_make_args(analysis_workers=99)) == cli.MAX_ANALYSIS_WORKERS + assert run_audit._analysis_worker_count(_make_args(analysis_workers=2)) == 2 + assert run_audit._analysis_worker_count(_make_args(analysis_workers=99)) == run_audit.MAX_ANALYSIS_WORKERS def test_analysis_worker_count_reads_env_when_flag_missing(monkeypatch): monkeypatch.setenv("GITHUB_REPO_AUDITOR_ANALYSIS_WORKERS", "3") - assert cli._analysis_worker_count(_make_args(analysis_workers=None)) == 3 + assert run_audit._analysis_worker_count(_make_args(analysis_workers=None)) == 3 def test_analysis_progress_is_disabled_when_stderr_is_not_tty(monkeypatch): monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: False) - assert cli._use_analysis_progress(4) is False + assert run_audit._use_analysis_progress(4) is False def test_analysis_progress_is_enabled_for_parallel_tty(monkeypatch): monkeypatch.setattr(cli.sys.stderr, "isatty", lambda: True) - assert cli._use_analysis_progress(4) is True - assert cli._use_analysis_progress(1) is False + assert run_audit._use_analysis_progress(4) is True + assert run_audit._use_analysis_progress(1) is False def test_analyzer_cache_is_single_worker_only(): - assert cli._use_analyzer_cache(_make_args(no_analyzer_cache=False), 1) is True - assert cli._use_analyzer_cache(_make_args(no_analyzer_cache=False), 2) is False - assert cli._use_analyzer_cache(_make_args(no_analyzer_cache=True), 1) is False + assert run_audit._use_analyzer_cache(_make_args(no_analyzer_cache=False), 1) is True + assert run_audit._use_analyzer_cache(_make_args(no_analyzer_cache=False), 2) is False + assert run_audit._use_analyzer_cache(_make_args(no_analyzer_cache=True), 1) is False class FakeParser: @@ -238,9 +241,9 @@ def test_main_forwards_scoring_profile_to_targeted_audit(monkeypatch, sample_met captured: dict[str, object] = {} monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_scoring_profile", lambda name: ({"readme": 1.5}, "focus")) - monkeypatch.setattr(cli, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) - monkeypatch.setattr(cli, "_run_targeted_audit", lambda *a, **k: captured.update(k)) + monkeypatch.setattr(run_audit, "_load_scoring_profile", lambda name: ({"readme": 1.5}, "focus")) + monkeypatch.setattr(run_audit, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) + monkeypatch.setattr(run_audit, "_run_targeted_audit", lambda *a, **k: captured.update(k)) cli.main() @@ -374,9 +377,9 @@ def test_main_forwards_scoring_profile_to_incremental_audit(monkeypatch, sample_ captured: dict[str, object] = {} monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_scoring_profile", lambda name: ({"readme": 1.5}, "focus")) - monkeypatch.setattr(cli, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) - monkeypatch.setattr(cli, "_run_incremental_audit", lambda *a, **k: captured.update(k)) + monkeypatch.setattr(run_audit, "_load_scoring_profile", lambda name: ({"readme": 1.5}, "focus")) + monkeypatch.setattr(run_audit, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) + monkeypatch.setattr(run_audit, "_run_incremental_audit", lambda *a, **k: captured.update(k)) cli.main() @@ -402,9 +405,9 @@ def test_main_watch_uses_chosen_watch_plan(monkeypatch, sample_metadata, tmp_pat monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) monkeypatch.setattr("src.recurring_review.choose_watch_plan", lambda *_a, **_k: watch_plan) monkeypatch.setattr("src.watch.run_watch_loop", lambda audit_fn, interval=0: audit_fn()) - monkeypatch.setattr(cli, "_load_scoring_profile", lambda name: (None, "default")) - monkeypatch.setattr(cli, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) - monkeypatch.setattr(cli, "_run_incremental_audit", lambda *a, **k: captured.update(k)) + monkeypatch.setattr(run_audit, "_load_scoring_profile", lambda name: (None, "default")) + monkeypatch.setattr(run_audit, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) + monkeypatch.setattr(run_audit, "_run_incremental_audit", lambda *a, **k: captured.update(k)) cli.main() @@ -452,7 +455,7 @@ def test_apply_scorecards_populates_report(monkeypatch, sample_metadata, tmp_pat report = AuditReport.from_audits("testuser", [audit], [], 1) report.operator_queue = [{"repo": "test-repo", "title": "Review test-repo"}] - updated = cli._apply_scorecards(report, _make_args(scorecards=scorecards_path)) + updated = apply_scorecards(report, _make_args(scorecards=scorecards_path)) assert updated.audits[0].scorecard["program"] == "maintain" assert updated.scorecards_summary["status_counts"]["below-target"] == 1 @@ -505,7 +508,7 @@ def test_apply_scorecards_refreshes_maintain_intent_alignment(sample_metadata, t } ] - updated = cli._apply_scorecards(report, _make_args(scorecards=scorecards_path)) + updated = apply_scorecards(report, _make_args(scorecards=scorecards_path)) assert updated.audits[0].scorecard["status"] == "on-track" assert updated.audits[0].portfolio_catalog["intent_alignment"] == "aligned" @@ -585,7 +588,9 @@ def test_control_center_snapshot_rehydrates_portfolio_context( "operator_queue": [dict(report.operator_queue[0])], } - updated = cli._enrich_control_center_snapshot_from_report( + from src.control_center_snapshot import enrich_control_center_snapshot_from_report + + updated = enrich_control_center_snapshot_from_report( report.to_dict(), snapshot, _make_args(catalog=catalog_path, scorecards=scorecards_path), @@ -642,7 +647,9 @@ def test_control_center_snapshot_repairs_missing_path_basename_catalog_context( ] snapshot = {"operator_summary": {}, "operator_queue": [dict(report.operator_queue[0])]} - updated = cli._enrich_control_center_snapshot_from_report( + from src.control_center_snapshot import enrich_control_center_snapshot_from_report + + updated = enrich_control_center_snapshot_from_report( report.to_dict(), snapshot, _make_args(catalog=catalog_path), @@ -674,7 +681,7 @@ class _Result: def test_main_approval_center_writes_artifacts_without_apply(monkeypatch, tmp_path, sample_metadata, capsys): args = _make_args(approval_center=True, output_dir=str(tmp_path)) - report = cli._report_from_dict(_make_report_dict(sample_metadata)) + report = report_from_dict(_make_report_dict(sample_metadata)) approval_json = tmp_path / "approval-center-testuser-2026-03-29.json" approval_md = tmp_path / "approval-center-testuser-2026-03-29.md" @@ -695,11 +702,13 @@ def _write_approval_center_artifacts(report_arg, output_dir, *, approval_view): monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) monkeypatch.setattr( - cli, - "_refresh_latest_report_state", + "src.app.approval_center.refresh_latest_report_state", lambda _output_dir, _args: (tmp_path / "audit-report-testuser-2026-03-29.json", {}, report), ) - monkeypatch.setattr(cli, "_write_approval_center_artifacts", _write_approval_center_artifacts) + monkeypatch.setattr( + "src.app.approval_center.write_approval_center_artifacts", + _write_approval_center_artifacts, + ) cli.main() @@ -718,8 +727,11 @@ def test_main_control_center_writes_artifacts_without_audit(monkeypatch, tmp_pat report_path.write_text("{}") monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_latest_report", lambda _output_dir: (report_path, report_data)) - monkeypatch.setattr("src.history.find_previous", lambda *_args, **_kwargs: None) + monkeypatch.setattr( + "src.app.control_center.load_latest_report", + lambda _output_dir: (report_path, report_data), + ) + monkeypatch.setattr("src.app.control_center.find_previous", lambda *_args, **_kwargs: None) cli.main() @@ -754,8 +766,11 @@ def test_main_control_center_suppresses_queue_when_portfolio_truth_is_newer( ) monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_latest_report", lambda _output_dir: (report_path, report_data)) - monkeypatch.setattr("src.history.find_previous", lambda *_args, **_kwargs: None) + monkeypatch.setattr( + "src.app.control_center.load_latest_report", + lambda _output_dir: (report_path, report_data), + ) + monkeypatch.setattr("src.app.control_center.find_previous", lambda *_args, **_kwargs: None) cli.main() @@ -767,14 +782,16 @@ def test_main_control_center_suppresses_queue_when_portfolio_truth_is_newer( def test_control_center_default_print_hides_experiment_items() -> None: - assert cli._should_print_control_center_item( + from src.operator_control_center_artifacts import should_print_control_center_item + + assert should_print_control_center_item( { "repo": "active-repo", "operating_path": "maintain", "portfolio_catalog": {"lifecycle_state": "active"}, } ) - assert not cli._should_print_control_center_item( + assert not should_print_control_center_item( { "repo": "experiment-repo", "operating_path": "experiment", @@ -788,7 +805,9 @@ def test_control_center_default_print_hides_experiment_items() -> None: def test_control_center_default_view_hides_archive_items() -> None: - assert not cli._should_print_control_center_item( + from src.operator_control_center_artifacts import should_print_control_center_item + + assert not should_print_control_center_item( { "repo": "archive-repo", "operating_path": "archive", @@ -822,7 +841,9 @@ def test_control_center_artifact_filter_drops_archive_queue_items() -> None: ], } - cli._filter_control_center_snapshot_for_default_view(snapshot) + from src.operator_control_center_artifacts import filter_snapshot_for_default_view + + filter_snapshot_for_default_view(snapshot) assert [item["repo"] for item in snapshot["operator_queue"]] == ["active-repo"] @@ -831,7 +852,7 @@ def test_main_control_center_requires_latest_report(monkeypatch): args = _make_args(control_center=True) monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_latest_report", lambda _output_dir: (None, None)) + monkeypatch.setattr("src.app.control_center.load_latest_report", lambda _output_dir: (None, None)) with pytest.raises(SystemExit) as exc: cli.main() @@ -850,7 +871,7 @@ def test_auto_apply_dry_run_prints_automation_trust_bar( report_data["operator_summary"] = { "decision_quality_v1": {"decision_quality_status": "trusted"} } - report = cli._report_from_dict(report_data) + report = report_from_dict(report_data) truth_path = tmp_path / "portfolio-truth-latest.json" truth_path.write_text( json.dumps( @@ -877,8 +898,8 @@ def test_auto_apply_dry_run_prints_automation_trust_bar( ) monkeypatch.setattr( - cli, - "_refresh_latest_report_state", + auto_apply, + "refresh_latest_report_state", lambda _output_dir, _args: (tmp_path / "audit-report-testuser-2026-03-29.json", {}, report), ) monkeypatch.setattr( @@ -886,7 +907,7 @@ def test_auto_apply_dry_run_prints_automation_trust_bar( lambda *_args, **_kwargs: {"approval_ledger": []}, ) - cli._run_auto_apply_approved_mode(args, tmp_path) + auto_apply.run_auto_apply_approved_mode(args, tmp_path) captured = capsys.readouterr() combined = captured.out + captured.err @@ -924,7 +945,7 @@ def test_auto_apply_dry_run_does_not_call_github_writeback( {"campaign_type": "promotion-push", "automation_posture": "approval-first"} ], } - report = cli._report_from_dict(report_data) + report = report_from_dict(report_data) (tmp_path / "portfolio-truth-latest.json").write_text( json.dumps( { @@ -939,8 +960,8 @@ def test_auto_apply_dry_run_does_not_call_github_writeback( ) ) monkeypatch.setattr( - cli, - "_refresh_latest_report_state", + auto_apply, + "refresh_latest_report_state", lambda _output_dir, _args: (tmp_path / "audit-report-testuser-2026-03-29.json", {}, report), ) monkeypatch.setattr( @@ -982,7 +1003,7 @@ def _apply_github_writeback(*_args, **_kwargs): monkeypatch.setattr("src.ops_writeback.apply_github_writeback", _apply_github_writeback) - cli._run_auto_apply_approved_mode(args, tmp_path) + auto_apply.run_auto_apply_approved_mode(args, tmp_path) captured = capsys.readouterr() normalized = " ".join((captured.out + captured.err).split()) @@ -998,7 +1019,7 @@ def test_main_approve_governance_captures_local_approval(monkeypatch, tmp_path, approval_note="looks good", output_dir=str(tmp_path), ) - report = cli._report_from_dict(_make_report_dict(sample_metadata)) + report = report_from_dict(_make_report_dict(sample_metadata)) approval_json = tmp_path / "approval-center-testuser-2026-03-29.json" approval_md = tmp_path / "approval-center-testuser-2026-03-29.md" saved: dict[str, object] = {} @@ -1046,20 +1067,18 @@ def _write_approval_center_artifacts(report_arg, output_dir, *, approval_view): monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) monkeypatch.setattr( - cli, - "_utcnow", + "src.app.approval_center._utcnow", lambda: datetime(2026, 4, 17, tzinfo=timezone.utc), ) monkeypatch.setattr( - cli, - "_refresh_latest_report_state", + "src.app.approval_center.refresh_latest_report_state", lambda _output_dir, _args: (tmp_path / "audit-report-testuser-2026-03-29.json", {}, report), ) - monkeypatch.setattr(cli, "_refresh_shared_artifacts_from_report", lambda *_a, **_k: {}) - monkeypatch.setattr(cli, "_write_approval_center_artifacts", _write_approval_center_artifacts) - monkeypatch.setattr("src.approval_ledger.load_approval_ledger_bundle", _load_approval_ledger_bundle) + monkeypatch.setattr("src.app.approval_center.refresh_shared_artifacts_from_report", lambda *_a, **_k: {}) + monkeypatch.setattr("src.app.approval_center.write_approval_center_artifacts", _write_approval_center_artifacts) + monkeypatch.setattr("src.app.approval_center.load_approval_ledger_bundle", _load_approval_ledger_bundle) monkeypatch.setattr( - "src.approval_ledger.build_approval_record", + "src.app.approval_center.build_approval_record", lambda ledger_record, *, reviewer, note="": { "approval_id": ledger_record["approval_id"], "approval_subject_type": ledger_record["approval_subject_type"], @@ -1071,7 +1090,7 @@ def _write_approval_center_artifacts(report_arg, output_dir, *, approval_view): "approval_note": note, }, ) - monkeypatch.setattr("src.warehouse.save_approval_record", _save_approval_record) + monkeypatch.setattr("src.app.approval_center.save_approval_record", _save_approval_record) cli.main() @@ -1096,8 +1115,14 @@ def test_main_generate_manifest_writes_artifact(monkeypatch, tmp_path, sample_me report_data = _make_report_dict(sample_metadata) monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_latest_report", lambda _output_dir: (report_path, report_data)) - monkeypatch.setattr("src.repo_improver.generate_manifest", lambda data: [{"repo": "testuser/test-repo"}]) + monkeypatch.setattr( + "src.app.report_only.load_latest_report", + lambda _output_dir: (report_path, report_data), + ) + monkeypatch.setattr( + "src.app.report_only.generate_manifest", + lambda data: [{"repo": "testuser/test-repo"}], + ) def _write_manifest(manifest, output_dir): assert manifest == [{"repo": "testuser/test-repo"}] @@ -1105,7 +1130,7 @@ def _write_manifest(manifest, output_dir): manifest_path.write_text("[]") return manifest_path - monkeypatch.setattr("src.repo_improver.write_manifest", _write_manifest) + monkeypatch.setattr("src.app.report_only.write_manifest", _write_manifest) cli.main() @@ -1199,9 +1224,9 @@ def test_main_preflight_off_skips_auto_preflight(monkeypatch, sample_metadata): captured: dict[str, object] = {} monkeypatch.setattr(cli, "build_parser", lambda: FakeParser(args)) - monkeypatch.setattr(cli, "_load_scoring_profile", lambda name: (None, "default")) - monkeypatch.setattr(cli, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) - monkeypatch.setattr(cli, "_run_targeted_audit", lambda *a, **k: captured.update(k)) + monkeypatch.setattr(run_audit, "_load_scoring_profile", lambda name: (None, "default")) + monkeypatch.setattr(run_audit, "_fetch_repo_metadata", lambda *_: ([sample_metadata], [])) + monkeypatch.setattr(run_audit, "_run_targeted_audit", lambda *a, **k: captured.update(k)) cli.main() @@ -1217,7 +1242,7 @@ def test_print_output_summary_emits_normal_audit_hint(capsys, sample_metadata): ) report = AuditReport.from_audits("testuser", [audit], [], 1) - cli._print_output_summary( + run_audit._print_output_summary( "Audited 1 repos for testuser", report, { @@ -1263,7 +1288,7 @@ def test_print_output_summary_emits_post_apply_monitoring_hints(capsys, sample_m "summary": "Security Review should win ties inside the preview-ready group because recent outcome history is proven.", } - cli._print_output_summary( + run_audit._print_output_summary( "Audited 1 repos for testuser", report, { @@ -1299,7 +1324,7 @@ def test_incremental_noop_regenerates_from_latest_report(monkeypatch, tmp_path, report_data = _make_report_dict(sample_metadata) report_data["audits"][0]["metadata"]["name"] = sample_metadata.name - monkeypatch.setattr(cli, "_load_latest_report", lambda _output_dir: (report_path, report_data)) + monkeypatch.setattr(run_audit, "_load_latest_report", lambda _output_dir: (report_path, report_data)) monkeypatch.setattr( "src.history.load_fingerprints", lambda *_args, **_kwargs: {sample_metadata.name: {"pushed_at": sample_metadata.pushed_at.isoformat()}}, @@ -1319,11 +1344,11 @@ def _record_regen(args, output_dir, *, client, existing_report_path, existing_re } ) - monkeypatch.setattr(cli, "_regenerate_outputs_from_latest_report", _record_regen) + monkeypatch.setattr(run_audit, "_regenerate_outputs_from_latest_report", _record_regen) - cli._run_incremental_audit( + run_audit._run_incremental_audit( args, - cli.GitHubClient(token=None, cache=None), + run_audit.GitHubClient(token=None, cache=None), tmp_path / "output", all_repos=[sample_metadata], errors=[], @@ -1356,12 +1381,12 @@ def _record_baseline(repos): return {} monkeypatch.setattr( - cli, + run_audit, "_portfolio_lang_freq_for_filtered_baseline", _record_baseline, ) monkeypatch.setattr( - cli, + run_audit, "_analyze_repos", lambda repos, **kwargs: [ RepoAudit( @@ -1372,7 +1397,7 @@ def _record_baseline(repos): ) ], ) - monkeypatch.setattr(cli, "_write_report_outputs", lambda *a, **k: { + monkeypatch.setattr(run_audit, "_write_report_outputs", lambda *a, **k: { "json_path": tmp_path / "audit-report.json", "md_path": tmp_path / "audit.md", "excel_path": tmp_path / "audit.xlsx", @@ -1388,12 +1413,12 @@ def _record_baseline(repos): "review_pack_info": "", "cache_info": "", }) - monkeypatch.setattr(cli, "_print_output_summary", lambda *a, **k: None) - monkeypatch.setattr(cli, "_apply_requested_reconciliation", lambda *a, **k: None) + monkeypatch.setattr(run_audit, "_print_output_summary", lambda *a, **k: None) + monkeypatch.setattr(run_audit, "_apply_requested_reconciliation", lambda *a, **k: None) - cli._run_targeted_audit( + run_audit._run_targeted_audit( args, - cli.GitHubClient(token=None, cache=None), + run_audit.GitHubClient(token=None, cache=None), tmp_path / "output", all_repos=[sample_metadata, other_repo], errors=[], @@ -1421,7 +1446,7 @@ def test_incremental_audit_delegates_changed_repos_to_targeted_path(monkeypatch, report_data["audits"][0]["metadata"]["name"] = changed_repo.name captured: dict[str, object] = {} - monkeypatch.setattr(cli, "_load_latest_report", lambda _output_dir: (report_path, report_data)) + monkeypatch.setattr(run_audit, "_load_latest_report", lambda _output_dir: (report_path, report_data)) monkeypatch.setattr( "src.history.load_fingerprints", lambda *_args, **_kwargs: { @@ -1429,11 +1454,11 @@ def test_incremental_audit_delegates_changed_repos_to_targeted_path(monkeypatch, sample_metadata.name: {"pushed_at": sample_metadata.pushed_at.isoformat()}, }, ) - monkeypatch.setattr(cli, "_run_targeted_audit", lambda *a, **k: captured.update({"repos": a[0].repos, **k})) + monkeypatch.setattr(run_audit, "_run_targeted_audit", lambda *a, **k: captured.update({"repos": a[0].repos, **k})) - cli._run_incremental_audit( + run_audit._run_incremental_audit( args, - cli.GitHubClient(token=None, cache=None), + run_audit.GitHubClient(token=None, cache=None), tmp_path / "output", all_repos=[changed_repo, sample_metadata], errors=[], @@ -1452,11 +1477,11 @@ def test_targeted_audit_blocks_without_baseline_context(monkeypatch, tmp_path, s report_data.pop("baseline_signature", None) called = {"analyze": False} - monkeypatch.setattr(cli, "_analyze_repos", lambda *a, **k: called.update({"analyze": True}) or []) + monkeypatch.setattr(run_audit, "_analyze_repos", lambda *a, **k: called.update({"analyze": True}) or []) - cli._run_targeted_audit( + run_audit._run_targeted_audit( args, - cli.GitHubClient(token=None, cache=None), + run_audit.GitHubClient(token=None, cache=None), tmp_path / "output", all_repos=[sample_metadata], errors=[], @@ -1473,11 +1498,11 @@ def test_targeted_audit_blocks_on_incompatible_baseline_context(monkeypatch, tmp report_data = _make_report_dict(sample_metadata, skip_forks=False) called = {"analyze": False} - monkeypatch.setattr(cli, "_analyze_repos", lambda *a, **k: called.update({"analyze": True}) or []) + monkeypatch.setattr(run_audit, "_analyze_repos", lambda *a, **k: called.update({"analyze": True}) or []) - cli._run_targeted_audit( + run_audit._run_targeted_audit( args, - cli.GitHubClient(token=None, cache=None), + run_audit.GitHubClient(token=None, cache=None), tmp_path / "output", all_repos=[sample_metadata], errors=[], @@ -1494,7 +1519,7 @@ def test_report_from_dict_keeps_legacy_reports_readable(sample_metadata): report_data.pop("baseline_context", None) report_data.pop("baseline_signature", None) - report = cli._report_from_dict(report_data) + report = report_from_dict(report_data) assert report.baseline_context == {} assert report.baseline_signature == "" @@ -1557,7 +1582,7 @@ def test_report_from_dict_preserves_action_sync_packet_outcome_tuning_and_automa "recommended_command": "audit testuser --campaign security-review --writeback-target all", } - report = cli._report_from_dict(report_data) + report = report_from_dict(report_data) assert report.action_sync_packets[0]["campaign_type"] == "security-review" assert report.apply_readiness_summary["summary"] == "Preview Security Review next." @@ -1606,9 +1631,9 @@ def _record_write(report, passed_args, output_dir, **kwargs): "cache_info": "", } - monkeypatch.setattr(cli, "_write_report_outputs", _record_write) + monkeypatch.setattr(run_audit, "_write_report_outputs", _record_write) - cli._regenerate_outputs_from_latest_report( + run_audit._regenerate_outputs_from_latest_report( args, tmp_path / "output", client=None, @@ -1632,13 +1657,13 @@ def test_write_report_outputs_forwards_analyst_view_args(monkeypatch, tmp_path, portfolio_profile="shipping", collection="showcase", ) - report = cli._report_from_dict(_make_report_dict(sample_metadata)) + report = report_from_dict(_make_report_dict(sample_metadata)) json_path = tmp_path / "audit-report-testuser-2026-03-29.json" - monkeypatch.setattr(cli, "write_json_report", lambda *_: json_path) - monkeypatch.setattr(cli, "write_markdown_report", lambda *a, **k: tmp_path / "audit.md") - monkeypatch.setattr(cli, "write_pcc_export", lambda *a, **k: tmp_path / "audit-pcc.json") - monkeypatch.setattr(cli, "write_raw_metadata", lambda *a, **k: tmp_path / "raw.json") + monkeypatch.setattr(run_audit, "write_json_report", lambda *_: json_path) + monkeypatch.setattr(run_audit, "write_markdown_report", lambda *a, **k: tmp_path / "audit.md") + monkeypatch.setattr(run_audit, "write_pcc_export", lambda *a, **k: tmp_path / "audit-pcc.json") + monkeypatch.setattr(run_audit, "write_raw_metadata", lambda *a, **k: tmp_path / "raw.json") monkeypatch.setattr("src.history.load_trend_data", lambda: []) monkeypatch.setattr("src.history.load_repo_score_history", lambda: {}) monkeypatch.setattr("src.history.find_previous", lambda *_: None) @@ -1667,7 +1692,7 @@ def _record_review_pack(*_args, **kwargs): monkeypatch.setattr("src.web_export.export_html_dashboard", _record_html) monkeypatch.setattr("src.review_pack.export_review_pack", _record_review_pack) - outputs = cli._write_report_outputs(report, args, tmp_path) + outputs = run_audit._write_report_outputs(report, args, tmp_path) assert html_calls["portfolio_profile"] == "shipping" assert html_calls["collection"] == "showcase" @@ -1688,9 +1713,9 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - monkeypatch.setattr(cli, "clone_workspace", lambda *a, **k: _CloneContext()) - monkeypatch.setattr(cli, "create_progress", lambda: None) - monkeypatch.setattr(cli, "run_all_analyzers", lambda *a, **k: []) + monkeypatch.setattr(run_audit, "clone_workspace", lambda *a, **k: _CloneContext()) + monkeypatch.setattr(run_audit, "create_progress", lambda: None) + monkeypatch.setattr(run_audit, "run_all_analyzers", lambda *a, **k: []) def _record_score_repo(*a, **kwargs): captured.append(kwargs) @@ -1701,12 +1726,12 @@ def _record_score_repo(*a, **kwargs): completeness_tier="functional", ) - monkeypatch.setattr(cli, "score_repo", _record_score_repo) + monkeypatch.setattr(run_audit, "score_repo", _record_score_repo) - cli._analyze_repos( + run_audit._analyze_repos( [sample_metadata], args=args, - client=cli.GitHubClient(token=None, cache=None), + client=run_audit.GitHubClient(token=None, cache=None), portfolio_lang_freq={}, custom_weights=None, ) diff --git a/tests/test_composer_golden_contract.py b/tests/test_composer_golden_contract.py index 242cbb1..e3cb80d 100644 --- a/tests/test_composer_golden_contract.py +++ b/tests/test_composer_golden_contract.py @@ -87,14 +87,66 @@ def test_magnitude_floor_unifies_rebuild_and_rererestore_tiers() -> None: # T3-2 phase 5 fix: the rererestore persistence builder now floors per-event # magnitude at 0 (max(0.0, ..)) exactly like rebuild -- previously it omitted the # floor (magnitude -= X), letting an over-penalized confirmation event go negative - # and count against its own side. With the floor, the SAME structural input (the - # "clamp-divergence" floor-path scenario) yields the SAME score across the tiers. - # This pins the fix: a regression that re-removed the floor would re-diverge here. - rebuild = GOLDEN[_REBUILD_PERSISTENCE]["clamp-divergence"] - rererestore = GOLDEN[_RERERESTORE_PERSISTENCE]["clamp-divergence"] + # and count against its own side. With the floor, the SAME structural input yields + # the SAME score across the tiers. This pins the fix: a regression that re-removed + # the floor would re-diverge here. + # + # This scenario is driven directly against the production composers (not read from + # GOLDEN/the shared "clamp-divergence" corpus fixture) and gives its "strong" event + # a `key`/`generated_at` that matches the target's `queue_identity`, so + # `ordered_reset_reentry_events_for_target` takes its `current_index == 0` shortcut + # and returns the two events unchanged. This sidesteps a known pre-existing gap: + # `current_closure_forecast_event_for_target` (src/operator_trend_support.py, + # ~line 210) synthesizes a "current" event from the target dict whose key coverage + # stops at the "rerestore" tier and never reaches "rererestore", so when the shared + # corpus fixture (which has no matching key/generated_at) falls through to that + # synthesizer, the rebuild and rererestore tiers diverge for a reason unrelated to + # the floor. Tracked as a follow-up; not fixed here (see operator report). + target = { + "lane": "urgent", + "kind": "config", + "item_id": "T1", + "closure_forecast_momentum_status": "sustained-confirmation", + "closure_forecast_stability_status": "stable", + } + strong = { + "class_key": "urgent:config", + "key": "T1", + "generated_at": "", + "closure_forecast_momentum_status": "sustained-confirmation", + "closure_forecast_stability_status": "stable", + "closure_forecast_reset_reentry_rebuild_status": "rebuilt-confirmation-reentry", + "closure_forecast_reset_reentry_freshness_status": "fresh", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": ( + "rererestored-confirmation-rebuild-reentry" + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status": "fresh", + } + decrement = { + "class_key": "urgent:config", + "closure_forecast_momentum_status": "insufficient-data", + "closure_forecast_stability_status": "watch", + "closure_forecast_reset_reentry_refresh_recovery_status": "rebuilding-confirmation-reentry", + "closure_forecast_reset_reentry_freshness_status": "mixed-age", + "closure_forecast_reset_reentry_reset_status": "confirmation-reset", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_refresh_recovery_status": ( + "rererestoring-confirmation-rebuild-reentry" + ), + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_freshness_status": "mixed-age", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_reset_status": "confirmation-reset", + } + events = [strong, decrement] + + rebuild = _enum.m.closure_forecast_reset_reentry_rebuild_persistence_for_target( + target, events, {} + ) + rererestore = _enum.m.closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( + target, events, {} + ) rebuild_score = rebuild[_REBUILD_SCORE_KEY] rererestore_score = rererestore[_RERERESTORE_SCORE_KEY] assert rebuild_score == rererestore_score, (rebuild_score, rererestore_score) + assert rebuild_score > 0.0, rebuild_score # The rerererestore tier wraps + delegates to the now-fixed rererestore builder, # so this confirmation-side scenario no longer yields a spurious NEGATIVE score diff --git a/tests/test_ghas_alerts.py b/tests/test_ghas_alerts.py index 1cb0438..cb7bd16 100644 --- a/tests/test_ghas_alerts.py +++ b/tests/test_ghas_alerts.py @@ -427,9 +427,9 @@ def test_vuln_check_also_triggers_ghas(self) -> None: """When --vuln-check is active, the GHAS block is also triggered (implied flag).""" from pathlib import Path as _Path - cli_source = (_Path(__file__).parent.parent / "src" / "cli.py").read_text() - # Look for the condition that gates GHAS on either flag - assert "ghas_alerts" in cli_source - assert "vuln_check" in cli_source + audit_flow_source = (_Path(__file__).parent.parent / "src" / "app" / "run_audit.py").read_text() + # Look for the condition that gates GHAS on either flag in the audit flow. + assert "ghas_alerts" in audit_flow_source + assert "vuln_check" in audit_flow_source # The block condition should include both flags joined by OR - assert 'getattr(args, "ghas_alerts"' in cli_source or "args.ghas_alerts" in cli_source + assert 'getattr(args, "ghas_alerts"' in audit_flow_source or "args.ghas_alerts" in audit_flow_source diff --git a/tests/test_operator_control_center.py b/tests/test_operator_control_center.py index 7ff4a05..bda911d 100644 --- a/tests/test_operator_control_center.py +++ b/tests/test_operator_control_center.py @@ -7,6 +7,7 @@ import src.operator_follow_through as operator_follow_through import src.operator_resolution_trend as operator_resolution_trend import src.operator_snapshot_packaging as operator_snapshot_packaging +import src.operator_trend_closure_forecast_reset_controls as reset_controls build_operator_snapshot = operator_control_center.build_operator_snapshot normalize_review_state = operator_control_center.normalize_review_state @@ -105,7 +106,11 @@ def _make_report(**overrides) -> dict: } ] }, - "rollback_preview": {"available": True, "item_count": 1, "fully_reversible_count": 0}, + "rollback_preview": { + "available": True, + "item_count": 1, + "fully_reversible_count": 0, + }, "audits": [], } data.update(overrides) @@ -151,7 +156,12 @@ def test_operator_snapshot_suppresses_cleared_security_posture_from_latest_truth ) ) report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, material_changes=[ { "change_key": "security-1", @@ -202,7 +212,9 @@ def test_operator_snapshot_suppresses_cleared_security_posture_from_latest_truth assert "RepoC shifted on ship readiness" in titles -def test_operator_snapshot_treats_project_mirror_drift_as_campaign_drift(tmp_path: Path): +def test_operator_snapshot_treats_project_mirror_drift_as_campaign_drift( + tmp_path: Path, +): snapshot = build_operator_snapshot( _make_report( managed_state_drift=[ @@ -217,13 +229,17 @@ def test_operator_snapshot_treats_project_mirror_drift_as_campaign_drift(tmp_pat output_dir=tmp_path, ) - project_item = next(item for item in snapshot["operator_queue"] if item["repo"] == "RepoD") + project_item = next( + item for item in snapshot["operator_queue"] if item["repo"] == "RepoD" + ) assert project_item["title"] == "RepoD drift needs review" assert project_item["lane"] == "urgent" def test_operator_snapshot_filters_by_triage_view(tmp_path: Path): - snapshot = build_operator_snapshot(_make_report(), output_dir=tmp_path, triage_view="ready") + snapshot = build_operator_snapshot( + _make_report(), output_dir=tmp_path, triage_view="ready" + ) assert snapshot["operator_queue"] assert all(item["lane"] == "ready" for item in snapshot["operator_queue"]) @@ -245,11 +261,16 @@ def test_operator_snapshot_includes_watch_guidance(tmp_path: Path): assert summary["primary_target"]["title"] == "GitHub authentication is required." assert summary["aging_status"] == "stale" assert "setup blocker" in summary["primary_target_reason"].lower() - assert "rerun the relevant command" in summary["primary_target_done_criteria"].lower() + assert ( + "rerun the relevant command" in summary["primary_target_done_criteria"].lower() + ) assert "Set GITHUB_TOKEN" in summary["closure_guidance"] assert summary["decision_memory_status"] == "new" assert summary["primary_target_last_outcome"] == "no-change" - assert "no earlier intervention" in summary["primary_target_resolution_evidence"].lower() + assert ( + "no earlier intervention" + in summary["primary_target_resolution_evidence"].lower() + ) assert summary["primary_target_confidence_label"] == "high" assert summary["primary_target_confidence_score"] >= 0.75 assert summary["next_action_confidence_label"] == "high" @@ -273,7 +294,11 @@ def test_operator_snapshot_includes_watch_guidance(tmp_path: Path): assert "blocked" in summary["primary_target_trust_policy_reason"].lower() assert summary["primary_target_exception_status"] == "none" assert summary["recommendation_drift_status"] == "stable" - assert summary["primary_target_recovery_confidence_label"] in {"low", "medium", "high"} + assert summary["primary_target_recovery_confidence_label"] in { + "low", + "medium", + "high", + } assert "recovery confidence" in summary["recovery_confidence_summary"].lower() assert summary["primary_target_exception_retirement_status"] in { "none", @@ -428,7 +453,11 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat operator_control_center, "load_review_history", lambda *args, **kwargs: [ - {"repo": "RepoA", "title": "RepoA", "summary": "RepoA reopened after review."} + { + "repo": "RepoA", + "title": "RepoA", + "summary": "RepoA reopened after review.", + } ], ) monkeypatch.setattr( @@ -457,7 +486,12 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "reopened_attention_count": 1, }, "operator_queue": [ - {"item_id": "a", "repo": "RepoA", "title": "RepoA", "lane": "urgent"} + { + "item_id": "a", + "repo": "RepoA", + "title": "RepoA", + "lane": "urgent", + } ], }, { @@ -551,7 +585,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "reacquired-clearance", "blocked", } - assert summary["primary_target_closure_forecast_reacquisition_persistence_status"] in { + assert summary[ + "primary_target_closure_forecast_reacquisition_persistence_status" + ] in { "none", "just-reacquired", "holding-confirmation", @@ -567,7 +603,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "churn", "blocked", } - assert summary["primary_target_closure_forecast_reacquisition_freshness_status"] in { + assert summary[ + "primary_target_closure_forecast_reacquisition_freshness_status" + ] in { "fresh", "mixed-age", "stale", @@ -598,7 +636,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "reentered-clearance", "blocked", } - assert summary["primary_target_closure_forecast_reset_reentry_persistence_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_persistence_status" + ] in { "none", "just-reentered", "holding-confirmation-reentry", @@ -614,7 +654,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "churn", "blocked", } - assert summary["primary_target_closure_forecast_reset_reentry_freshness_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_freshness_status" + ] in { "fresh", "mixed-age", "stale", @@ -628,7 +670,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "clearance-reset", "blocked", } - assert summary["primary_target_closure_forecast_reset_reentry_refresh_recovery_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_refresh_recovery_status" + ] in { "none", "recovering-confirmation-reentry-reset", "recovering-clearance-reentry-reset", @@ -645,7 +689,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "rebuilt-clearance-reentry", "blocked", } - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_persistence_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_persistence_status" + ] in { "none", "just-rebuilt", "holding-confirmation-rebuild", @@ -655,19 +701,25 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "reversing", "insufficient-data", } - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_churn_status" + ] in { "none", "watch", "churn", "blocked", } - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_freshness_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_freshness_status" + ] in { "fresh", "mixed-age", "stale", "insufficient-data", } - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_reset_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_reset_status" + ] in { "none", "confirmation-softened", "clearance-softened", @@ -686,7 +738,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat "reversing", "blocked", } - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_reentry_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_status" + ] in { "none", "pending-confirmation-rebuild-reentry", "pending-clearance-rebuild-reentry", @@ -952,27 +1006,45 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat } assert -0.95 <= summary["primary_target_closure_forecast_reweight_score"] <= 0.95 assert -0.95 <= summary["primary_target_closure_forecast_momentum_score"] <= 0.95 - assert -0.95 <= summary["primary_target_closure_forecast_refresh_recovery_score"] <= 0.95 assert ( - -0.95 <= summary["primary_target_closure_forecast_reacquisition_persistence_score"] <= 0.95 + -0.95 + <= summary["primary_target_closure_forecast_refresh_recovery_score"] + <= 0.95 ) - assert -0.95 <= summary["primary_target_closure_forecast_reset_refresh_recovery_score"] <= 0.95 assert ( - -0.95 <= summary["primary_target_closure_forecast_reset_reentry_persistence_score"] <= 0.95 + -0.95 + <= summary["primary_target_closure_forecast_reacquisition_persistence_score"] + <= 0.95 ) assert ( -0.95 - <= summary["primary_target_closure_forecast_reset_reentry_refresh_recovery_score"] + <= summary["primary_target_closure_forecast_reset_refresh_recovery_score"] <= 0.95 ) assert ( -0.95 - <= summary["primary_target_closure_forecast_reset_reentry_rebuild_persistence_score"] + <= summary["primary_target_closure_forecast_reset_reentry_persistence_score"] <= 0.95 ) assert ( -0.95 - <= summary["primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_score"] + <= summary[ + "primary_target_closure_forecast_reset_reentry_refresh_recovery_score" + ] + <= 0.95 + ) + assert ( + -0.95 + <= summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_persistence_score" + ] + <= 0.95 + ) + assert ( + -0.95 + <= summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_refresh_recovery_score" + ] <= 0.95 ) assert ( @@ -1031,27 +1103,45 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat ] <= 0.95 ) - assert 0.0 <= summary["primary_target_closure_forecast_recovery_churn_score"] <= 0.95 - assert 0.0 <= summary["primary_target_closure_forecast_reset_reentry_churn_score"] <= 0.95 assert ( - 0.0 <= summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_score"] <= 0.95 + 0.0 <= summary["primary_target_closure_forecast_recovery_churn_score"] <= 0.95 ) assert ( 0.0 - <= summary["primary_target"]["decayed_rerestored_rebuild_reentry_confirmation_rate"] + <= summary["primary_target_closure_forecast_reset_reentry_churn_score"] + <= 0.95 + ) + assert ( + 0.0 + <= summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_score"] + <= 0.95 + ) + assert ( + 0.0 + <= summary["primary_target"][ + "decayed_rerestored_rebuild_reentry_confirmation_rate" + ] <= 1.0 ) assert ( - 0.0 <= summary["primary_target"]["decayed_rerestored_rebuild_reentry_clearance_rate"] <= 1.0 + 0.0 + <= summary["primary_target"][ + "decayed_rerestored_rebuild_reentry_clearance_rate" + ] + <= 1.0 ) assert ( 0.0 - <= summary["primary_target"]["decayed_rererestored_rebuild_reentry_confirmation_rate"] + <= summary["primary_target"][ + "decayed_rererestored_rebuild_reentry_confirmation_rate" + ] <= 1.0 ) assert ( 0.0 - <= summary["primary_target"]["decayed_rererestored_rebuild_reentry_clearance_rate"] + <= summary["primary_target"][ + "decayed_rererestored_rebuild_reentry_clearance_rate" + ] <= 1.0 ) assert ( @@ -1062,7 +1152,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat ) assert ( 0.0 - <= summary["primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_score"] + <= summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_reentry_churn_score" + ] <= 0.95 ) assert ( @@ -1095,31 +1187,65 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat ) assert 0.0 <= summary["primary_target"]["decayed_confirmation_forecast_rate"] <= 1.0 assert 0.0 <= summary["primary_target"]["decayed_clearance_forecast_rate"] <= 1.0 - assert 0.0 <= summary["primary_target"]["decayed_rebuilt_confirmation_reentry_rate"] <= 1.0 - assert 0.0 <= summary["primary_target"]["decayed_rebuilt_clearance_reentry_rate"] <= 1.0 assert ( 0.0 - <= summary["primary_target"]["decayed_restored_rebuild_reentry_confirmation_rate"] + <= summary["primary_target"]["decayed_rebuilt_confirmation_reentry_rate"] + <= 1.0 + ) + assert ( + 0.0 + <= summary["primary_target"]["decayed_rebuilt_clearance_reentry_rate"] <= 1.0 ) assert ( - 0.0 <= summary["primary_target"]["decayed_restored_rebuild_reentry_clearance_rate"] <= 1.0 + 0.0 + <= summary["primary_target"][ + "decayed_restored_rebuild_reentry_confirmation_rate" + ] + <= 1.0 + ) + assert ( + 0.0 + <= summary["primary_target"]["decayed_restored_rebuild_reentry_clearance_rate"] + <= 1.0 + ) + assert ( + 0.0 + <= summary["primary_target_weighted_pending_resolution_support_score"] + <= 0.95 ) - assert 0.0 <= summary["primary_target_weighted_pending_resolution_support_score"] <= 0.95 assert 0.0 <= summary["primary_target_weighted_pending_debt_caution_score"] <= 0.95 assert summary["class_decay_window_runs"] == 4 assert summary["closure_forecast_reset_reentry_rebuild_decay_window_runs"] == 4 assert summary["closure_forecast_reset_reentry_rebuild_refresh_window_runs"] == 4 assert summary["closure_forecast_reset_reentry_rebuild_reentry_window_runs"] == 4 - assert summary["closure_forecast_reset_reentry_rebuild_reentry_decay_window_runs"] == 4 - assert summary["closure_forecast_reset_reentry_rebuild_reentry_refresh_window_runs"] == 4 - assert summary["closure_forecast_reset_reentry_rebuild_reentry_restore_window_runs"] == 4 - assert summary["closure_forecast_reset_reentry_rebuild_reentry_restore_decay_window_runs"] == 4 assert ( - summary["closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_window_runs"] == 4 + summary["closure_forecast_reset_reentry_rebuild_reentry_decay_window_runs"] == 4 + ) + assert ( + summary["closure_forecast_reset_reentry_rebuild_reentry_refresh_window_runs"] + == 4 + ) + assert ( + summary["closure_forecast_reset_reentry_rebuild_reentry_restore_window_runs"] + == 4 + ) + assert ( + summary[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_decay_window_runs" + ] + == 4 + ) + assert ( + summary[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_window_runs" + ] + == 4 ) assert ( - summary["closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs"] + summary[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs" + ] == 4 ) assert ( @@ -1129,7 +1255,9 @@ def test_operator_snapshot_includes_phase_84_outcomes(monkeypatch, tmp_path: Pat == 4 ) assert ( - summary["closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_window_runs"] + summary[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_window_runs" + ] == 4 ) assert ( @@ -1201,20 +1329,30 @@ def test_operator_snapshot_attaches_portfolio_catalog_context(tmp_path: Path): ) snapshot = build_operator_snapshot(report, output_dir=tmp_path) - urgent_item = next(item for item in snapshot["operator_queue"] if item.get("repo") == "RepoC") + urgent_item = next( + item for item in snapshot["operator_queue"] if item.get("repo") == "RepoC" + ) markdown = render_control_center_markdown(snapshot, "testuser", "2026-03-29") assert urgent_item["catalog_line"].startswith("operator-loop | flagship queue item") assert urgent_item["intent_alignment"] == "needs-review" - assert urgent_item["scorecard_line"] == "Scorecard: Maintain — Operating (target Strong)" - assert urgent_item["maturity_gap_summary"] == "testing, ci are still below the maintain bar." + assert ( + urgent_item["scorecard_line"] + == "Scorecard: Maintain — Operating (target Strong)" + ) + assert ( + urgent_item["maturity_gap_summary"] + == "testing, ci are still below the maintain bar." + ) assert "Catalog: operator-loop | flagship queue item" in markdown assert "Intent Alignment: needs-review" in markdown assert "Scorecard: Maintain — Operating (target Strong)" in markdown assert "Maturity Gap: testing, ci are still below the maintain bar." in markdown -def test_operator_snapshot_adds_follow_through_from_recent_history(tmp_path: Path, monkeypatch): +def test_operator_snapshot_adds_follow_through_from_recent_history( + tmp_path: Path, monkeypatch +): monkeypatch.setattr( "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: [ @@ -1249,7 +1387,9 @@ def test_operator_snapshot_adds_follow_through_from_recent_history(tmp_path: Pat ], ) - snapshot = build_operator_snapshot(_make_report(preflight_summary={}), output_dir=tmp_path) + snapshot = build_operator_snapshot( + _make_report(preflight_summary={}), output_dir=tmp_path + ) summary = snapshot["operator_summary"] assert summary["repeat_urgent_count"] >= 1 @@ -1362,9 +1502,10 @@ def test_project_queue_follow_through_keeps_aligned_on_track_maintain_items_quie assert "current operator queue is quiet" in follow_through["follow_through_summary"] assert "182 item" not in follow_through["follow_through_summary"] - assert "No stronger follow-through checkpoint" in follow_through[ - "follow_through_checkpoint_summary" - ] + assert ( + "No stronger follow-through checkpoint" + in follow_through["follow_through_checkpoint_summary"] + ) def test_project_queue_follow_through_keeps_recent_waiting_items_on_watch(): @@ -1467,7 +1608,9 @@ def test_project_queue_follow_through_marks_calmer_post_escalation_items_as_reco item = enriched[0] assert item["follow_through_recovery_status"] == "recovering" assert item["follow_through_recovery_age_runs"] == 1 - assert "recovering from recent escalation" in item["follow_through_recovery_summary"] + assert ( + "recovering from recent escalation" in item["follow_through_recovery_summary"] + ) assert item["follow_through_recovery_persistence_status"] == "just-recovering" assert item["follow_through_relapse_churn_status"] == "blocked" @@ -1528,7 +1671,9 @@ def test_project_queue_follow_through_marks_one_quiet_run_as_retiring_watch(): assert item["follow_through_status"] == "resolved" assert item["follow_through_recovery_status"] == "retiring-watch" assert "one more quiet run" in item["follow_through_recovery_summary"] - assert item["follow_through_recovery_persistence_status"] == "holding-retiring-watch" + assert ( + item["follow_through_recovery_persistence_status"] == "holding-retiring-watch" + ) assert item["follow_through_relapse_churn_status"] == "none" @@ -1600,7 +1745,9 @@ def test_project_queue_follow_through_marks_two_quiet_runs_as_retired(): assert item["follow_through_recovery_status"] == "retired" assert item["follow_through_recovery_age_runs"] == 2 assert "retired its recent escalation" in item["follow_through_recovery_summary"] - assert item["follow_through_recovery_persistence_status"] == "sustained-retiring-watch" + assert ( + item["follow_through_recovery_persistence_status"] == "sustained-retiring-watch" + ) assert item["follow_through_relapse_churn_status"] == "none" @@ -1892,8 +2039,12 @@ def test_follow_through_reacquisition_durability_progresses_from_new_to_durable( operator_follow_through._follow_through_reacquisition_durability_projection( item, [ - {"follow_through_recovery_reacquisition_durability_status": "holding-reacquired"}, - {"follow_through_recovery_reacquisition_durability_status": "holding-reacquired"}, + { + "follow_through_recovery_reacquisition_durability_status": "holding-reacquired" + }, + { + "follow_through_recovery_reacquisition_durability_status": "holding-reacquired" + }, ], follow_through_recovery_reacquisition_status="reacquired", follow_through_relapse_churn_status="none", @@ -1934,7 +2085,11 @@ def test_follow_through_reacquisition_consolidation_tracks_holding_durable_and_r status, reason, summary = ( operator_follow_through._follow_through_reacquisition_consolidation_projection( item, - [{"follow_through_recovery_reacquisition_durability_status": "holding-reacquired"}], + [ + { + "follow_through_recovery_reacquisition_durability_status": "holding-reacquired" + } + ], follow_through_recovery_reacquisition_status="holding-reacquired", follow_through_recovery_reacquisition_durability_status="holding-reacquired", follow_through_relapse_churn_status="none", @@ -1964,7 +2119,11 @@ def test_follow_through_reacquisition_consolidation_tracks_holding_durable_and_r status, reason, summary = ( operator_follow_through._follow_through_reacquisition_consolidation_projection( item, - [{"follow_through_recovery_reacquisition_consolidation_status": "holding-confidence"}], + [ + { + "follow_through_recovery_reacquisition_consolidation_status": "holding-confidence" + } + ], follow_through_recovery_reacquisition_status="holding-reacquired", follow_through_recovery_reacquisition_durability_status="holding-reacquired", follow_through_relapse_churn_status="fragile", @@ -2002,7 +2161,11 @@ def test_follow_through_revalidation_recovery_marks_rebuilding_when_revalidation age_runs, status, reason, summary = ( operator_follow_through._follow_through_reacquisition_revalidation_recovery_projection( {"repo": "RepoD", "title": "RepoD drift needs review"}, - [{"follow_through_reacquisition_confidence_retirement_status": "revalidation-needed"}], + [ + { + "follow_through_reacquisition_confidence_retirement_status": "revalidation-needed" + } + ], follow_through_recovery_reacquisition_status="reacquiring", follow_through_recovery_reacquisition_durability_status="consolidating", follow_through_recovery_reacquisition_consolidation_status="fragile-confidence", @@ -2023,7 +2186,11 @@ def test_follow_through_revalidation_recovery_marks_reearning_when_confidence_is age_runs, status, reason, summary = ( operator_follow_through._follow_through_reacquisition_revalidation_recovery_projection( {"repo": "RepoD", "title": "RepoD drift needs review"}, - [{"follow_through_reacquisition_confidence_retirement_status": "revalidation-needed"}], + [ + { + "follow_through_reacquisition_confidence_retirement_status": "revalidation-needed" + } + ], follow_through_recovery_reacquisition_status="reacquired", follow_through_recovery_reacquisition_durability_status="holding-reacquired", follow_through_recovery_reacquisition_consolidation_status="building-confidence", @@ -2044,7 +2211,11 @@ def test_follow_through_revalidation_recovery_marks_just_reearned_on_first_resto age_runs, status, reason, summary = ( operator_follow_through._follow_through_reacquisition_revalidation_recovery_projection( {"repo": "RepoD", "title": "RepoD drift needs review"}, - [{"follow_through_reacquisition_confidence_retirement_status": "revalidation-needed"}], + [ + { + "follow_through_reacquisition_confidence_retirement_status": "revalidation-needed" + } + ], follow_through_recovery_reacquisition_status="reacquired", follow_through_recovery_reacquisition_durability_status="durable-reacquired", follow_through_recovery_reacquisition_consolidation_status="holding-confidence", @@ -2093,7 +2264,11 @@ def test_follow_through_revalidation_recovery_falls_back_to_insufficient_evidenc age_runs, status, reason, summary = ( operator_follow_through._follow_through_reacquisition_revalidation_recovery_projection( {"repo": "RepoD", "title": "RepoD drift needs review"}, - [{"follow_through_reacquisition_softening_decay_status": "revalidation-needed"}], + [ + { + "follow_through_reacquisition_softening_decay_status": "revalidation-needed" + } + ], follow_through_recovery_reacquisition_status="reacquired", follow_through_recovery_reacquisition_durability_status="insufficient-evidence", follow_through_recovery_reacquisition_consolidation_status="insufficient-evidence", @@ -2131,7 +2306,9 @@ def test_follow_through_revalidation_recovery_summary_prioritizes_under_revalida assert "RepoC: RepoC drift needs review" in summary -def test_operator_snapshot_marks_quiet_recovery_as_improving(tmp_path: Path, monkeypatch): +def test_operator_snapshot_marks_quiet_recovery_as_improving( + tmp_path: Path, monkeypatch +): monkeypatch.setattr( "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: [ @@ -2223,7 +2400,9 @@ def test_operator_snapshot_tracks_reopened_attention_items(tmp_path: Path, monke assert summary["primary_target"]["title"] == "RepoD drift needs review" -def test_operator_snapshot_prefers_reopened_urgent_over_fresh_urgent(tmp_path: Path, monkeypatch): +def test_operator_snapshot_prefers_reopened_urgent_over_fresh_urgent( + tmp_path: Path, monkeypatch +): monkeypatch.setattr( "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: [ @@ -2264,7 +2443,10 @@ def test_operator_snapshot_prefers_reopened_urgent_over_fresh_urgent(tmp_path: P resolution_targets = summary["resolution_targets"] assert resolution_targets[0]["title"] == "RepoD drift needs review" - assert resolution_targets[0]["confidence_score"] >= resolution_targets[1]["confidence_score"] + assert ( + resolution_targets[0]["confidence_score"] + >= resolution_targets[1]["confidence_score"] + ) assert summary["primary_target"]["title"] == "RepoD drift needs review" assert summary["primary_target"]["item_id"] == resolution_targets[0]["item_id"] @@ -2524,7 +2706,9 @@ def test_operator_snapshot_tracks_confirmed_resolution_and_reopen_evidence( assert reopened_summary["reopened_after_resolution_count"] >= 1 -def test_operator_snapshot_marks_generic_low_priority_ready_work_as_low_confidence(tmp_path: Path): +def test_operator_snapshot_marks_generic_low_priority_ready_work_as_low_confidence( + tmp_path: Path, +): snapshot = build_operator_snapshot( _make_report( preflight_summary={}, @@ -2553,7 +2737,9 @@ def test_operator_snapshot_marks_generic_low_priority_ready_work_as_low_confiden assert target["confidence_label"] == "low" assert target["confidence_score"] < 0.45 assert summary["next_action_confidence_label"] == "low" - assert summary["recommendation_quality_summary"].startswith("Tentative recommendation;") + assert summary["recommendation_quality_summary"].startswith( + "Tentative recommendation;" + ) def test_next_operator_action_prioritizes_chronic_closure_over_quiet_streak(): @@ -2594,7 +2780,9 @@ def test_closure_guidance_makes_ready_done_criteria_readable(): {"kind": "campaign", "lane": "ready"} ) guidance = operator_resolution_trend._closure_guidance( - {"recommended_action": "Review the reconcile queue before any manual writeback."}, + { + "recommended_action": "Review the reconcile queue before any manual writeback." + }, done_criteria, ) @@ -2602,7 +2790,9 @@ def test_closure_guidance_makes_ready_done_criteria_readable(): assert "when make the manual decision" not in guidance -def test_operator_snapshot_calibrates_healthy_confidence_history(tmp_path: Path, monkeypatch): +def test_operator_snapshot_calibrates_healthy_confidence_history( + tmp_path: Path, monkeypatch +): monkeypatch.setattr( "src.operator_control_center.load_operator_calibration_history", lambda *_args, **_kwargs: [ @@ -2631,7 +2821,12 @@ def test_operator_snapshot_calibrates_healthy_confidence_history(tmp_path: Path, "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-d", "repo": "RepoD", "title": "Drift D", "lane": "urgent"} + { + "item_id": "target-d", + "repo": "RepoD", + "title": "Drift D", + "lane": "urgent", + } ], }, { @@ -2647,7 +2842,12 @@ def test_operator_snapshot_calibrates_healthy_confidence_history(tmp_path: Path, "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-c", "repo": "RepoC", "title": "Drift C", "lane": "urgent"} + { + "item_id": "target-c", + "repo": "RepoC", + "title": "Drift C", + "lane": "urgent", + } ], }, { @@ -2663,7 +2863,12 @@ def test_operator_snapshot_calibrates_healthy_confidence_history(tmp_path: Path, "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-b", "repo": "RepoB", "title": "Drift B", "lane": "urgent"} + { + "item_id": "target-b", + "repo": "RepoB", + "title": "Drift B", + "lane": "urgent", + } ], }, { @@ -2679,7 +2884,12 @@ def test_operator_snapshot_calibrates_healthy_confidence_history(tmp_path: Path, "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-a", "repo": "RepoA", "title": "Drift A", "lane": "urgent"} + { + "item_id": "target-a", + "repo": "RepoA", + "title": "Drift A", + "lane": "urgent", + } ], }, ], @@ -2695,7 +2905,9 @@ def test_operator_snapshot_calibrates_healthy_confidence_history(tmp_path: Path, assert "validating well" in summary["confidence_calibration_summary"].lower() -def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: Path, monkeypatch): +def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat( + tmp_path: Path, monkeypatch +): monkeypatch.setattr( "src.operator_control_center.load_operator_calibration_history", lambda *_args, **_kwargs: [ @@ -2718,7 +2930,12 @@ def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-c", "repo": "RepoC", "title": "Drift C", "lane": "urgent"} + { + "item_id": "target-c", + "repo": "RepoC", + "title": "Drift C", + "lane": "urgent", + } ], }, { @@ -2734,7 +2951,12 @@ def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-b", "repo": "RepoB", "title": "Drift B", "lane": "urgent"} + { + "item_id": "target-b", + "repo": "RepoB", + "title": "Drift B", + "lane": "urgent", + } ], }, { @@ -2750,7 +2972,12 @@ def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-a", "repo": "RepoA", "title": "Drift A", "lane": "urgent"} + { + "item_id": "target-a", + "repo": "RepoA", + "title": "Drift A", + "lane": "urgent", + } ], }, { @@ -2766,7 +2993,12 @@ def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-b", "repo": "RepoB", "title": "Drift B", "lane": "urgent"} + { + "item_id": "target-b", + "repo": "RepoB", + "title": "Drift B", + "lane": "urgent", + } ], }, { @@ -2782,7 +3014,12 @@ def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-a", "repo": "RepoA", "title": "Drift A", "lane": "urgent"} + { + "item_id": "target-a", + "repo": "RepoA", + "title": "Drift A", + "lane": "urgent", + } ], }, ], @@ -2797,7 +3034,9 @@ def test_operator_snapshot_marks_noisy_calibration_when_reopens_repeat(tmp_path: assert "noisy" in summary["confidence_calibration_summary"].lower() -def test_operator_snapshot_tracks_partially_validated_recommendations(tmp_path: Path, monkeypatch): +def test_operator_snapshot_tracks_partially_validated_recommendations( + tmp_path: Path, monkeypatch +): monkeypatch.setattr( "src.operator_control_center.load_operator_calibration_history", lambda *_args, **_kwargs: [ @@ -2820,7 +3059,12 @@ def test_operator_snapshot_tracks_partially_validated_recommendations(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-c", "repo": "RepoC", "title": "Drift C", "lane": "urgent"} + { + "item_id": "target-c", + "repo": "RepoC", + "title": "Drift C", + "lane": "urgent", + } ], }, { @@ -2836,8 +3080,18 @@ def test_operator_snapshot_tracks_partially_validated_recommendations(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-a", "repo": "RepoA", "title": "Drift A", "lane": "ready"}, - {"item_id": "target-b", "repo": "RepoB", "title": "Drift B", "lane": "urgent"}, + { + "item_id": "target-a", + "repo": "RepoA", + "title": "Drift A", + "lane": "ready", + }, + { + "item_id": "target-b", + "repo": "RepoB", + "title": "Drift B", + "lane": "urgent", + }, ], }, { @@ -2853,8 +3107,18 @@ def test_operator_snapshot_tracks_partially_validated_recommendations(tmp_path: "primary_target_confidence_label": "high", }, "operator_queue": [ - {"item_id": "target-a", "repo": "RepoA", "title": "Drift A", "lane": "urgent"}, - {"item_id": "target-b", "repo": "RepoB", "title": "Drift B", "lane": "urgent"}, + { + "item_id": "target-a", + "repo": "RepoA", + "title": "Drift A", + "lane": "urgent", + }, + { + "item_id": "target-b", + "repo": "RepoB", + "title": "Drift B", + "lane": "urgent", + }, ], }, { @@ -2870,7 +3134,12 @@ def test_operator_snapshot_tracks_partially_validated_recommendations(tmp_path: "primary_target_confidence_label": "medium", }, "operator_queue": [ - {"item_id": "target-a", "repo": "RepoA", "title": "Drift A", "lane": "blocked"} + { + "item_id": "target-a", + "repo": "RepoA", + "title": "Drift A", + "lane": "blocked", + } ], }, ], @@ -2881,7 +3150,8 @@ def test_operator_snapshot_tracks_partially_validated_recommendations(tmp_path: assert summary["partially_validated_recommendation_count"] >= 1 assert any( - item["outcome"] == "partially_validated" for item in summary["recent_validation_outcomes"] + item["outcome"] == "partially_validated" + for item in summary["recent_validation_outcomes"] ) @@ -2907,7 +3177,8 @@ def test_operator_snapshot_healthy_calibration_boosts_urgent_confidence( rollback_preview={}, ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: [] + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: [], ) monkeypatch.setattr( @@ -2948,7 +3219,10 @@ def test_operator_snapshot_healthy_calibration_boosts_urgent_confidence( ) mixed_snapshot = build_operator_snapshot(report, output_dir=tmp_path) - assert healthy_snapshot["operator_summary"]["confidence_validation_status"] == "healthy" + assert ( + healthy_snapshot["operator_summary"]["confidence_validation_status"] + == "healthy" + ) assert mixed_snapshot["operator_summary"]["confidence_validation_status"] == "mixed" assert ( healthy_snapshot["operator_summary"]["primary_target_confidence_score"] @@ -3020,7 +3294,8 @@ def test_operator_snapshot_uses_verify_first_for_noisy_reopened_targets( }, ) monkeypatch.setattr( - "src.operator_resolution_trend._was_resolved_then_reopened", lambda *_args, **_kwargs: True + "src.operator_resolution_trend._was_resolved_then_reopened", + lambda *_args, **_kwargs: True, ) snapshot = build_operator_snapshot(report, output_dir=tmp_path) @@ -3296,7 +3571,8 @@ def test_operator_snapshot_never_softens_blocked_setup_below_act_with_review( }, ) monkeypatch.setattr( - "src.operator_resolution_trend._was_resolved_then_reopened", lambda *_args, **_kwargs: True + "src.operator_resolution_trend._was_resolved_then_reopened", + lambda *_args, **_kwargs: True, ) snapshot = build_operator_snapshot(report, output_dir=tmp_path) @@ -3310,9 +3586,16 @@ def test_operator_snapshot_never_softens_blocked_setup_below_act_with_review( assert summary["primary_target_trust_policy"] == "act-with-review" -def test_operator_snapshot_recovers_stable_verify_first_target(tmp_path: Path, monkeypatch): +def test_operator_snapshot_recovers_stable_verify_first_target( + tmp_path: Path, monkeypatch +): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -3424,9 +3707,16 @@ def test_operator_snapshot_recovers_stable_verify_first_target(tmp_path: Path, m assert summary["primary_target_exception_retirement_status"] == "candidate" -def test_operator_snapshot_retires_exception_after_stable_window(tmp_path: Path, monkeypatch): +def test_operator_snapshot_retires_exception_after_stable_window( + tmp_path: Path, monkeypatch +): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -3540,7 +3830,12 @@ def test_operator_snapshot_applies_class_level_normalization_for_healthy_class( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -3666,7 +3961,12 @@ def test_operator_snapshot_keeps_one_off_noise_from_class_normalization( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -3797,9 +4097,16 @@ def test_operator_snapshot_keeps_one_off_noise_from_class_normalization( assert "target-specific" in summary["policy_debt_summary"].lower() -def test_operator_snapshot_decays_stale_class_normalization(tmp_path: Path, monkeypatch): +def test_operator_snapshot_decays_stale_class_normalization( + tmp_path: Path, monkeypatch +): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -3865,7 +4172,8 @@ def test_operator_snapshot_decays_stale_class_normalization(tmp_path: Path, monk } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -3907,7 +4215,9 @@ def test_operator_snapshot_decays_stale_class_normalization(tmp_path: Path, monk summary = snapshot["operator_summary"] assert summary["primary_target_class_normalization_status"] == "candidate" - assert summary["primary_target_class_memory_freshness_status"] == "insufficient-data" + assert ( + summary["primary_target_class_memory_freshness_status"] == "insufficient-data" + ) assert summary["primary_target_class_decay_status"] == "normalization-decayed" assert summary["primary_target_trust_policy"] == "verify-first" assert ( @@ -3920,7 +4230,12 @@ def test_operator_snapshot_softens_class_debt_when_fresh_sticky_signal_ages_out( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -3970,7 +4285,8 @@ def test_operator_snapshot_softens_class_debt_when_fresh_sticky_signal_ages_out( } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4006,7 +4322,8 @@ def test_operator_snapshot_softens_class_debt_when_fresh_sticky_signal_ages_out( assert summary["primary_target_class_decay_status"] == "policy-debt-decayed" assert summary["primary_target_class_memory_freshness_status"] == "fresh" assert ( - "no longer has enough fresh sticky class evidence" in summary["class_decay_summary"].lower() + "no longer has enough fresh sticky class evidence" + in summary["class_decay_summary"].lower() ) @@ -4014,7 +4331,12 @@ def test_operator_snapshot_boosts_candidate_normalization_when_fresh_support_cro tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4062,7 +4384,8 @@ def test_operator_snapshot_boosts_candidate_normalization_when_fresh_support_cro } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4125,14 +4448,20 @@ def test_operator_snapshot_boosts_candidate_normalization_when_fresh_support_cro snapshot = build_operator_snapshot(report, output_dir=tmp_path) summary = snapshot["operator_summary"] - assert summary["primary_target_class_trust_reweight_direction"] == "supporting-normalization" + assert ( + summary["primary_target_class_trust_reweight_direction"] + == "supporting-normalization" + ) assert ( summary["primary_target_weighted_class_support_score"] > summary["primary_target_weighted_class_caution_score"] ) assert summary["primary_target_class_normalization_status"] == "applied" assert summary["primary_target_class_trust_momentum_status"] == "sustained-support" - assert summary["primary_target_class_reweight_transition_status"] == "confirmed-support" + assert ( + summary["primary_target_class_reweight_transition_status"] + == "confirmed-support" + ) assert summary["primary_target_class_transition_resolution_status"] == "confirmed" assert summary["primary_target_trust_policy"] == "act-with-review" assert "confirm broader normalization" in summary["class_momentum_summary"].lower() @@ -4142,7 +4471,12 @@ def test_operator_snapshot_strengthens_watch_into_class_debt_when_fresh_caution_ tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4190,7 +4524,8 @@ def test_operator_snapshot_strengthens_watch_into_class_debt_when_fresh_caution_ } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4250,14 +4585,19 @@ def test_operator_snapshot_strengthens_watch_into_class_debt_when_fresh_caution_ snapshot = build_operator_snapshot(report, output_dir=tmp_path) summary = snapshot["operator_summary"] - assert summary["primary_target_class_trust_reweight_direction"] == "supporting-caution" + assert ( + summary["primary_target_class_trust_reweight_direction"] == "supporting-caution" + ) assert ( summary["primary_target_weighted_class_caution_score"] > summary["primary_target_weighted_class_support_score"] ) assert summary["primary_target_policy_debt_status"] == "class-debt" assert summary["primary_target_class_trust_momentum_status"] == "sustained-caution" - assert summary["primary_target_class_reweight_transition_status"] == "confirmed-caution" + assert ( + summary["primary_target_class_reweight_transition_status"] + == "confirmed-caution" + ) assert summary["primary_target_class_transition_resolution_status"] == "confirmed" assert summary["primary_target_trust_policy"] == "verify-first" assert "confirm broader caution" in summary["class_momentum_summary"].lower() @@ -4267,7 +4607,12 @@ def test_operator_snapshot_holds_class_normalization_pending_until_support_persi tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4287,7 +4632,8 @@ def test_operator_snapshot_holds_class_normalization_pending_until_support_persi ) history = [] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4355,7 +4701,9 @@ def test_operator_snapshot_holds_class_normalization_pending_until_support_persi summary = snapshot["operator_summary"] assert summary["primary_target_class_trust_momentum_status"] == "insufficient-data" - assert summary["primary_target_class_reweight_transition_status"] == "pending-support" + assert ( + summary["primary_target_class_reweight_transition_status"] == "pending-support" + ) assert summary["primary_target_class_transition_health_status"] == "building" assert summary["primary_target_class_transition_resolution_status"] == "none" assert summary["primary_target_class_normalization_status"] == "candidate" @@ -4367,7 +4715,12 @@ def test_operator_snapshot_marks_flat_pending_support_as_holding_then_stalled( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4407,7 +4760,8 @@ def test_operator_snapshot_marks_flat_pending_support_as_holding_then_stalled( } ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4472,7 +4826,13 @@ def test_operator_snapshot_marks_flat_pending_support_as_holding_then_stalled( ) monkeypatch.setattr( "src.operator_resolution_trend._class_trust_reweight_scores_for_target", - lambda target, _history_meta: (0.48, 0.24, 0.24, "supporting-normalization", []), + lambda target, _history_meta: ( + 0.48, + 0.24, + 0.24, + "supporting-normalization", + [], + ), ) monkeypatch.setattr( "src.operator_resolution_trend._class_trust_momentum_for_target", @@ -4492,7 +4852,9 @@ def test_operator_snapshot_marks_flat_pending_support_as_holding_then_stalled( assert summary["primary_target_class_transition_health_status"] == "holding" assert summary["primary_target_class_transition_resolution_status"] == "none" - assert summary["primary_target_class_reweight_transition_status"] == "pending-support" + assert ( + summary["primary_target_class_reweight_transition_status"] == "pending-support" + ) assert summary["primary_target_class_normalization_status"] == "candidate" history.insert( @@ -4527,7 +4889,12 @@ def test_operator_snapshot_expires_old_pending_support_when_signal_fades( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4569,7 +4936,8 @@ def test_operator_snapshot_expires_old_pending_support_when_signal_fades( } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4662,7 +5030,12 @@ def test_operator_snapshot_marks_blocked_pending_support_when_local_noise_overri tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4681,7 +5054,8 @@ def test_operator_snapshot_marks_blocked_pending_support_when_local_noise_overri ], ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: [] + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: [], ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4770,7 +5144,12 @@ def test_operator_snapshot_scores_pending_support_as_confirm_soon_without_auto_c tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -4813,7 +5192,8 @@ def test_operator_snapshot_scores_pending_support_as_confirm_soon_without_auto_c } ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -4865,7 +5245,13 @@ def test_operator_snapshot_scores_pending_support_as_confirm_soon_without_auto_c ) monkeypatch.setattr( "src.operator_resolution_trend._class_trust_reweight_scores_for_target", - lambda target, _history_meta: (0.55, 0.20, 0.35, "supporting-normalization", []), + lambda target, _history_meta: ( + 0.55, + 0.20, + 0.35, + "supporting-normalization", + [], + ), ) monkeypatch.setattr( "src.operator_resolution_trend._class_trust_reweight_for_target", @@ -4896,9 +5282,14 @@ def test_operator_snapshot_scores_pending_support_as_confirm_soon_without_auto_c summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] - assert summary["primary_target_class_reweight_transition_status"] == "pending-support" + assert ( + summary["primary_target_class_reweight_transition_status"] == "pending-support" + ) assert summary["primary_target_transition_closure_confidence_label"] == "high" - assert summary["primary_target_transition_closure_likely_outcome"] in {"confirm-soon", "hold"} + assert summary["primary_target_transition_closure_likely_outcome"] in { + "confirm-soon", + "hold", + } assert summary["primary_target_closure_forecast_reweight_direction"] in { "neutral", "supporting-confirmation", @@ -4920,7 +5311,12 @@ def test_operator_snapshot_clears_low_confidence_pending_support_with_active_pen tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5013,7 +5409,8 @@ def test_operator_snapshot_clears_low_confidence_pending_support_with_active_pen }, ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) monkeypatch.setattr( "src.operator_resolution_trend._build_confidence_calibration", @@ -5107,16 +5504,29 @@ def test_operator_snapshot_clears_low_confidence_pending_support_with_active_pen "neutral", "supporting-clearance", } - assert summary["primary_target_closure_forecast_momentum_status"] == "sustained-clearance" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-clearance" + assert ( + summary["primary_target_closure_forecast_momentum_status"] + == "sustained-clearance" + ) + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-clearance" + ) assert summary["primary_target_class_transition_resolution_status"] == "cleared" assert summary["primary_target_class_reweight_transition_status"] == "none" assert summary["primary_target_trust_policy"] == "verify-first" -def test_operator_snapshot_marks_class_pending_debt_as_clearing(tmp_path: Path, monkeypatch): +def test_operator_snapshot_marks_class_pending_debt_as_clearing( + tmp_path: Path, monkeypatch +): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5165,7 +5575,8 @@ def test_operator_snapshot_marks_class_pending_debt_as_clearing(tmp_path: Path, }, ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] @@ -5182,7 +5593,12 @@ def test_operator_snapshot_reacquires_confirmation_forecast_after_decay( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5272,7 +5688,8 @@ def test_operator_snapshot_reacquires_confirmation_forecast_after_decay( }, ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) def _phase43_seed( @@ -5324,6 +5741,12 @@ def _phase43_seed( "src.operator_resolution_trend._target_specific_normalization_noise", lambda *_args, **_kwargs: False, ) + # the satellite reads its own import of target_specific_normalization_noise, + # not the god module's reference, so patch it there too + monkeypatch.setattr( + "src.operator_trend_closure_forecast_reacquisition_controls.target_specific_normalization_noise", + lambda *_args, **_kwargs: False, + ) summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] @@ -5332,17 +5755,26 @@ def _phase43_seed( == "reacquiring-confirmation" ) assert ( - summary["primary_target_closure_forecast_reacquisition_status"] == "reacquired-confirmation" + summary["primary_target_closure_forecast_reacquisition_status"] + == "reacquired-confirmation" ) assert summary["primary_target_transition_closure_likely_outcome"] == "confirm-soon" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-confirmation" + ) def test_operator_snapshot_reenables_early_clear_when_clearance_is_reacquired( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5432,7 +5864,8 @@ def test_operator_snapshot_reenables_early_clear_when_clearance_is_reacquired( }, ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) def _phase43_seed( @@ -5491,7 +5924,10 @@ def _phase43_seed( summary["primary_target_closure_forecast_refresh_recovery_status"] == "reacquiring-clearance" ) - assert summary["primary_target_closure_forecast_reacquisition_status"] == "reacquired-clearance" + assert ( + summary["primary_target_closure_forecast_reacquisition_status"] + == "reacquired-clearance" + ) assert summary["primary_target_transition_closure_likely_outcome"] in { "clear-risk", "expire-risk", @@ -5504,7 +5940,12 @@ def test_operator_snapshot_marks_new_confirmation_reacquisition_as_fragile( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5523,7 +5964,8 @@ def test_operator_snapshot_marks_new_confirmation_reacquisition_as_fragile( ], ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: [] + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: [], ) def _phase44_seed( @@ -5592,7 +6034,12 @@ def test_operator_snapshot_keeps_confirmation_reacquisition_when_it_is_holding( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5657,7 +6104,8 @@ def test_operator_snapshot_keeps_confirmation_reacquisition_when_it_is_holding( }, ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) def _phase44_seed( @@ -5711,6 +6159,12 @@ def _phase44_seed( "src.operator_resolution_trend._target_specific_normalization_noise", lambda *_args, **_kwargs: False, ) + # the satellite reads its own import of target_specific_normalization_noise, + # not the god module's reference, so patch it there too + monkeypatch.setattr( + "src.operator_trend_closure_forecast_reacquisition_controls.target_specific_normalization_noise", + lambda *_args, **_kwargs: False, + ) summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] @@ -5726,7 +6180,12 @@ def test_operator_snapshot_softens_reacquired_clearance_when_recovery_churns( tmp_path: Path, monkeypatch ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5795,7 +6254,8 @@ def test_operator_snapshot_softens_reacquired_clearance_when_recovery_churns( }, ] monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) def _phase44_seed( @@ -5849,13 +6309,21 @@ def _phase44_seed( "src.operator_resolution_trend._target_specific_normalization_noise", lambda *_args, **_kwargs: False, ) + # the satellite reads its own import of target_specific_normalization_noise, + # not the god module's reference, so patch it there too + monkeypatch.setattr( + "src.operator_trend_closure_forecast_reacquisition_controls.target_specific_normalization_noise", + lambda *_args, **_kwargs: False, + ) summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] assert summary["primary_target_closure_forecast_recovery_churn_status"] == "churn" assert summary["primary_target_transition_closure_likely_outcome"] == "hold" assert summary["primary_target_class_transition_resolution_status"] == "none" - assert summary["primary_target_class_reweight_transition_status"] == "pending-caution" + assert ( + summary["primary_target_class_reweight_transition_status"] == "pending-caution" + ) def test_operator_snapshot_softens_sustained_reacquisition_when_freshness_turns_mixed_age( @@ -5863,7 +6331,12 @@ def test_operator_snapshot_softens_sustained_reacquisition_when_freshness_turns_ monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -5959,7 +6432,8 @@ def test_operator_snapshot_softens_sustained_reacquisition_when_freshness_turns_ } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) def _phase44_seed( @@ -6013,10 +6487,19 @@ def _phase44_seed( "src.operator_resolution_trend._target_specific_normalization_noise", lambda *_args, **_kwargs: False, ) + # the satellite reads its own import of target_specific_normalization_noise, + # not the god module's reference, so patch it there too + monkeypatch.setattr( + "src.operator_trend_closure_forecast_reacquisition_controls.target_specific_normalization_noise", + lambda *_args, **_kwargs: False, + ) summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] - assert summary["primary_target_closure_forecast_reacquisition_freshness_status"] == "mixed-age" + assert ( + summary["primary_target_closure_forecast_reacquisition_freshness_status"] + == "mixed-age" + ) assert ( summary["primary_target_closure_forecast_reacquisition_persistence_status"] == "holding-confirmation" @@ -6033,7 +6516,12 @@ def test_operator_snapshot_resets_stale_reacquired_clearance_and_restores_pendin monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -6151,7 +6639,8 @@ def test_operator_snapshot_resets_stale_reacquired_clearance_and_restores_pendin } ) monkeypatch.setattr( - "src.operator_control_center.load_operator_state_history", lambda *_args, **_kwargs: history + "src.operator_control_center.load_operator_state_history", + lambda *_args, **_kwargs: history, ) def _phase44_seed( @@ -6205,16 +6694,33 @@ def _phase44_seed( "src.operator_resolution_trend._target_specific_normalization_noise", lambda *_args, **_kwargs: False, ) + # the satellite reads its own import of target_specific_normalization_noise, + # not the god module's reference, so patch it there too + monkeypatch.setattr( + "src.operator_trend_closure_forecast_reacquisition_controls.target_specific_normalization_noise", + lambda *_args, **_kwargs: False, + ) summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] - assert summary["primary_target_closure_forecast_reacquisition_freshness_status"] == "stale" - assert summary["primary_target_closure_forecast_persistence_reset_status"] == "clearance-reset" + assert ( + summary["primary_target_closure_forecast_reacquisition_freshness_status"] + == "stale" + ) + assert ( + summary["primary_target_closure_forecast_persistence_reset_status"] + == "clearance-reset" + ) assert summary["primary_target_closure_forecast_reacquisition_status"] == "none" - assert summary["primary_target_closure_forecast_reacquisition_persistence_status"] == "none" + assert ( + summary["primary_target_closure_forecast_reacquisition_persistence_status"] + == "none" + ) assert summary["primary_target_transition_closure_likely_outcome"] == "hold" assert summary["primary_target_class_transition_resolution_status"] == "none" - assert summary["primary_target_class_reweight_transition_status"] == "pending-caution" + assert ( + summary["primary_target_class_reweight_transition_status"] == "pending-caution" + ) def test_operator_snapshot_sets_pending_confirmation_reentry_after_confirmation_reset( @@ -6222,7 +6728,12 @@ def test_operator_snapshot_sets_pending_confirmation_reentry_after_confirmation_ monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -6329,17 +6840,24 @@ def _phase46_seed( summary["primary_target_closure_forecast_reset_reentry_status"] == "pending-confirmation-reentry" ) - assert summary["primary_target_closure_forecast_reset_reentry_persistence_status"] in { + assert summary[ + "primary_target_closure_forecast_reset_reentry_persistence_status" + ] in { "none", "insufficient-data", } - assert summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" + assert ( + summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" + ) assert ( summary["primary_target_closure_forecast_reacquisition_status"] == "pending-confirmation-reacquisition" ) assert summary["primary_target_transition_closure_likely_outcome"] == "hold" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "pending-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "pending-confirmation" + ) def test_operator_snapshot_reenters_confirmation_after_fresh_follow_through( @@ -6347,7 +6865,12 @@ def test_operator_snapshot_reenters_confirmation_after_fresh_follow_through( monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -6469,18 +6992,25 @@ def _phase46_seed( == "reentering-confirmation" ) assert ( - summary["primary_target_closure_forecast_reset_reentry_status"] == "reentered-confirmation" + summary["primary_target_closure_forecast_reset_reentry_status"] + == "reentered-confirmation" ) assert ( summary["primary_target_closure_forecast_reset_reentry_persistence_status"] == "just-reentered" ) - assert summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" assert ( - summary["primary_target_closure_forecast_reacquisition_status"] == "reacquired-confirmation" + summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" + ) + assert ( + summary["primary_target_closure_forecast_reacquisition_status"] + == "reacquired-confirmation" ) assert summary["primary_target_transition_closure_likely_outcome"] == "confirm-soon" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-confirmation" + ) def test_operator_snapshot_reenters_clearance_after_fresh_follow_through( @@ -6488,7 +7018,12 @@ def test_operator_snapshot_reenters_clearance_after_fresh_follow_through( monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -6616,17 +7151,33 @@ def _phase46_seed( summary["primary_target_closure_forecast_reset_refresh_recovery_status"] == "reentering-clearance" ) - assert summary["primary_target_closure_forecast_reset_reentry_status"] == "reentered-clearance" + assert ( + summary["primary_target_closure_forecast_reset_reentry_status"] + == "reentered-clearance" + ) assert ( summary["primary_target_closure_forecast_reset_reentry_persistence_status"] == "holding-clearance-reentry" ) - assert summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" - assert summary["primary_target_closure_forecast_reset_reentry_freshness_status"] == "fresh" - assert summary["primary_target_closure_forecast_reset_reentry_reset_status"] == "none" - assert summary["primary_target_closure_forecast_reacquisition_status"] == "reacquired-clearance" + assert ( + summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" + ) + assert ( + summary["primary_target_closure_forecast_reset_reentry_freshness_status"] + == "fresh" + ) + assert ( + summary["primary_target_closure_forecast_reset_reentry_reset_status"] == "none" + ) + assert ( + summary["primary_target_closure_forecast_reacquisition_status"] + == "reacquired-clearance" + ) assert summary["primary_target_transition_closure_likely_outcome"] == "clear-risk" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-clearance" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-clearance" + ) def test_operator_snapshot_holds_reset_reentry_when_follow_through_stays_aligned( @@ -6634,7 +7185,12 @@ def test_operator_snapshot_holds_reset_reentry_when_follow_through_stays_aligned monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -6734,9 +7290,14 @@ def _phase47_seed( summary["primary_target_closure_forecast_reset_reentry_persistence_status"] == "holding-confirmation-reentry" ) - assert summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" + assert ( + summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "none" + ) assert summary["primary_target_transition_closure_likely_outcome"] == "confirm-soon" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-confirmation" + ) def test_operator_snapshot_softens_reset_reentry_when_reentry_starts_churning( @@ -6744,7 +7305,12 @@ def test_operator_snapshot_softens_reset_reentry_when_reentry_starts_churning( monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -6882,9 +7448,14 @@ def _phase47_seed( summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] - assert summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "churn" + assert ( + summary["primary_target_closure_forecast_reset_reentry_churn_status"] == "churn" + ) assert summary["primary_target_transition_closure_likely_outcome"] == "hold" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "pending-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "pending-confirmation" + ) def test_operator_snapshot_starts_pending_confirmation_rebuild_after_reset_reentry_reset( @@ -6892,7 +7463,12 @@ def test_operator_snapshot_starts_pending_confirmation_rebuild_after_reset_reent monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -7010,7 +7586,10 @@ def _phase49_seed( == "pending-confirmation-reacquisition" ) assert summary["primary_target_transition_closure_likely_outcome"] == "hold" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "pending-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "pending-confirmation" + ) def test_operator_snapshot_rebuilds_confirmation_reentry_after_fresh_follow_through( @@ -7018,7 +7597,12 @@ def test_operator_snapshot_rebuilds_confirmation_reentry_after_fresh_follow_thro monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -7146,13 +7730,18 @@ def _phase49_seed( == "rebuilt-confirmation-reentry" ) assert ( - summary["primary_target_closure_forecast_reset_reentry_status"] == "reentered-confirmation" + summary["primary_target_closure_forecast_reset_reentry_status"] + == "reentered-confirmation" ) assert ( - summary["primary_target_closure_forecast_reacquisition_status"] == "reacquired-confirmation" + summary["primary_target_closure_forecast_reacquisition_status"] + == "reacquired-confirmation" ) assert summary["primary_target_transition_closure_likely_outcome"] == "confirm-soon" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-confirmation" + ) def test_operator_snapshot_rebuilds_clearance_reentry_after_fresh_follow_through( @@ -7160,7 +7749,12 @@ def test_operator_snapshot_rebuilds_clearance_reentry_after_fresh_follow_through monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -7287,10 +7881,19 @@ def _phase49_seed( summary["primary_target_closure_forecast_reset_reentry_rebuild_status"] == "rebuilt-clearance-reentry" ) - assert summary["primary_target_closure_forecast_reset_reentry_status"] == "reentered-clearance" - assert summary["primary_target_closure_forecast_reacquisition_status"] == "reacquired-clearance" + assert ( + summary["primary_target_closure_forecast_reset_reentry_status"] + == "reentered-clearance" + ) + assert ( + summary["primary_target_closure_forecast_reacquisition_status"] + == "reacquired-clearance" + ) assert summary["primary_target_transition_closure_likely_outcome"] == "clear-risk" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-clearance" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-clearance" + ) def test_operator_snapshot_marks_rebuilt_confirmation_as_just_rebuilt( @@ -7298,7 +7901,12 @@ def test_operator_snapshot_marks_rebuilt_confirmation_as_just_rebuilt( monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -7374,12 +7982,20 @@ def test_operator_snapshot_marks_rebuilt_confirmation_as_just_rebuilt( summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] assert ( - summary["primary_target_closure_forecast_reset_reentry_rebuild_persistence_status"] + summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_persistence_status" + ] == "just-rebuilt" ) - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_status"] == "none" + assert ( + summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_status"] + == "none" + ) assert summary["primary_target_transition_closure_likely_outcome"] == "confirm-soon" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "confirmed-confirmation" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "confirmed-confirmation" + ) def test_operator_snapshot_softens_rebuilt_clearance_when_rebuild_churn_is_high( @@ -7387,7 +8003,12 @@ def test_operator_snapshot_softens_rebuilt_clearance_when_rebuild_churn_is_high( monkeypatch, ): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -7462,17 +8083,25 @@ def test_operator_snapshot_softens_rebuilt_clearance_when_rebuild_churn_is_high( summary = build_operator_snapshot(report, output_dir=tmp_path)["operator_summary"] - assert summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_status"] == "churn" assert ( - summary["primary_target_closure_forecast_reset_reentry_rebuild_persistence_status"] + summary["primary_target_closure_forecast_reset_reentry_rebuild_churn_status"] + == "churn" + ) + assert ( + summary[ + "primary_target_closure_forecast_reset_reentry_rebuild_persistence_status" + ] == "reversing" ) assert summary["primary_target_transition_closure_likely_outcome"] == "hold" - assert summary["primary_target_closure_forecast_hysteresis_status"] == "pending-clearance" + assert ( + summary["primary_target_closure_forecast_hysteresis_status"] + == "pending-clearance" + ) def test_rebuild_freshness_softens_mixed_age_sustained_confirmation_rebuild(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_freshness_reset_control( + updates = reset_controls.apply_reset_reentry_rebuild_freshness_reset_control( { "closure_forecast_reset_reentry_rebuild_churn_status": "none", }, @@ -7497,7 +8126,10 @@ def test_rebuild_freshness_softens_mixed_age_sustained_confirmation_rebuild(): persistence_reason="Confirmation-side rebuild is now holding with enough follow-through to trust the restored forecast more.", ) - assert updates["closure_forecast_reset_reentry_rebuild_reset_status"] == "confirmation-softened" + assert ( + updates["closure_forecast_reset_reentry_rebuild_reset_status"] + == "confirmation-softened" + ) assert ( updates["closure_forecast_reset_reentry_rebuild_persistence_status"] == "holding-confirmation-rebuild" @@ -7506,7 +8138,7 @@ def test_rebuild_freshness_softens_mixed_age_sustained_confirmation_rebuild(): def test_rebuild_freshness_resets_stale_clearance_and_restores_pending_posture(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_freshness_reset_control( + updates = reset_controls.apply_reset_reentry_rebuild_freshness_reset_control( { "closure_forecast_reset_reentry_rebuild_churn_status": "none", }, @@ -7531,9 +8163,14 @@ def test_rebuild_freshness_resets_stale_clearance_and_restores_pending_posture() persistence_reason="Clearance-side rebuild is now holding with enough follow-through to trust the restored caution more.", ) - assert updates["closure_forecast_reset_reentry_rebuild_reset_status"] == "clearance-reset" + assert ( + updates["closure_forecast_reset_reentry_rebuild_reset_status"] + == "clearance-reset" + ) assert updates["closure_forecast_reset_reentry_rebuild_status"] == "none" - assert updates["closure_forecast_reset_reentry_rebuild_persistence_status"] == "none" + assert ( + updates["closure_forecast_reset_reentry_rebuild_persistence_status"] == "none" + ) assert updates["transition_closure_likely_outcome"] == "clear-risk" assert updates["class_reweight_transition_status"] == "pending-caution" assert updates["class_transition_resolution_status"] == "none" @@ -7569,9 +8206,12 @@ def test_rebuild_refresh_sets_pending_confirmation_reentry_until_fully_reearned( ) assert ( - updates["closure_forecast_reset_reentry_rebuild_status"] == "pending-confirmation-rebuild" + updates["closure_forecast_reset_reentry_rebuild_status"] + == "pending-confirmation-rebuild" + ) + assert ( + updates["closure_forecast_reset_reentry_rebuild_persistence_status"] == "none" ) - assert updates["closure_forecast_reset_reentry_rebuild_persistence_status"] == "none" assert updates["transition_closure_likely_outcome"] == "hold" assert updates["closure_forecast_hysteresis_status"] == "pending-confirmation" @@ -7605,7 +8245,10 @@ def test_rebuild_refresh_reenters_clearance_and_restores_earlier_clear_when_full persistence_reason="", ) - assert updates["closure_forecast_reset_reentry_rebuild_status"] == "rebuilt-clearance-reentry" + assert ( + updates["closure_forecast_reset_reentry_rebuild_status"] + == "rebuilt-clearance-reentry" + ) assert updates["transition_closure_likely_outcome"] == "clear-risk" assert updates["closure_forecast_hysteresis_status"] == "confirmed-clearance" assert updates["class_transition_resolution_status"] == "cleared" @@ -7674,7 +8317,7 @@ def test_rebuild_reentry_churn_softens_clearance_back_toward_hold(): def test_rebuild_reentry_refresh_sets_pending_confirmation_restore_until_fully_restored(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_reentry_refresh_restore_control( + updates = reset_controls.apply_reset_reentry_rebuild_reentry_refresh_restore_control( { "closure_forecast_reset_reentry_rebuild_reentry_freshness_status": "mixed-age", "decayed_reentered_rebuild_clearance_rate": 0.12, @@ -7702,13 +8345,16 @@ def test_rebuild_reentry_refresh_sets_pending_confirmation_restore_until_fully_r ) assert updates["closure_forecast_reset_reentry_rebuild_reentry_status"] == "none" - assert updates["closure_forecast_reset_reentry_rebuild_reentry_persistence_status"] == "none" + assert ( + updates["closure_forecast_reset_reentry_rebuild_reentry_persistence_status"] + == "none" + ) assert updates["transition_closure_likely_outcome"] == "hold" assert updates["closure_forecast_hysteresis_status"] == "pending-confirmation" def test_rebuild_reentry_refresh_restores_clearance_and_earlier_clear_when_fully_earned(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_reentry_refresh_restore_control( + updates = reset_controls.apply_reset_reentry_rebuild_reentry_refresh_restore_control( { "closure_forecast_reset_reentry_rebuild_reentry_freshness_status": "fresh", "closure_forecast_stability_status": "stable", @@ -7847,7 +8493,9 @@ def test_rebuild_reentry_restore_freshness_mixed_age_softens_confirmation_restor == "confirmation-softened" ) assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status" + ] == "holding-confirmation-rebuild-reentry-restore" ) assert updates["transition_closure_likely_outcome"] == "confirm-soon" @@ -7891,7 +8539,10 @@ def test_rebuild_reentry_restore_freshness_stale_resets_clearance_restore(): updates["closure_forecast_reset_reentry_rebuild_reentry_status"] == "pending-clearance-rebuild-reentry" ) - assert updates["closure_forecast_reset_reentry_rebuild_reentry_restore_status"] == "none" + assert ( + updates["closure_forecast_reset_reentry_rebuild_reentry_restore_status"] + == "none" + ) assert updates["class_transition_resolution_status"] == "none" @@ -7940,7 +8591,9 @@ def test_rebuild_reentry_restore_refresh_pending_confirmation_rerestore_holds_we == "pending-confirmation-rebuild-reentry-restore" ) assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status" + ] == "none" ) @@ -7992,13 +8645,15 @@ def test_rebuild_reentry_restore_refresh_rerestored_clearance_reenables_clear_po ) assert updates["class_transition_resolution_status"] == "cleared" assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_persistence_status" + ] == "none" ) def test_rererestore_refresh_pending_confirmation_rerererestore_holds_weaker_posture(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( + updates = reset_controls.apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "mixed-age", "decayed_rererestored_rebuild_reentry_clearance_rate": 0.18, @@ -8039,7 +8694,9 @@ def test_rererestore_refresh_pending_confirmation_rerererestore_holds_weaker_pos assert updates["transition_closure_likely_outcome"] == "hold" assert updates["closure_forecast_hysteresis_status"] == "pending-confirmation" assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ] == "pending-confirmation-rebuild-reentry-rererestore" ) assert ( @@ -8051,7 +8708,7 @@ def test_rererestore_refresh_pending_confirmation_rerererestore_holds_weaker_pos def test_rererestore_refresh_rerererestored_clearance_reenables_clear_posture(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( + updates = reset_controls.apply_reset_reentry_rebuild_reentry_restore_rererestore_refresh_rerererestore_control( { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "fresh", "decayed_rererestored_rebuild_reentry_clearance_rate": 0.61, @@ -8100,18 +8757,22 @@ def test_rererestore_refresh_rerererestored_clearance_reenables_clear_posture(): == "restored-clearance-rebuild-reentry" ) assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerestore_status" + ] == "rerestored-clearance-rebuild-reentry" ) assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ] == "rererestored-clearance-rebuild-reentry" ) assert updates["class_transition_resolution_status"] == "cleared" def test_rerererestore_persistence_holding_confirmation_keeps_stronger_posture(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( + updates = reset_controls.apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "fresh", }, @@ -8144,13 +8805,15 @@ def test_rerererestore_persistence_holding_confirmation_keeps_stronger_posture() assert updates["transition_closure_likely_outcome"] == "confirm-soon" assert updates["closure_forecast_hysteresis_status"] == "confirmed-confirmation" assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ] == "rererestored-confirmation-rebuild-reentry" ) def test_rerererestore_churn_softens_clearance_posture(): - updates = operator_resolution_trend._apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( + updates = reset_controls.apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control( { "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "mixed-age", }, @@ -8183,14 +8846,23 @@ def test_rerererestore_churn_softens_clearance_posture(): assert updates["transition_closure_likely_outcome"] == "clear-risk" assert updates["closure_forecast_hysteresis_status"] == "pending-clearance" assert ( - updates["closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status"] + updates[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ] == "pending-clearance-rebuild-reentry-rererestore" ) -def test_operator_snapshot_learns_when_soft_exception_was_overcautious(tmp_path: Path, monkeypatch): +def test_operator_snapshot_learns_when_soft_exception_was_overcautious( + tmp_path: Path, monkeypatch +): report = _make_report( - preflight_summary={"status": "ok", "blocking_errors": 0, "warnings": 0, "checks": []}, + preflight_summary={ + "status": "ok", + "blocking_errors": 0, + "warnings": 0, + "checks": [], + }, review_targets=[], managed_state_drift=[], governance_drift=[], @@ -8299,7 +8971,8 @@ def test_operator_snapshot_learns_when_soft_exception_was_overcautious(tmp_path: }, ) monkeypatch.setattr( - "src.operator_resolution_trend._was_resolved_then_reopened", lambda *_args, **_kwargs: True + "src.operator_resolution_trend._was_resolved_then_reopened", + lambda *_args, **_kwargs: True, ) snapshot = build_operator_snapshot(report, output_dir=tmp_path) @@ -8327,7 +9000,9 @@ def test_normalize_review_state_backfills_missing_fields(tmp_path: Path): assert isinstance(report["review_history"], list) -def test_operator_snapshot_includes_action_sync_readiness_and_queue_handoff(tmp_path: Path): +def test_operator_snapshot_includes_action_sync_readiness_and_queue_handoff( + tmp_path: Path, +): snapshot = build_operator_snapshot( _make_report( preflight_summary={"checks": []}, @@ -8400,13 +9075,18 @@ def test_operator_snapshot_includes_action_sync_readiness_and_queue_handoff(tmp_ assert "Action Sync:" in repo_item["action_sync_line"] assert repo_item["apply_packet_state"] == "preview-next" assert repo_item["apply_packet_summary"] - assert repo_item["apply_packet_command"].startswith("audit testuser --campaign security-review") + assert repo_item["apply_packet_command"].startswith( + "audit testuser --campaign security-review" + ) assert repo_item["post_apply_state"] == "no-recent-apply" assert "Post-Apply Monitoring:" in repo_item["post_apply_line"] assert repo_item["campaign_tuning_status"] == "insufficient-evidence" assert "Campaign Tuning:" in repo_item["campaign_tuning_line"] assert repo_item["historical_intelligence_status"] == "insufficient-evidence" - assert "Historical Portfolio Intelligence:" in repo_item["historical_intelligence_line"] + assert ( + "Historical Portfolio Intelligence:" + in repo_item["historical_intelligence_line"] + ) assert repo_item["automation_posture"] in { "preview-safe", "manual-only", diff --git a/tests/test_operator_control_center_artifacts.py b/tests/test_operator_control_center_artifacts.py new file mode 100644 index 0000000..33314d8 --- /dev/null +++ b/tests/test_operator_control_center_artifacts.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from datetime import datetime, timezone + +import pytest + +from src import operator_control_center_artifacts as artifacts + + +def test_control_center_artifacts_reject_credential_payload_before_writing(tmp_path, monkeypatch): + json_path = tmp_path / "control.json" + md_path = tmp_path / "control.md" + monkeypatch.setattr(artifacts, "control_center_paths", lambda *_args: (json_path, md_path)) + monkeypatch.setattr(artifacts, "load_latest_portfolio_truth", lambda *_args: (None, {})) + monkeypatch.setattr(artifacts, "build_weekly_command_center_digest", lambda *_args, **_kwargs: {}) + monkeypatch.setattr( + artifacts, + "write_weekly_command_center_artifacts", + lambda *_args, **_kwargs: (tmp_path / "weekly.json", tmp_path / "weekly.md"), + ) + monkeypatch.setattr(artifacts, "control_center_artifact_payload", lambda *_args: {"token": "secret"}) + + with pytest.raises(ValueError, match="must not persist credential fields"): + artifacts.write_control_center_artifacts( + {}, {}, tmp_path, username="user", generated_at=datetime.now(timezone.utc), report_reference="report" + ) + + assert not json_path.exists() + assert not md_path.exists() diff --git a/tests/test_operator_trend_closure_forecast_freshness.py b/tests/test_operator_trend_closure_forecast_freshness.py index d11c6d1..56b2a32 100644 --- a/tests/test_operator_trend_closure_forecast_freshness.py +++ b/tests/test_operator_trend_closure_forecast_freshness.py @@ -2,37 +2,11 @@ from src.operator_trend_closure_forecast_freshness_controls import ( apply_closure_forecast_decay_control, - closure_forecast_event_has_evidence, - closure_forecast_event_is_clearance_like, - closure_forecast_event_is_confirmation_like, - closure_forecast_event_signal_label, closure_forecast_freshness_for_target, closure_forecast_freshness_hotspots, - closure_forecast_freshness_reason, - closure_forecast_freshness_status, - recent_closure_forecast_signal_mix, ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _normalized_closure_forecast_direction(direction: str, score: float) -> str: - normalized = (direction or "neutral").strip().lower() - if normalized in {"supporting-confirmation", "supporting-clearance", "neutral"}: - return normalized - if score >= 0.05: - return "supporting-confirmation" - if score <= -0.05: - return "supporting-clearance" - return "neutral" - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - def test_closure_forecast_freshness_for_target_reports_mixed_age_signal() -> None: target = {"lane": "urgent", "kind": "config"} events = [ @@ -54,60 +28,30 @@ def test_closure_forecast_freshness_for_target_reports_mixed_age_signal() -> Non }, ] - freshness_meta = closure_forecast_freshness_for_target( - target, - events, - target_class_key=_target_class_key, - closure_forecast_event_has_evidence=lambda event: closure_forecast_event_has_evidence( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - closure_forecast_event_signal_label=lambda event: closure_forecast_event_signal_label( - event, - closure_forecast_event_is_confirmation_like=lambda value: closure_forecast_event_is_confirmation_like( - value, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - closure_forecast_event_is_clearance_like=lambda value: closure_forecast_event_is_clearance_like( - value, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - ), - closure_forecast_event_is_confirmation_like=lambda event: closure_forecast_event_is_confirmation_like( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - closure_forecast_event_is_clearance_like=lambda event: closure_forecast_event_is_clearance_like( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - class_memory_recency_weights=[1.0, 0.8, 0.6, 0.4], - history_window_runs=4, - class_closure_forecast_freshness_window_runs=2, - freshness_status=closure_forecast_freshness_status, - freshness_reason=lambda *args: closure_forecast_freshness_reason( - *args, - class_closure_forecast_freshness_window_runs=2, - ), - recent_signal_mix=recent_closure_forecast_signal_mix, - ) + freshness_meta = closure_forecast_freshness_for_target(target, events) assert freshness_meta["closure_forecast_freshness_status"] == "fresh" - assert freshness_meta["closure_forecast_memory_weight"] == 0.75 - assert freshness_meta["recent_closure_forecast_path"] == "confirmation-like -> clearance-like" + assert freshness_meta["closure_forecast_memory_weight"] == 1.0 + assert ( + freshness_meta["recent_closure_forecast_path"] + == "confirmation-like -> clearance-like -> confirmation-like" + ) + assert freshness_meta["decayed_confirmation_forecast_rate"] == 0.63 + assert freshness_meta["decayed_clearance_forecast_rate"] == 0.37 -def test_apply_closure_forecast_decay_control_blocks_confirmation_under_local_noise() -> None: +def test_apply_closure_forecast_decay_control_blocks_confirmation_under_local_noise() -> ( + None +): updates = apply_closure_forecast_decay_control( { "closure_forecast_reweight_direction": "supporting-confirmation", - "local_noise": True, }, freshness_meta={ "closure_forecast_freshness_status": "fresh", "decayed_clearance_forecast_rate": 0.0, }, - transition_history_meta={"current_transition_reversed": False}, + transition_history_meta={"recent_reopened": True}, trust_policy="act-with-review", trust_policy_reason="Current signal is actionable.", transition_status="pending-support", @@ -123,7 +67,6 @@ def test_apply_closure_forecast_decay_control_blocks_confirmation_under_local_no policy_debt_reason="", class_normalization_status="active", class_normalization_reason="", - target_specific_normalization_noise=_target_specific_normalization_noise, ) assert updates[0] == "blocked" @@ -131,7 +74,9 @@ def test_apply_closure_forecast_decay_control_blocks_confirmation_under_local_no assert updates[3] == "pending-confirmation" -def test_apply_closure_forecast_decay_control_softens_confirmed_clearance_when_stale() -> None: +def test_apply_closure_forecast_decay_control_softens_confirmed_clearance_when_stale() -> ( + None +): updates = apply_closure_forecast_decay_control( { "closure_forecast_reweight_direction": "supporting-clearance", @@ -157,7 +102,6 @@ def test_apply_closure_forecast_decay_control_softens_confirmed_clearance_when_s policy_debt_reason="", class_normalization_status="candidate", class_normalization_reason="", - target_specific_normalization_noise=_target_specific_normalization_noise, ) assert updates[0] == "clearance-decayed" @@ -186,7 +130,6 @@ def test_closure_forecast_freshness_hotspots_prefers_dominant_class_signal() -> }, ], mode="fresh", - target_class_key=_target_class_key, ) assert hotspots[0]["label"] == "urgent:config" diff --git a/tests/test_operator_trend_closure_forecast_reacquisition.py b/tests/test_operator_trend_closure_forecast_reacquisition.py index e6d2d29..42a3448 100644 --- a/tests/test_operator_trend_closure_forecast_reacquisition.py +++ b/tests/test_operator_trend_closure_forecast_reacquisition.py @@ -1,97 +1,20 @@ from __future__ import annotations -from src.operator_trend_closure_forecast_freshness_controls import closure_forecast_event_has_evidence from src.operator_trend_closure_forecast_reacquisition_controls import ( apply_closure_forecast_reacquisition_control, apply_reacquisition_persistence_and_churn_control, closure_forecast_reacquisition_hotspots, closure_forecast_reacquisition_persistence_for_target, - closure_forecast_reacquisition_side_from_event, closure_forecast_reacquisition_side_from_status, closure_forecast_reacquisition_summary, closure_forecast_recovery_churn_for_target, closure_forecast_refresh_recovery_for_target, - closure_forecast_refresh_signal_from_event, ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - -def _normalized_closure_forecast_direction(direction: str, score: float) -> str: - normalized = (direction or "neutral").strip().lower() - if normalized in {"supporting-confirmation", "supporting-clearance", "neutral"}: - return normalized - if score >= 0.05: - return "supporting-confirmation" - if score <= -0.05: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_majority(directions: list[str]) -> str: - confirmation = sum(1 for direction in directions if direction == "supporting-confirmation") - clearance = sum(1 for direction in directions if direction == "supporting-clearance") - if confirmation > clearance: - return "supporting-confirmation" - if clearance > confirmation: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_reversing(current_direction: str, earlier_majority: str) -> bool: - if current_direction == "neutral" or earlier_majority == "neutral": - return False - return current_direction != earlier_majority - - -def _recent_closure_forecast_weakened_side(events: list[dict]) -> str: - for event in events: - if event.get("closure_forecast_decay_status") == "confirmation-decayed": - return "confirmation" - if event.get("closure_forecast_decay_status") == "clearance-decayed": - return "clearance" - return "none" - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - -def _clamp_round(value: float, lower: float, upper: float) -> float: - return round(max(lower, min(upper, value)), 2) - - -def _class_direction_flip_count(directions: list[str]) -> int: - non_neutral = [direction for direction in directions if direction != "neutral"] - return sum(1 for previous, current in zip(non_neutral, non_neutral[1:]) if current != previous) - - -def _closure_forecast_refresh_path_label(event: dict) -> str: - direction = _normalized_closure_forecast_direction( - event.get("closure_forecast_reweight_direction", "neutral"), - event.get("closure_forecast_reweight_score", 0.0), - ) - if direction == "supporting-confirmation": - return "fresh confirmation" - if direction == "supporting-clearance": - return "fresh clearance" - return "neutral" - - -def _closure_forecast_reacquisition_path_label(event: dict) -> str: - status = event.get("closure_forecast_reacquisition_status", "none") or "none" - if status != "none": - return status - return event.get("transition_closure_likely_outcome", "hold") or "hold" - - -def test_closure_forecast_refresh_recovery_for_target_detects_reacquired_confirmation() -> None: +def test_closure_forecast_refresh_recovery_for_target_detects_reacquired_confirmation() -> ( + None +): target = { "lane": "urgent", "kind": "config", @@ -117,34 +40,21 @@ def test_closure_forecast_refresh_recovery_for_target_detects_reacquired_confirm }, ] - refresh_meta = closure_forecast_refresh_recovery_for_target( - target, - events, - {}, - target_class_key=_target_class_key, - closure_forecast_event_has_evidence=lambda event: closure_forecast_event_has_evidence( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - closure_forecast_refresh_signal_from_event=lambda event: closure_forecast_refresh_signal_from_event( - event, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - ), - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - recent_closure_forecast_weakened_side=_recent_closure_forecast_weakened_side, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_refresh_path_label=_closure_forecast_refresh_path_label, - class_closure_forecast_refresh_window_runs=4, - ) + refresh_meta = closure_forecast_refresh_recovery_for_target(target, events, {}) - assert refresh_meta["closure_forecast_refresh_recovery_status"] == "reacquiring-confirmation" - assert refresh_meta["closure_forecast_reacquisition_status"] == "reacquired-confirmation" + assert ( + refresh_meta["closure_forecast_refresh_recovery_status"] + == "reacquiring-confirmation" + ) + assert ( + refresh_meta["closure_forecast_reacquisition_status"] + == "reacquired-confirmation" + ) -def test_apply_closure_forecast_reacquisition_control_confirms_clearance_resolution() -> None: +def test_apply_closure_forecast_reacquisition_control_confirms_clearance_resolution() -> ( + None +): updates = apply_closure_forecast_reacquisition_control( { "class_reweight_transition_status": "pending-caution", @@ -182,7 +92,9 @@ def test_apply_closure_forecast_reacquisition_control_confirms_clearance_resolut assert updates[3] == "none" -def test_closure_forecast_reacquisition_persistence_for_target_detects_sustained_confirmation() -> None: +def test_closure_forecast_reacquisition_persistence_for_target_detects_sustained_confirmation() -> ( + None +): target = { "lane": "urgent", "kind": "config", @@ -219,20 +131,18 @@ def test_closure_forecast_reacquisition_persistence_for_target_detects_sustained target, events, {}, - target_class_key=_target_class_key, - closure_forecast_reacquisition_side_from_event=closure_forecast_reacquisition_side_from_event, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reacquisition_path_label=_closure_forecast_reacquisition_path_label, - class_reacquisition_persistence_window_runs=4, ) - assert persistence_meta["closure_forecast_reacquisition_persistence_status"] == "sustained-confirmation" + assert ( + persistence_meta["closure_forecast_reacquisition_persistence_status"] + == "sustained-confirmation" + ) assert persistence_meta["closure_forecast_reacquisition_age_runs"] == 3 -def test_apply_reacquisition_persistence_and_churn_control_softens_churning_clearance() -> None: +def test_apply_reacquisition_persistence_and_churn_control_softens_churning_clearance() -> ( + None +): updates = apply_reacquisition_persistence_and_churn_control( { "closure_forecast_reacquisition_status": "reacquired-clearance", @@ -300,13 +210,6 @@ def test_closure_forecast_recovery_churn_for_target_detects_wobble() -> None: target, events, {}, - target_class_key=_target_class_key, - closure_forecast_reacquisition_side_from_event=closure_forecast_reacquisition_side_from_event, - class_direction_flip_count=_class_direction_flip_count, - clamp_round=_clamp_round, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_reacquisition_path_label=_closure_forecast_reacquisition_path_label, - class_reacquisition_persistence_window_runs=4, ) assert churn_meta["closure_forecast_recovery_churn_status"] == "churn" @@ -336,7 +239,6 @@ def test_closure_forecast_reacquisition_hotspots_and_summary_prefer_live_risk() }, ], mode="churn", - target_class_key=_target_class_key, ) summary = closure_forecast_reacquisition_summary( @@ -347,13 +249,20 @@ def test_closure_forecast_reacquisition_hotspots_and_summary_prefer_live_risk() }, recovering_confirmation_hotspots=[], recovering_clearance_hotspots=[{"label": "blocked:setup"}], - target_label=_target_label, ) assert hotspots[0]["label"] == "blocked:setup" assert "blocked:setup" in summary -def test_closure_forecast_reacquisition_side_from_status_maps_hysteresis_labels() -> None: - assert closure_forecast_reacquisition_side_from_status("confirmed-confirmation") == "confirmation" - assert closure_forecast_reacquisition_side_from_status("holding-clearance") == "clearance" +def test_closure_forecast_reacquisition_side_from_status_maps_hysteresis_labels() -> ( + None +): + assert ( + closure_forecast_reacquisition_side_from_status("confirmed-confirmation") + == "confirmation" + ) + assert ( + closure_forecast_reacquisition_side_from_status("holding-clearance") + == "clearance" + ) diff --git a/tests/test_operator_trend_closure_forecast_reacquisition_freshness.py b/tests/test_operator_trend_closure_forecast_reacquisition_freshness.py index 61b73a2..20ccbe6 100644 --- a/tests/test_operator_trend_closure_forecast_reacquisition_freshness.py +++ b/tests/test_operator_trend_closure_forecast_reacquisition_freshness.py @@ -1,38 +1,17 @@ from __future__ import annotations -from src.operator_trend_closure_forecast_freshness_controls import closure_forecast_freshness_status -from src.operator_trend_closure_forecast_reacquisition_controls import ( - closure_forecast_reacquisition_side_from_event, - closure_forecast_reacquisition_side_from_status, -) from src.operator_trend_closure_forecast_reacquisition_controls import ( apply_reacquisition_freshness_reset_control, closure_forecast_persistence_reset_summary, closure_forecast_reacquisition_freshness_for_target, closure_forecast_reacquisition_freshness_hotspots, - closure_forecast_reacquisition_freshness_reason, closure_forecast_reacquisition_freshness_summary, - reacquisition_event_has_evidence, - reacquisition_event_is_clearance_like, - reacquisition_event_is_confirmation_like, - reacquisition_event_signal_label, - recent_reacquisition_signal_mix, ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - -def test_closure_forecast_reacquisition_freshness_for_target_reports_fresh_signal() -> None: +def test_closure_forecast_reacquisition_freshness_for_target_reports_fresh_signal() -> ( + None +): target = { "lane": "urgent", "kind": "config", @@ -59,41 +38,16 @@ def test_closure_forecast_reacquisition_freshness_for_target_reports_fresh_signa }, ] - freshness_meta = closure_forecast_reacquisition_freshness_for_target( - target, - events, - target_class_key=_target_class_key, - reacquisition_event_has_evidence=lambda event: reacquisition_event_has_evidence( - event, - reacquisition_event_is_confirmation_like=reacquisition_event_is_confirmation_like, - reacquisition_event_is_clearance_like=reacquisition_event_is_clearance_like, - ), - reacquisition_event_signal_label=lambda event: reacquisition_event_signal_label( - event, - reacquisition_event_is_confirmation_like=reacquisition_event_is_confirmation_like, - reacquisition_event_is_clearance_like=reacquisition_event_is_clearance_like, - ), - closure_forecast_reacquisition_side_from_status=closure_forecast_reacquisition_side_from_status, - closure_forecast_reacquisition_side_from_event=closure_forecast_reacquisition_side_from_event, - class_memory_recency_weights=[1.0, 0.8, 0.6, 0.4], - history_window_runs=4, - class_reacquisition_freshness_window_runs=2, - freshness_status=closure_forecast_freshness_status, - freshness_reason=lambda *args: closure_forecast_reacquisition_freshness_reason( - *args, - class_reacquisition_freshness_window_runs=2, - ), - recent_signal_mix=recent_reacquisition_signal_mix, - reacquisition_event_is_confirmation_like=reacquisition_event_is_confirmation_like, - reacquisition_event_is_clearance_like=reacquisition_event_is_clearance_like, - ) + freshness_meta = closure_forecast_reacquisition_freshness_for_target(target, events) assert freshness_meta["closure_forecast_reacquisition_freshness_status"] == "fresh" - assert freshness_meta["closure_forecast_reacquisition_memory_weight"] == 0.75 + assert freshness_meta["closure_forecast_reacquisition_memory_weight"] == 0.74 assert freshness_meta["has_fresh_aligned_recent_evidence"] is True -def test_apply_reacquisition_freshness_reset_control_resets_clearance_when_aged_out() -> None: +def test_apply_reacquisition_freshness_reset_control_resets_clearance_when_aged_out() -> ( + None +): updates = apply_reacquisition_freshness_reset_control( { "closure_forecast_recovery_churn_status": "churn", @@ -126,9 +80,6 @@ def test_apply_reacquisition_freshness_reset_control_resets_clearance_when_aged_ persistence_score=-0.4, persistence_status="sustained-clearance", persistence_reason="", - closure_forecast_reacquisition_side_from_status=closure_forecast_reacquisition_side_from_status, - closure_forecast_reacquisition_side_from_event=closure_forecast_reacquisition_side_from_event, - target_specific_normalization_noise=_target_specific_normalization_noise, ) assert updates["closure_forecast_persistence_reset_status"] == "clearance-reset" @@ -136,7 +87,9 @@ def test_apply_reacquisition_freshness_reset_control_resets_clearance_when_aged_ assert updates["closure_forecast_reacquisition_status"] == "none" -def test_closure_forecast_reacquisition_freshness_hotspots_and_summaries_track_dominant_classes() -> None: +def test_closure_forecast_reacquisition_freshness_hotspots_and_summaries_track_dominant_classes() -> ( + None +): targets = [ { "lane": "urgent", @@ -159,18 +112,18 @@ def test_closure_forecast_reacquisition_freshness_hotspots_and_summaries_track_d stale_hotspots = closure_forecast_reacquisition_freshness_hotspots( targets, mode="stale", - target_class_key=_target_class_key, ) fresh_hotspots = closure_forecast_reacquisition_freshness_hotspots( targets, mode="fresh", - target_class_key=_target_class_key, ) freshness_summary = closure_forecast_reacquisition_freshness_summary( - {"title": "RepoC", "closure_forecast_reacquisition_freshness_status": "mixed-age"}, + { + "title": "RepoC", + "closure_forecast_reacquisition_freshness_status": "mixed-age", + }, stale_hotspots, fresh_hotspots, - target_label=_target_label, ) reset_summary = closure_forecast_persistence_reset_summary( { @@ -182,7 +135,6 @@ def test_closure_forecast_reacquisition_freshness_hotspots_and_summaries_track_d }, stale_hotspots, fresh_hotspots, - target_label=_target_label, ) assert stale_hotspots[0]["label"] == "blocked:setup" diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_freshness.py b/tests/test_operator_trend_closure_forecast_reset_reentry_freshness.py index bfd3625..5a482ad 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_freshness.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_freshness.py @@ -1,6 +1,5 @@ from __future__ import annotations -from src.operator_trend_closure_forecast_freshness_controls import closure_forecast_freshness_status from src.operator_trend_closure_forecast_reset_controls import ( apply_reset_reentry_freshness_reset_control, closure_forecast_reset_reentry_freshness_for_target, @@ -10,97 +9,9 @@ ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - -def _reset_reentry_side_from_persistence_status(status: str) -> str: - if status in {"holding-confirmation-reentry", "sustained-confirmation-reentry"}: - return "confirmation" - if status in {"holding-clearance-reentry", "sustained-clearance-reentry"}: - return "clearance" - return "none" - - -def _reset_reentry_side_from_status(status: str) -> str: - if status in {"pending-confirmation-reentry", "reentered-confirmation"}: - return "confirmation" - if status in {"pending-clearance-reentry", "reentered-clearance"}: - return "clearance" - return "none" - - -def _reset_reentry_memory_side_from_event(event: dict) -> str: - side = _reset_reentry_side_from_persistence_status( - event.get("closure_forecast_reset_reentry_persistence_status", "none") - ) - if side != "none": - return side - return _reset_reentry_side_from_status( - event.get("closure_forecast_reset_reentry_status", "none") - ) - - -def _reset_reentry_event_is_confirmation_like(event: dict) -> bool: - return _reset_reentry_memory_side_from_event(event) == "confirmation" or event.get( - "transition_closure_likely_outcome", "none" - ) == "confirm-soon" - - -def _reset_reentry_event_is_clearance_like(event: dict) -> bool: - return _reset_reentry_memory_side_from_event(event) == "clearance" or event.get( - "transition_closure_likely_outcome", "none" - ) in {"clear-risk", "expire-risk"} - - -def _reset_reentry_event_has_evidence(event: dict) -> bool: - return _reset_reentry_event_is_confirmation_like( - event - ) or _reset_reentry_event_is_clearance_like(event) - - -def _reset_reentry_event_signal_label(event: dict) -> str: - if _reset_reentry_event_is_confirmation_like(event): - return "confirmation-like" - if _reset_reentry_event_is_clearance_like(event): - return "clearance-like" - return "neutral" - - -def _reset_reentry_freshness_reason( - freshness_status: str, - weighted_count: float, - recent_share: float, - confirmation_rate: float, - clearance_rate: float, -) -> str: - return ( - f"{freshness_status}:{weighted_count:.2f}:{recent_share:.2f}:" - f"{confirmation_rate:.2f}:{clearance_rate:.2f}" - ) - - -def _recent_reset_reentry_signal_mix( - weighted_count: float, - confirmation_like: float, - clearance_like: float, - recent_share: float, -) -> str: - return ( - f"{weighted_count:.2f}:{confirmation_like:.2f}:" - f"{clearance_like:.2f}:{recent_share:.2f}" - ) - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - -def test_closure_forecast_reset_reentry_freshness_for_target_reports_fresh_signal() -> None: +def test_closure_forecast_reset_reentry_freshness_for_target_reports_fresh_signal() -> ( + None +): target = { "lane": "urgent", "kind": "config", @@ -128,37 +39,19 @@ def test_closure_forecast_reset_reentry_freshness_for_target_reports_fresh_signa }, ] - freshness_meta = closure_forecast_reset_reentry_freshness_for_target( - target, - events, - target_class_key=_target_class_key, - reset_reentry_event_has_evidence=_reset_reentry_event_has_evidence, - reset_reentry_event_signal_label=_reset_reentry_event_signal_label, - closure_forecast_reset_reentry_side_from_persistence_status=( - _reset_reentry_side_from_persistence_status - ), - closure_forecast_reset_reentry_side_from_status=_reset_reentry_side_from_status, - closure_forecast_reset_reentry_memory_side_from_event=( - _reset_reentry_memory_side_from_event - ), - class_memory_recency_weights=[1.0, 0.8, 0.6, 0.4], - history_window_runs=4, - class_reset_reentry_freshness_window_runs=2, - closure_forecast_freshness_status=closure_forecast_freshness_status, - closure_forecast_reset_reentry_freshness_reason=_reset_reentry_freshness_reason, - recent_reset_reentry_signal_mix=_recent_reset_reentry_signal_mix, - reset_reentry_event_is_confirmation_like=( - _reset_reentry_event_is_confirmation_like - ), - reset_reentry_event_is_clearance_like=_reset_reentry_event_is_clearance_like, - ) + freshness_meta = closure_forecast_reset_reentry_freshness_for_target(target, events) assert freshness_meta["closure_forecast_reset_reentry_freshness_status"] == "fresh" - assert freshness_meta["closure_forecast_reset_reentry_memory_weight"] == 0.75 + # 0.74 under the real production CLASS_RESET_REENTRY_FRESHNESS_WINDOW_RUNS/ + # CLASS_MEMORY_RECENCY_WEIGHTS (wider than the old 2-run/4-weight test stand-ins), + # hand-verified by running the production code path. + assert freshness_meta["closure_forecast_reset_reentry_memory_weight"] == 0.74 assert freshness_meta["has_fresh_aligned_recent_evidence"] is True -def test_apply_reset_reentry_freshness_reset_control_resets_clearance_when_aged_out() -> None: +def test_apply_reset_reentry_freshness_reset_control_resets_clearance_when_aged_out() -> ( + None +): updates = apply_reset_reentry_freshness_reset_control( { "closure_forecast_reset_reentry_churn_status": "churn", @@ -184,11 +77,6 @@ def test_apply_reset_reentry_freshness_reset_control_resets_clearance_when_aged_ persistence_score=-0.4, persistence_status="sustained-clearance-reentry", persistence_reason="", - closure_forecast_reset_reentry_side_from_persistence_status=( - _reset_reentry_side_from_persistence_status - ), - closure_forecast_reset_reentry_side_from_status=_reset_reentry_side_from_status, - target_specific_normalization_noise=_target_specific_normalization_noise, ) assert updates["closure_forecast_reset_reentry_reset_status"] == "clearance-reset" @@ -196,7 +84,9 @@ def test_apply_reset_reentry_freshness_reset_control_resets_clearance_when_aged_ assert updates["closure_forecast_reacquisition_status"] == "none" -def test_closure_forecast_reset_reentry_freshness_hotspots_and_summaries_track_classes() -> None: +def test_closure_forecast_reset_reentry_freshness_hotspots_and_summaries_track_classes() -> ( + None +): targets = [ { "lane": "urgent", @@ -223,18 +113,18 @@ def test_closure_forecast_reset_reentry_freshness_hotspots_and_summaries_track_c stale_hotspots = closure_forecast_reset_reentry_freshness_hotspots( targets, mode="stale", - target_class_key=_target_class_key, ) fresh_hotspots = closure_forecast_reset_reentry_freshness_hotspots( targets, mode="fresh", - target_class_key=_target_class_key, ) freshness_summary = closure_forecast_reset_reentry_freshness_summary( - {"title": "RepoC", "closure_forecast_reset_reentry_freshness_status": "mixed-age"}, + { + "title": "RepoC", + "closure_forecast_reset_reentry_freshness_status": "mixed-age", + }, stale_hotspots, fresh_hotspots, - target_label=_target_label, ) reset_summary = closure_forecast_reset_reentry_reset_summary( { @@ -246,7 +136,6 @@ def test_closure_forecast_reset_reentry_freshness_hotspots_and_summaries_track_c }, stale_hotspots, fresh_hotspots, - target_label=_target_label, ) assert stale_hotspots[0]["label"] == "blocked:setup" diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild.py b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild.py index 4a39219..18a1688 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild.py @@ -9,66 +9,6 @@ ) -def _ordered_reset_reentry_events_for_target(target: dict, events: list[dict]) -> list[dict]: - class_key = f"{target.get('lane', '')}:{target.get('kind', '') or 'unknown'}" - return [event for event in events if event.get("class_key") == class_key] - - -def _normalized_closure_forecast_direction(direction: str, score: float) -> str: - normalized = (direction or "neutral").strip().lower() - if normalized in {"supporting-confirmation", "supporting-clearance", "neutral"}: - return normalized - if score >= 0.05: - return "supporting-confirmation" - if score <= -0.05: - return "supporting-clearance" - return "neutral" - - -def _clamp_round(value: float, lower: float, upper: float) -> float: - return round(max(lower, min(upper, value)), 2) - - -def _closure_forecast_direction_majority(directions: list[str]) -> str: - confirmation = sum(1 for direction in directions if direction == "supporting-confirmation") - clearance = sum(1 for direction in directions if direction == "supporting-clearance") - if confirmation > clearance: - return "supporting-confirmation" - if clearance > confirmation: - return "supporting-clearance" - return "neutral" - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - -def _closure_forecast_direction_reversing(current_direction: str, earlier_majority: str) -> bool: - if current_direction == "neutral" or earlier_majority == "neutral": - return False - return current_direction != earlier_majority - - -def _closure_forecast_reset_side_from_status(status: str) -> str: - if status in {"confirmation-softened", "confirmation-reset"}: - return "confirmation" - if status in {"clearance-softened", "clearance-reset"}: - return "clearance" - return "none" - - -def _closure_forecast_reset_reentry_refresh_path_label(event: dict) -> str: - return event.get("closure_forecast_reset_reentry_reset_status", "hold") - - -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - def test_refresh_recovery_for_target_detects_confirmation_rebuild() -> None: target = { "lane": "urgent", @@ -102,20 +42,7 @@ def test_refresh_recovery_for_target_detects_confirmation_rebuild() -> None: ] refresh_meta = closure_forecast_reset_reentry_refresh_recovery_for_target( - target, - events, - {}, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_side_from_status=_closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_reentry_refresh_path_label=( - _closure_forecast_reset_reentry_refresh_path_label - ), - class_reset_reentry_refresh_rebuild_window_runs=4, + target, events, {} ) assert ( @@ -162,8 +89,14 @@ def test_apply_reset_reentry_refresh_rebuild_control_softens_to_pending() -> Non persistence_reason="", ) - assert updates["closure_forecast_reacquisition_status"] == "pending-confirmation-reacquisition" - assert updates["closure_forecast_reset_reentry_status"] == "pending-confirmation-reentry" + assert ( + updates["closure_forecast_reacquisition_status"] + == "pending-confirmation-reacquisition" + ) + assert ( + updates["closure_forecast_reset_reentry_status"] + == "pending-confirmation-reentry" + ) def test_refresh_hotspots_and_summaries_track_active_classes() -> None: @@ -189,7 +122,6 @@ def test_refresh_hotspots_and_summaries_track_active_classes() -> None: }, ], mode="confirmation", - target_class_key=_target_class_key, ) refresh_summary = closure_forecast_reset_reentry_refresh_recovery_summary( { @@ -201,7 +133,6 @@ def test_refresh_hotspots_and_summaries_track_active_classes() -> None: }, hotspots, [], - target_label=_target_label, ) rebuild_summary = closure_forecast_reset_reentry_rebuild_summary( { @@ -210,7 +141,6 @@ def test_refresh_hotspots_and_summaries_track_active_classes() -> None: }, hotspots, [], - target_label=_target_label, ) assert hotspots[0]["label"] == "urgent:config" diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_freshness.py b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_freshness.py index f59dab1..7b759f3 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_freshness.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_freshness.py @@ -9,58 +9,6 @@ ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - -def _closure_forecast_reset_reentry_rebuild_side_from_event(event: dict) -> str: - status = event.get("closure_forecast_reset_reentry_rebuild_status", "none") - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - persistence_status = event.get("closure_forecast_reset_reentry_rebuild_persistence_status", "none") - if "confirmation" in persistence_status: - return "confirmation" - if "clearance" in persistence_status: - return "clearance" - return "none" - - -def _closure_forecast_reset_reentry_rebuild_side_from_persistence_status(status: str) -> str: - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - return "none" - - -def _closure_forecast_reset_reentry_rebuild_side_from_status(status: str) -> str: - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - return "none" - - -def _closure_forecast_freshness_status(weighted_count: float, recent_share: float) -> str: - if weighted_count < 0.5: - return "insufficient-data" - if recent_share >= 0.6: - return "fresh" - if recent_share >= 0.35: - return "mixed-age" - return "stale" - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - def test_rebuild_freshness_for_target_detects_fresh_confirmation_signal() -> None: target = { "lane": "urgent", @@ -85,24 +33,7 @@ def test_rebuild_freshness_for_target_detects_fresh_confirmation_signal() -> Non }, ] - meta = closure_forecast_reset_reentry_rebuild_freshness_for_target( - target, - events, - target_class_key=_target_class_key, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - _closure_forecast_reset_reentry_rebuild_side_from_status - ), - closure_forecast_freshness_status=_closure_forecast_freshness_status, - class_memory_recency_weights=(1.0, 0.8, 0.6, 0.4), - class_reset_reentry_rebuild_freshness_window_runs=2, - history_window_runs=4, - ) + meta = closure_forecast_reset_reentry_rebuild_freshness_for_target(target, events) assert meta["closure_forecast_reset_reentry_rebuild_freshness_status"] == "fresh" assert meta["decayed_rebuilt_confirmation_reentry_rate"] > 0.8 @@ -132,16 +63,12 @@ def test_rebuild_freshness_reset_control_softens_sustained_confirmation() -> Non persistence_score=0.42, persistence_status="sustained-confirmation-rebuild", persistence_reason="stable", - closure_forecast_reset_reentry_rebuild_side_from_persistence_status=( - _closure_forecast_reset_reentry_rebuild_side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_side_from_status=( - _closure_forecast_reset_reentry_rebuild_side_from_status - ), - target_specific_normalization_noise=_target_specific_normalization_noise, ) - assert updates["closure_forecast_reset_reentry_rebuild_reset_status"] == "confirmation-softened" + assert ( + updates["closure_forecast_reset_reentry_rebuild_reset_status"] + == "confirmation-softened" + ) assert ( updates["closure_forecast_reset_reentry_rebuild_persistence_status"] == "holding-confirmation-rebuild" @@ -175,24 +102,20 @@ def test_rebuild_freshness_hotspots_and_summaries_track_labels() -> None: fresh_hotspots = closure_forecast_reset_reentry_rebuild_freshness_hotspots( targets, mode="fresh", - target_class_key=_target_class_key, ) stale_hotspots = closure_forecast_reset_reentry_rebuild_freshness_hotspots( targets, mode="stale", - target_class_key=_target_class_key, ) freshness_summary = closure_forecast_reset_reentry_rebuild_freshness_summary( targets[0], stale_hotspots, fresh_hotspots, - target_label=_target_label, ) reset_summary = closure_forecast_reset_reentry_rebuild_reset_summary( targets[1], stale_hotspots, fresh_hotspots, - target_label=_target_label, ) assert fresh_hotspots[0]["label"] == "urgent:review" diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_persistence.py b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_persistence.py index a0bc4da..efad60c 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_persistence.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_persistence.py @@ -9,69 +9,6 @@ ) -def _ordered_reset_reentry_events_for_target(target: dict, events: list[dict]) -> list[dict]: - class_key = f"{target.get('lane', '')}:{target.get('kind', '') or 'unknown'}" - return [event for event in events if event.get("class_key") == class_key] - - -def _closure_forecast_reset_reentry_rebuild_side_from_event(event: dict) -> str: - status = event.get("closure_forecast_reset_reentry_rebuild_status", "none") - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - recovery_status = event.get("closure_forecast_reset_reentry_refresh_recovery_status", "none") - if "confirmation" in recovery_status: - return "confirmation" - if "clearance" in recovery_status: - return "clearance" - return "none" - - -def _closure_forecast_direction_majority(directions: list[str]) -> str: - confirmation = sum(1 for direction in directions if direction == "supporting-confirmation") - clearance = sum(1 for direction in directions if direction == "supporting-clearance") - if confirmation > clearance: - return "supporting-confirmation" - if clearance > confirmation: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_reversing(current_direction: str, earlier_majority: str) -> bool: - if current_direction == "neutral" or earlier_majority == "neutral": - return False - return current_direction != earlier_majority - - -def _clamp_round(value: float, lower: float, upper: float) -> float: - return round(max(lower, min(upper, value)), 2) - - -def _closure_forecast_reset_reentry_rebuild_path_label(event: dict) -> str: - return event.get("closure_forecast_reset_reentry_rebuild_status", "hold") - - -def _class_direction_flip_count(directions: list[str]) -> int: - flips = 0 - for previous, current in zip(directions, directions[1:]): - if previous != current: - flips += 1 - return flips - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - def test_persistence_for_target_detects_just_rebuilt_confirmation() -> None: target = { "lane": "urgent", @@ -95,24 +32,19 @@ def test_persistence_for_target_detects_just_rebuilt_confirmation() -> None: ] meta = closure_forecast_reset_reentry_rebuild_persistence_for_target( - target, - events, - {}, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - closure_forecast_direction_majority=_closure_forecast_direction_majority, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - clamp_round=_clamp_round, - closure_forecast_reset_reentry_rebuild_path_label=( - _closure_forecast_reset_reentry_rebuild_path_label - ), - class_reset_reentry_rebuild_persistence_window_runs=4, + target, events, {} ) - assert meta["closure_forecast_reset_reentry_rebuild_persistence_status"] == "just-rebuilt" - assert meta["closure_forecast_reset_reentry_rebuild_age_runs"] == 1 + # Under production's ordered_reset_reentry_events_for_target, the single real event + # doesn't carry a key/generated_at matching the target's queue_identity, so a second + # "current" event is synthesized from the target dict (which already carries the same + # rebuilt-confirmation-reentry status) -- two aligned confirmation runs, not one, hand- + # verified by running the production code path. + assert ( + meta["closure_forecast_reset_reentry_rebuild_persistence_status"] + == "holding-confirmation-rebuild" + ) + assert meta["closure_forecast_reset_reentry_rebuild_age_runs"] == 2 def test_churn_for_target_detects_flip_heavy_path() -> None: @@ -141,22 +73,7 @@ def test_churn_for_target_detects_flip_heavy_path() -> None: }, ] - meta = closure_forecast_reset_reentry_rebuild_churn_for_target( - target, - events, - {}, - ordered_reset_reentry_events_for_target=_ordered_reset_reentry_events_for_target, - closure_forecast_reset_reentry_rebuild_side_from_event=( - _closure_forecast_reset_reentry_rebuild_side_from_event - ), - class_direction_flip_count=_class_direction_flip_count, - target_specific_normalization_noise=_target_specific_normalization_noise, - clamp_round=_clamp_round, - closure_forecast_reset_reentry_rebuild_path_label=( - _closure_forecast_reset_reentry_rebuild_path_label - ), - class_reset_reentry_rebuild_persistence_window_runs=4, - ) + meta = closure_forecast_reset_reentry_rebuild_churn_for_target(target, events, {}) assert meta["closure_forecast_reset_reentry_rebuild_churn_status"] == "churn" assert meta["closure_forecast_reset_reentry_rebuild_churn_score"] >= 0.45 @@ -191,23 +108,19 @@ def test_hotspots_and_summaries_track_rebuild_labels() -> None: holding_hotspots = closure_forecast_reset_reentry_rebuild_hotspots( targets, mode="holding", - target_class_key=_target_class_key, ) churn_hotspots = closure_forecast_reset_reentry_rebuild_hotspots( targets, mode="churn", - target_class_key=_target_class_key, ) persistence_summary = closure_forecast_reset_reentry_rebuild_persistence_summary( targets[0], [], holding_hotspots, - target_label=_target_label, ) churn_summary = closure_forecast_reset_reentry_rebuild_churn_summary( targets[1], churn_hotspots, - target_label=_target_label, ) assert holding_hotspots[0]["label"] == "urgent:config" diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence.py b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence.py index 0c83dea..b7b1b7a 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence.py @@ -8,40 +8,40 @@ ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - def test_rerererestore_persistence_for_target_translates_status_and_text() -> None: - meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target( - { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status": ( - "pending-confirmation-rebuild-reentry-rerererestore" - ), - }, - [], - {}, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target=( - lambda _target, _events, _history: { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_age_runs": 2, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_score": 0.31, - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status": ( - "holding-confirmation-rebuild-reentry-rererestore" - ), - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason": ( - "Confirmation-side re-re-restored posture has stayed aligned." - ), - "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path": ( - "rererestored-confirmation-rebuild-reentry" - ), - } + # This wrapper translates rerererestore-vocab target/events down a tier and delegates + # to the real rererestore persistence builder (no longer an injected stand-in), then + # translates the result back up. Two aligned confirmation runs -- one with `key`/ + # `generated_at` matching the target's queue_identity so + # ordered_reset_reentry_events_for_target's current_index==0 shortcut fires -- drive + # the shared base builder's "holding" branch, hand-verified against the real code path. + target = { + "lane": "urgent", + "kind": "review", + "item_id": "T1", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status": ( + "rerererestored-confirmation-rebuild-reentry" + ), + } + events = [ + { + "class_key": "urgent:review", + "key": "T1", + "generated_at": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status": ( + "rerererestored-confirmation-rebuild-reentry" ), - ) + }, + { + "class_key": "urgent:review", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_status": ( + "rerererestored-confirmation-rebuild-reentry" + ), + }, + ] + + meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target( + target, events, {} ) assert ( @@ -50,14 +50,17 @@ def test_rerererestore_persistence_for_target_translates_status_and_text() -> No ] == "holding-confirmation-rebuild-reentry-rerererestore" ) - assert "re-re-re-restored posture" in meta[ - "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason" - ] + assert ( + "re-re-re-restored posture" + in meta[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_reason" + ] + ) assert ( meta[ "recent_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_path" ] - == "rerererestored-confirmation-rebuild-reentry" + == "rerererestored-confirmation-rebuild-reentry -> rerererestored-confirmation-rebuild-reentry" ) @@ -93,23 +96,18 @@ def test_rerererestore_hotspots_and_summary_use_labels() -> None: closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots( targets, mode="just-rerererestored", - target_class_key=_target_class_key, ) ) holding_hotspots = ( closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_hotspots( targets, mode="holding", - target_class_key=_target_class_key, ) ) - summary = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary( - targets[0], - just_hotspots, - holding_hotspots, - target_label=_target_label, - ) + summary = closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_summary( + targets[0], + just_hotspots, + holding_hotspots, ) assert just_hotspots[0]["label"] == "blocked:setup" @@ -118,27 +116,16 @@ def test_rerererestore_hotspots_and_summary_use_labels() -> None: def test_rerererestore_apply_returns_empty_defaults_without_targets() -> None: - summary = apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn( - [], - [], - current_generated_at="2026-04-17T00:00:00Z", - confidence_calibration={}, - recommendation_bucket=lambda _target: "focus", - class_closure_forecast_events=lambda *_args, **_kwargs: [], - class_transition_events=lambda *_args, **_kwargs: [], - target_class_transition_history=lambda _target, _events: {}, - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_for_target=( - lambda _target, _events, _history: {} - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rerererestore_churn_for_target=( - lambda _target, _events, _history: {} - ), - apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn_control=( - lambda *_args, **_kwargs: {} - ), - target_class_key=_target_class_key, - target_label=_target_label, - class_reset_reentry_rebuild_reentry_restore_rerererestore_window_runs=4, + summary = ( + apply_reset_reentry_rebuild_reentry_restore_rerererestore_persistence_and_churn( + [], + [], + current_generated_at="2026-04-17T00:00:00Z", + confidence_calibration={}, + class_closure_forecast_events=lambda *_args, **_kwargs: [], + class_transition_events=lambda *_args, **_kwargs: [], + target_class_transition_history=lambda _target, _events: {}, + ) ) assert ( diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness.py b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness.py index e7fe031..327941d 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness.py @@ -10,60 +10,6 @@ ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _side_from_status(status: str) -> str: - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - return "none" - - -def _side_from_persistence_status(status: str) -> str: - if "confirmation" in status: - return "confirmation" - if "clearance" in status: - return "clearance" - return "none" - - -def _side_from_event(event: dict) -> str: - status = str( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status", - "none", - ) - ) - side = _side_from_persistence_status(status) - if side != "none": - return side - return _side_from_status( - str( - event.get( - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status", - "none", - ) - ) - ) - - -def _closure_forecast_freshness_status(weighted_count: float, recent_share: float) -> str: - if weighted_count < 1.0: - return "insufficient-data" - if recent_share >= 0.65: - return "fresh" - if recent_share >= 0.35: - return "mixed-age" - return "stale" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - def test_rererestore_freshness_for_target_detects_fresh_confirmation_signal() -> None: target = { "lane": "urgent", @@ -93,25 +39,8 @@ def test_rererestore_freshness_for_target_detects_fresh_confirmation_signal() -> }, ] - meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target( - target, - events, - target_class_key=_target_class_key, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status=( - _side_from_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status=( - _side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event=( - _side_from_event - ), - closure_forecast_freshness_status=_closure_forecast_freshness_status, - class_memory_recency_weights=(1.0, 0.8, 0.6, 0.4), - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs=4, - history_window_runs=4, - ) + meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target( + target, events ) assert ( @@ -124,43 +53,34 @@ def test_rererestore_freshness_for_target_detects_fresh_confirmation_signal() -> def test_rererestore_reset_control_softens_mixed_age_confirmation_signal() -> None: - updates = ( - apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control( - { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "watch" - }, - freshness_meta={ - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "mixed-age", - "has_fresh_aligned_recent_evidence": True, - }, - transition_history_meta={}, - closure_likely_outcome="confirm-soon", - closure_hysteresis_status="confirmed-confirmation", - closure_hysteresis_reason="", - transition_status="supporting-confirmation", - transition_reason="", - resolution_status="none", - resolution_reason="", - reentry_status="reentered-confirmation", - reentry_reason="", - restore_status="restored-confirmation-rebuild-reentry", - restore_reason="", - rerestore_status="rererestored-confirmation-rebuild-reentry", - rerestore_reason="", - rererestore_status="none", - rererestore_reason="", - persistence_age_runs=3, - persistence_score=0.62, - persistence_status="sustained-confirmation-rebuild-reentry-rererestore", - persistence_reason="", - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_persistence_status=( - _side_from_persistence_status - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_status=( - _side_from_status - ), - target_specific_normalization_noise=lambda _target, _meta: False, - ) + updates = apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control( + { + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_status": "watch" + }, + freshness_meta={ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_status": "mixed-age", + "has_fresh_aligned_recent_evidence": True, + }, + transition_history_meta={}, + closure_likely_outcome="confirm-soon", + closure_hysteresis_status="confirmed-confirmation", + closure_hysteresis_reason="", + transition_status="supporting-confirmation", + transition_reason="", + resolution_status="none", + resolution_reason="", + reentry_status="reentered-confirmation", + reentry_reason="", + restore_status="restored-confirmation-rebuild-reentry", + restore_reason="", + rerestore_status="rererestored-confirmation-rebuild-reentry", + rerestore_reason="", + rererestore_status="none", + rererestore_reason="", + persistence_age_runs=3, + persistence_score=0.62, + persistence_status="sustained-confirmation-rebuild-reentry-rererestore", + persistence_reason="", ) assert ( @@ -195,35 +115,23 @@ def test_rererestore_freshness_hotspots_and_summaries_use_labels() -> None: }, ] - stale_hotspots = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( - targets, - mode="stale", - target_class_key=_target_class_key, - ) + stale_hotspots = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( + targets, + mode="stale", ) - fresh_hotspots = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( - targets, - mode="fresh", - target_class_key=_target_class_key, - ) + fresh_hotspots = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots( + targets, + mode="fresh", ) - freshness_summary = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary( - targets[0], - stale_hotspots, - fresh_hotspots, - target_label=_target_label, - ) + freshness_summary = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary( + targets[0], + stale_hotspots, + fresh_hotspots, ) - reset_summary = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary( - targets[0], - stale_hotspots, - fresh_hotspots, - target_label=_target_label, - ) + reset_summary = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary( + targets[0], + stale_hotspots, + fresh_hotspots, ) assert stale_hotspots[0]["label"] == "urgent:review" @@ -233,31 +141,16 @@ def test_rererestore_freshness_hotspots_and_summaries_use_labels() -> None: def test_rererestore_freshness_apply_returns_empty_defaults_without_targets() -> None: - summary = apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( - [], - [], - current_generated_at="2026-04-17T00:00:00Z", - confidence_calibration={}, - recommendation_bucket=lambda _target: "focus", - class_closure_forecast_events=lambda *_args, **_kwargs: [], - class_transition_events=lambda *_args, **_kwargs: [], - target_class_transition_history=lambda _target, _events: {}, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_for_target=( - lambda _target, _events: {} - ), - apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_reset_control=( - lambda *_args, **_kwargs: {} - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_hotspots=( - lambda _targets, mode: [] - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_freshness_summary=( - lambda _primary, _stale, _fresh: "" - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_reset_summary=( - lambda _primary, _stale, _fresh: "" - ), - class_reset_reentry_rebuild_reentry_restore_rererestore_freshness_window_runs=4, + summary = ( + apply_reset_reentry_rebuild_reentry_restore_rererestore_freshness_and_reset( + [], + [], + current_generated_at="2026-04-17T00:00:00Z", + confidence_calibration={}, + class_closure_forecast_events=lambda *_args, **_kwargs: [], + class_transition_events=lambda *_args, **_kwargs: [], + target_class_transition_history=lambda _target, _events: {}, + ) ) assert ( diff --git a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence.py b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence.py index 5c54749..3b02f71 100644 --- a/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence.py +++ b/tests/test_operator_trend_closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence.py @@ -6,44 +6,62 @@ closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target, closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary, ) +from src.operator_trend_support import current_closure_forecast_event_for_target -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" +def test_rererestore_persistence_uses_synthesized_current_event() -> None: + target = { + "lane": "urgent", + "kind": "review", + "item_id": "T-synthesized", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": ( + "rererestored-confirmation-rebuild-reentry" + ), + } + event = current_closure_forecast_event_for_target(target) + meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( + target, [], {} + ) -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" + assert ( + event[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status" + ] + == "rererestored-confirmation-rebuild-reentry" + ) + assert ( + meta[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_status" + ] + == "just-rererestored" + ) def test_rererestore_persistence_for_target_keeps_status_and_text() -> None: - meta = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( - { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": ( - "rererestored-confirmation-rebuild-reentry" - ), - }, - [], - {}, - ordered_reset_reentry_events_for_target=lambda _target, _events: [ - { - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": ( - "rererestored-confirmation-rebuild-reentry" - ) - } - ], - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_side_from_event=( - lambda _event: "confirmation" - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_path_label=( - lambda _event: "rererestored-confirmation-rebuild-reentry" - ), - closure_forecast_direction_majority=lambda _directions: "neutral", - closure_forecast_direction_reversing=lambda _current, _earlier: False, - clamp_round=lambda value, **_kwargs: float(value), - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs=4, - ) + # `item_id`/`key`/`generated_at` line up so ordered_reset_reentry_events_for_target's + # current_index==0 shortcut fires and returns this one event unchanged (no synthesized + # "current" event); the target's own settled status + a single aligned run drives the + # base builder's "just-*" branch, matching the original stand-in's scripted intent. + target = { + "lane": "urgent", + "kind": "review", + "item_id": "T1", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": ( + "rererestored-confirmation-rebuild-reentry" + ), + } + event = { + "class_key": "urgent:review", + "key": "T1", + "generated_at": "", + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_status": ( + "rererestored-confirmation-rebuild-reentry" + ), + } + + meta = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target( + target, [event], {} ) assert ( @@ -52,9 +70,12 @@ def test_rererestore_persistence_for_target_keeps_status_and_text() -> None: ] == "just-rererestored" ) - assert "has been re-re-restored" in meta[ - "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason" - ] + assert ( + "has been re-re-restored" + in meta[ + "closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_reason" + ] + ) assert ( meta[ "recent_reset_reentry_rebuild_reentry_restore_rererestore_persistence_path" @@ -95,23 +116,18 @@ def test_rererestore_hotspots_and_summary_use_labels() -> None: closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots( targets, mode="just-rererestored", - target_class_key=_target_class_key, ) ) holding_hotspots = ( closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots( targets, mode="holding", - target_class_key=_target_class_key, ) ) - summary = ( - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary( - targets[0], - just_hotspots, - holding_hotspots, - target_label=_target_label, - ) + summary = closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary( + targets[0], + just_hotspots, + holding_hotspots, ) assert just_hotspots[0]["label"] == "blocked:setup" @@ -120,34 +136,16 @@ def test_rererestore_hotspots_and_summary_use_labels() -> None: def test_rererestore_apply_returns_empty_defaults_without_targets() -> None: - summary = apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn( - [], - [], - current_generated_at="2026-04-17T00:00:00Z", - confidence_calibration={}, - recommendation_bucket=lambda _target: "focus", - class_closure_forecast_events=lambda *_args, **_kwargs: [], - class_transition_events=lambda *_args, **_kwargs: [], - target_class_transition_history=lambda _target, _events: {}, - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_for_target=( - lambda _target, _events, _history: {} - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_for_target=( - lambda _target, _events, _history: {} - ), - apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn_control=( - lambda *_args, **_kwargs: {} - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_hotspots=( - lambda *_args, **_kwargs: [] - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_persistence_summary=( - lambda *_args, **_kwargs: "" - ), - closure_forecast_reset_reentry_rebuild_reentry_restore_rererestore_churn_summary=( - lambda *_args, **_kwargs: "" - ), - class_reset_reentry_rebuild_reentry_restore_rererestore_window_runs=4, + summary = ( + apply_reset_reentry_rebuild_reentry_restore_rererestore_persistence_and_churn( + [], + [], + current_generated_at="2026-04-17T00:00:00Z", + confidence_calibration={}, + class_closure_forecast_events=lambda *_args, **_kwargs: [], + class_transition_events=lambda *_args, **_kwargs: [], + target_class_transition_history=lambda _target, _events: {}, + ) ) assert ( diff --git a/tests/test_operator_trend_closure_forecast_reset_refresh.py b/tests/test_operator_trend_closure_forecast_reset_refresh.py index 28095c2..7c9b5c7 100644 --- a/tests/test_operator_trend_closure_forecast_reset_refresh.py +++ b/tests/test_operator_trend_closure_forecast_reset_refresh.py @@ -5,54 +5,12 @@ closure_forecast_reset_refresh_hotspots, closure_forecast_reset_refresh_recovery_for_target, closure_forecast_reset_refresh_recovery_summary, - closure_forecast_reset_side_from_status, ) -def _target_class_key(item: dict) -> str: - return f"{item.get('lane', '')}:{item.get('kind', '') or 'unknown'}" - - -def _target_label(item: dict) -> str: - return item.get("title", "") or item.get("kind", "") or "target" - - -def _normalized_closure_forecast_direction(direction: str, score: float) -> str: - normalized = (direction or "neutral").strip().lower() - if normalized in {"supporting-confirmation", "supporting-clearance", "neutral"}: - return normalized - if score >= 0.05: - return "supporting-confirmation" - if score <= -0.05: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_majority(directions: list[str]) -> str: - confirmation = sum(1 for direction in directions if direction == "supporting-confirmation") - clearance = sum(1 for direction in directions if direction == "supporting-clearance") - if confirmation > clearance: - return "supporting-confirmation" - if clearance > confirmation: - return "supporting-clearance" - return "neutral" - - -def _closure_forecast_direction_reversing(current_direction: str, earlier_majority: str) -> bool: - if current_direction == "neutral" or earlier_majority == "neutral": - return False - return current_direction != earlier_majority - - -def _target_specific_normalization_noise(target: dict, history_meta: dict) -> bool: - return bool(target.get("local_noise") or history_meta.get("current_transition_reversed")) - - -def _clamp_round(value: float, lower: float, upper: float) -> float: - return round(max(lower, min(upper, value)), 2) - - -def test_closure_forecast_reset_refresh_recovery_for_target_detects_confirmation_reentry() -> None: +def test_closure_forecast_reset_refresh_recovery_for_target_detects_confirmation_reentry() -> ( + None +): target = { "lane": "urgent", "kind": "config", @@ -85,25 +43,22 @@ def test_closure_forecast_reset_refresh_recovery_for_target_detects_confirmation ] refresh_meta = closure_forecast_reset_refresh_recovery_for_target( - target, - events, - {}, - target_class_key=_target_class_key, - closure_forecast_reset_side_from_status=closure_forecast_reset_side_from_status, - normalized_closure_forecast_direction=_normalized_closure_forecast_direction, - clamp_round=_clamp_round, - closure_forecast_direction_majority=_closure_forecast_direction_majority, - target_specific_normalization_noise=_target_specific_normalization_noise, - closure_forecast_direction_reversing=_closure_forecast_direction_reversing, - closure_forecast_reset_refresh_path_label=lambda event: "path", - class_reset_reentry_window_runs=4, + target, events, {} ) - assert refresh_meta["closure_forecast_reset_refresh_recovery_status"] == "reentering-confirmation" - assert refresh_meta["closure_forecast_reset_reentry_status"] == "reentered-confirmation" + assert ( + refresh_meta["closure_forecast_reset_refresh_recovery_status"] + == "reentering-confirmation" + ) + assert ( + refresh_meta["closure_forecast_reset_reentry_status"] + == "reentered-confirmation" + ) -def test_apply_reset_refresh_reentry_control_softens_confirmation_when_blocked() -> None: +def test_apply_reset_refresh_reentry_control_softens_confirmation_when_blocked() -> ( + None +): updates = apply_reset_refresh_reentry_control( { "closure_forecast_reacquisition_age_runs": 2, @@ -133,10 +88,15 @@ def test_apply_reset_refresh_reentry_control_softens_confirmation_when_blocked() assert updates["transition_closure_likely_outcome"] == "hold" assert updates["closure_forecast_hysteresis_status"] == "pending-confirmation" - assert updates["closure_forecast_reacquisition_status"] == "pending-confirmation-reacquisition" + assert ( + updates["closure_forecast_reacquisition_status"] + == "pending-confirmation-reacquisition" + ) -def test_closure_forecast_reset_refresh_hotspots_and_summary_track_active_classes() -> None: +def test_closure_forecast_reset_refresh_hotspots_and_summary_track_active_classes() -> ( + None +): hotspots = closure_forecast_reset_refresh_hotspots( [ { @@ -155,7 +115,6 @@ def test_closure_forecast_reset_refresh_hotspots_and_summary_track_active_classe }, ], mode="clearance", - target_class_key=_target_class_key, ) summary = closure_forecast_reset_refresh_recovery_summary( @@ -166,7 +125,6 @@ def test_closure_forecast_reset_refresh_hotspots_and_summary_track_active_classe }, recovering_confirmation_hotspots=[], recovering_clearance_hotspots=hotspots, - target_label=_target_label, ) assert hotspots[0]["label"] == "blocked:setup" diff --git a/tests/test_portfolio_truth.py b/tests/test_portfolio_truth.py index f761f44..dec86ca 100644 --- a/tests/test_portfolio_truth.py +++ b/tests/test_portfolio_truth.py @@ -2246,7 +2246,7 @@ def test_git_default_branch_empty_when_origin_head_unset(tmp_path: Path) -> None # ── F2: warehouse-report staleness reminder ──────────────────────────────── -from src.cli import _warn_if_warehouse_report_stale # noqa: E402 +from src.portfolio_truth_status import warn_if_warehouse_report_stale # noqa: E402 def _write_warehouse_report(d: Path, username: str, date_str: str) -> None: @@ -2260,7 +2260,7 @@ class TestWarehouseStalenessReminder: def test_missing_report_warns(self, tmp_path: Path, capsys) -> None: import re - _warn_if_warehouse_report_stale(tmp_path, "saagpatel") + warn_if_warehouse_report_stale(tmp_path, "saagpatel") captured = capsys.readouterr() # print_warning word-wraps, so normalize whitespace before substring checks combined = re.sub(r"\s+", " ", captured.out + captured.err) @@ -2269,7 +2269,7 @@ def test_missing_report_warns(self, tmp_path: Path, capsys) -> None: def test_stale_report_warns(self, tmp_path: Path, capsys) -> None: _write_warehouse_report(tmp_path, "saagpatel", "2020-01-01") - _warn_if_warehouse_report_stale(tmp_path, "saagpatel") + warn_if_warehouse_report_stale(tmp_path, "saagpatel") captured = capsys.readouterr() assert "stale" in (captured.out + captured.err).lower() @@ -2277,7 +2277,7 @@ def test_fresh_report_no_warning(self, tmp_path: Path, capsys) -> None: from datetime import date _write_warehouse_report(tmp_path, "saagpatel", date.today().isoformat()) - _warn_if_warehouse_report_stale(tmp_path, "saagpatel") + warn_if_warehouse_report_stale(tmp_path, "saagpatel") captured = capsys.readouterr() combined = captured.out + captured.err assert "stale" not in combined.lower() diff --git a/tests/test_portfolio_truth_strict_signals.py b/tests/test_portfolio_truth_strict_signals.py index ae251de..7324a6c 100644 --- a/tests/test_portfolio_truth_strict_signals.py +++ b/tests/test_portfolio_truth_strict_signals.py @@ -207,10 +207,10 @@ def _make_audit_json(tmp_path: Path, username: str, repo_name: str, release_coun def test_release_count_loaded_from_audit_json(tmp_path: Path) -> None: """--portfolio-truth-include-release-count with valid audit JSON → release_count == 3.""" - from src.cli import _load_release_count_by_name + from src.portfolio_truth_status import load_release_count_by_name _make_audit_json(tmp_path, username="saagpatel", repo_name="MyRepo", release_count=3) - result = _load_release_count_by_name(output_dir=tmp_path, username="saagpatel") + result = load_release_count_by_name(output_dir=tmp_path, username="saagpatel") assert result is not None assert result.get("MyRepo") == 3 @@ -219,10 +219,10 @@ def test_release_count_no_audit_json_returns_none( tmp_path: Path, caplog: pytest.LogCaptureFixture ) -> None: """--portfolio-truth-include-release-count with no audit JSON → None returned, warning logged.""" - from src.cli import _load_release_count_by_name + from src.portfolio_truth_status import load_release_count_by_name with caplog.at_level(logging.WARNING): - result = _load_release_count_by_name(output_dir=tmp_path, username="saagpatel") + result = load_release_count_by_name(output_dir=tmp_path, username="saagpatel") assert result is None assert any("prior audit run" in record.message for record in caplog.records) @@ -230,10 +230,10 @@ def test_release_count_no_audit_json_returns_none( def test_release_count_absent_for_missing_project(tmp_path: Path) -> None: """Project not in the audit report → release_count key absent from returned dict.""" - from src.cli import _load_release_count_by_name + from src.portfolio_truth_status import load_release_count_by_name _make_audit_json(tmp_path, username="saagpatel", repo_name="KnownRepo", release_count=5) - result = _load_release_count_by_name(output_dir=tmp_path, username="saagpatel") + result = load_release_count_by_name(output_dir=tmp_path, username="saagpatel") assert result is not None assert "UnknownRepo" not in result assert result.get("KnownRepo") == 5 @@ -248,7 +248,7 @@ def _make_ghas_json(tmp_path: Path, *, username: str, entries: dict) -> Path: def test_security_alerts_loaded_from_ghas_json(tmp_path: Path) -> None: """--portfolio-truth-include-security with a valid GHAS JSON → name-keyed dict.""" - from src.cli import _load_security_alerts_by_name + from src.portfolio_truth_status import load_security_alerts_by_name _make_ghas_json( tmp_path, @@ -261,7 +261,7 @@ def test_security_alerts_loaded_from_ghas_json(tmp_path: Path) -> None: } }, ) - result = _load_security_alerts_by_name(output_dir=tmp_path, username="saagpatel") + result = load_security_alerts_by_name(output_dir=tmp_path, username="saagpatel") assert result is not None assert result["MyRepo"]["dependabot"]["critical"] == 1 @@ -270,10 +270,10 @@ def test_security_alerts_no_ghas_json_returns_none( tmp_path: Path, caplog: pytest.LogCaptureFixture ) -> None: """--portfolio-truth-include-security with no GHAS JSON → None, warning logged.""" - from src.cli import _load_security_alerts_by_name + from src.portfolio_truth_status import load_security_alerts_by_name with caplog.at_level(logging.WARNING): - result = _load_security_alerts_by_name(output_dir=tmp_path, username="saagpatel") + result = load_security_alerts_by_name(output_dir=tmp_path, username="saagpatel") assert result is None assert any("audit report --ghas-alerts" in record.message for record in caplog.records) @@ -281,7 +281,7 @@ def test_security_alerts_no_ghas_json_returns_none( def test_security_alerts_picks_latest_by_mtime(tmp_path: Path) -> None: """When multiple GHAS files exist, the most recently modified one wins.""" - from src.cli import _load_security_alerts_by_name + from src.portfolio_truth_status import load_security_alerts_by_name older = tmp_path / "ghas-alerts-saagpatel-2026-05-01.json" older.write_text(json.dumps({"MyRepo": {"dependabot": {"high": 9, "available": True}}})) @@ -295,6 +295,6 @@ def test_security_alerts_picks_latest_by_mtime(tmp_path: Path) -> None: ) os.utime(newer, (1_700_000_000, 1_700_000_000)) - result = _load_security_alerts_by_name(output_dir=tmp_path, username="saagpatel") + result = load_security_alerts_by_name(output_dir=tmp_path, username="saagpatel") assert result is not None assert result["MyRepo"]["dependabot"]["high"] == 1 diff --git a/tests/test_tier_gaps_export.py b/tests/test_tier_gaps_export.py index 22e888d..caf7ec2 100644 --- a/tests/test_tier_gaps_export.py +++ b/tests/test_tier_gaps_export.py @@ -23,7 +23,8 @@ import pytest -from src.cli import _print_tier_gaps_markdown, _run_tier_gaps_export_mode, build_subcommand_parser +from src.app.portfolio_analysis import _print_tier_gaps_markdown, _run_tier_gaps_export_mode +from src.cli import build_subcommand_parser # ── Fixtures ──────────────────────────────────────────────────────────────────