"""Replay and anchor orchestration helpers extracted from `hiveos.observe`."""

from __future__ import annotations

import json

from hiveos_trace import terminal_style as _term

_CANONICAL_ANCHOR_TYPES = {
    "model.request",
    "model.response",
    "tool.request",
    "tool.result",
    "decision.branch",
    "output.commit",
    "checkpoint.state",
    "step.generic",
}


def _print_wrapped_kv(key, value, *, indent="  "):
    for line in _term.wrap_kv(key, value, indent=indent):
        print(line)


def _continuation_viability(score):
    value = float(score or 0.0)
    if value >= 0.75:
        return "high"
    if value >= 0.5:
        return "medium"
    if value >= 0.3:
        return "low"
    return "minimal"


def _boundary_strength(anchor_category):
    category = str(anchor_category or "").strip().lower()
    if category == "checkpoint.state":
        return 1.0
    if category == "output.commit":
        return 0.9
    if category in {"tool.result", "model.response"}:
        return 0.8
    if category == "decision.branch":
        return 0.7
    if category == "step.generic":
        return 0.45
    if category in {"tool.request", "model.request"}:
        return 0.25
    return 0.2


def _idempotency_risk(anchor_category, *, idempotency_hint=None):
    hinted = str(idempotency_hint or "").strip().lower()
    if hinted in {"low", "medium", "high", "unknown"}:
        return hinted
    category = str(anchor_category or "").strip().lower()
    if category in {"checkpoint.state", "output.commit", "model.response"}:
        return "low"
    if category in {"tool.result", "decision.branch"}:
        return "medium"
    if category in {"tool.request", "model.request"}:
        return "high"
    return "unknown"


def _infer_transition(anchor_category):
    category = str(anchor_category or "").strip().lower()
    if category == "checkpoint.state":
        return ("checkpoint.resume", "decision")
    if category == "tool.result":
        return ("tool_result.resume", "decision")
    if category == "model.response":
        return ("model_response.resume", "decision")
    if category == "output.commit":
        return ("response_resume", "turn.finish")
    if category == "decision.branch":
        return ("decision_resume", "step.generic")
    if category in {"tool.request", "model.request"}:
        return ("unknown", "unknown")
    if category == "step.generic":
        return ("step_resume", "step.generic")
    return ("unknown", "unknown")


def _build_resume_envelope(
    *,
    base_run_id,
    from_step_id,
    from_checkpoint_id,
    anchor_category,
    side_effect_signals=None,
    validation_mode,
    validation_checks,
):
    anchor_id = str(from_checkpoint_id or from_step_id or "").strip() or None
    anchor_type = "checkpoint_id" if from_checkpoint_id else ("step_id" if from_step_id else None)
    closure_status = "pass" if bool(anchor_id) else "fail"
    closure_reasons = [] if bool(anchor_id) else ["anchor required for replayable resume boundary"]
    resume_phase, next_transition = _infer_transition(anchor_category)
    if not anchor_id:
        resume_phase = "unknown"
        next_transition = "unknown"
    state_sufficiency = "insufficient"
    committed_state_ref = "none"
    if from_checkpoint_id:
        state_sufficiency = "full"
        committed_state_ref = f"checkpoint://{from_checkpoint_id}"
    elif from_step_id:
        state_sufficiency = "partial"
        committed_state_ref = f"step://{from_step_id}"
    signals = side_effect_signals if isinstance(side_effect_signals, dict) else {}
    boundary_strength = _boundary_strength(anchor_category)
    idempotency_risk = _idempotency_risk(anchor_category, idempotency_hint=signals.get("idempotency_hint"))
    side_effect = bool(signals.get("side_effect"))
    external_write = bool(signals.get("external_write"))
    rank = "weak_anchor"
    score = 0.2 + (0.7 * float(boundary_strength))
    rationale = []
    if state_sufficiency == "full" and closure_status == "pass":
        rank = "stable_anchor"
        score = min(1.0, score + 0.2)
        rationale.append("checkpoint boundary with full state sufficiency")
    elif state_sufficiency == "partial" and closure_status == "pass":
        if boundary_strength >= 0.75:
            rank = "stable_anchor"
            score = min(1.0, score + 0.15)
            rationale.append("strong boundary with partial state sufficiency")
        else:
            rank = "semi_stable_anchor"
            rationale.append("partial state sufficiency")
    else:
        rationale.append("anchor/state requirements not fully satisfied")
    if str(validation_mode or "").strip().lower() == "deterministic":
        score = min(1.0, score + 0.05)
        rationale.append("deterministic validation mode selected")
    if side_effect:
        score = max(0.0, score - 0.05)
        rationale.append("side-effecting boundary detected")
    if external_write:
        score = max(0.0, score - 0.1)
        rationale.append("external write detected")
    admission_reasons = []
    if closure_status != "pass":
        admission_reasons.append("historical closure failed")
    if str(resume_phase) == "unknown" or str(next_transition) == "unknown":
        admission_reasons.append("transitional clarity unavailable")
    if str(state_sufficiency) == "insufficient":
        admission_reasons.append("state sufficiency is insufficient")
    if external_write and str(state_sufficiency) != "full":
        admission_reasons.append("external writes require checkpoint-level state for safe replay")
    if float(boundary_strength) < 0.3:
        admission_reasons.append("boundary type is transitional and not replay-safe")
    if str((validation_checks or {}).get("status") or "").strip().lower() == "fail":
        admission_reasons.append("validation checks failed")
    deterministic_gate = {
        "required_min_boundary_strength": 0.75,
        "allowed_idempotency_risk": ["low", "medium"],
    }
    if str(validation_mode or "").strip().lower() == "deterministic":
        if float(boundary_strength) < float(deterministic_gate["required_min_boundary_strength"]):
            admission_reasons.append("deterministic mode requires strong boundary")
        if str(idempotency_risk) not in set(deterministic_gate["allowed_idempotency_risk"]):
            admission_reasons.append("deterministic mode rejects high/unknown idempotency risk")
    return {
        "resume_contract_version": "1.0",
        "parent_run_id": base_run_id,
        "anchor_id": anchor_id,
        "anchor_ref_type": anchor_type,
        "boundary_type": anchor_category or None,
        "historical_closure": {"status": closure_status, "reasons": closure_reasons},
        "transition": {
            "resume_phase": resume_phase,
            "next_expected_transition": next_transition,
        },
        "state": {
            "committed_state_ref": committed_state_ref,
            "state_sufficiency": state_sufficiency,
        },
        "side_effects": {
            "unresolved_count": 1 if external_write else (0 if closure_status == "pass" else 1),
            "idempotency_risk": idempotency_risk,
            "side_effect": side_effect,
            "external_write": external_write,
        },
        "stability": {
            "rank": rank,
            "score": float(score),
            "boundary_strength": float(boundary_strength),
            "rationale": rationale,
        },
        "validation_mode": validation_mode,
        "deterministic_gate": deterministic_gate if str(validation_mode or "").strip().lower() == "deterministic" else None,
        "admission": {
            "allowed": len(admission_reasons) == 0,
            "reasons": admission_reasons,
        },
    }


def canonical_anchor_type_for_event(event):
    event_type = str(event.get("event_type") or "").strip()
    payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
    for key in ("canonical_anchor_type", "boundary_type", "anchor_type"):
        hinted = str(payload.get(key) or "").strip().lower()
        if hinted in _CANONICAL_ANCHOR_TYPES:
            return hinted
    contract = payload.get("contract_v1") if isinstance(payload.get("contract_v1"), dict) else {}
    contract_anchor = contract.get("anchor") if isinstance(contract.get("anchor"), dict) else {}
    contract_anchor_type = str(contract_anchor.get("anchor_type") or "").strip().lower()
    if contract_anchor_type in _CANONICAL_ANCHOR_TYPES:
        return contract_anchor_type
    if event_type == "observe_checkpoint":
        return "checkpoint.state"
    if event_type == "observe_output":
        return "output.commit"
    canonical_event_map = {
        "checkpoint": "checkpoint.state",
        "response.commit": "output.commit",
        "tool.request": "tool.request",
        "tool.result": "tool.result",
        "model.request": "model.request",
        "model.response": "model.response",
        "decision": "decision.branch",
        "error": "output.commit",
        "turn.start": "step.generic",
        "turn.finish": "step.generic",
    }
    if event_type in canonical_event_map:
        return canonical_event_map[event_type]
    if event_type != "observe_step":
        return None
    step_type = str(event.get("step_type") or "").strip().lower()
    phase = str(payload.get("phase") or "").strip().lower()
    step_name = str(payload.get("step_name") or "").strip().lower()
    if step_type == "branch":
        return "decision.branch"
    if step_type == "tool_call":
        if phase in {"start", "request"}:
            return "tool.request"
        if phase in {"end", "result", "finish", "complete", "completed"}:
            return "tool.result"
        return "tool.result"
    if step_type in {"model", "llm"}:
        if phase in {"start", "request"}:
            return "model.request"
        if phase in {"end", "response", "finish", "complete", "completed"}:
            return "model.response"
    if "tool.result" in step_name:
        return "tool.result"
    if "tool.request" in step_name:
        return "tool.request"
    if "model.response" in step_name:
        return "model.response"
    if "model.request" in step_name:
        return "model.request"
    if "response.commit" in step_name or "command.finish" in step_name:
        return "output.commit"
    if "decision" in step_name or "branch" in step_name:
        return "decision.branch"
    return "step.generic"


def _extract_side_effect_signals(event):
    payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
    hint = str(payload.get("idempotency_hint") or payload.get("idempotency_risk") or "").strip().lower()
    if hint not in {"low", "medium", "high", "unknown"}:
        hint = None
    return {
        "side_effect": bool(payload.get("side_effect")),
        "external_write": bool(payload.get("external_write")),
        "idempotency_hint": hint,
    }


def _run_replay_context(events):
    usage_markers = (
        "required option",
        "missing required",
        "too many arguments",
        "expected 0 arguments",
        "unknown option",
        "unrecognized argument",
        "not recognized as an internal",
        "usage:",
    )
    invocation_failure = False
    output_commit_count = 0
    successful_tool_result_count = 0
    side_effect_event_count = 0
    external_write_event_count = 0
    checkpoint_anchor_count = 0
    for event in list(events or []):
        event_type = str(event.get("event_type") or "").strip()
        payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
        anchor_type = canonical_anchor_type_for_event(event)
        if anchor_type == "checkpoint.state":
            checkpoint_anchor_count += 1
        if anchor_type == "output.commit":
            text = str(payload.get("text") or payload.get("error") or "").strip()
            if text:
                output_commit_count += 1
                lowered = text.lower()
                if any(marker in lowered for marker in usage_markers):
                    invocation_failure = True
        if anchor_type == "tool.result":
            if str(event.get("outcome") or "").strip().lower() == "success":
                successful_tool_result_count += 1
        if bool(payload.get("side_effect")):
            side_effect_event_count += 1
        if bool(payload.get("external_write")):
            external_write_event_count += 1
        if event_type in {"tool.result", "turn.finish", "observe_run_finished", "observe_step"}:
            exit_code = payload.get("exit_code")
            try:
                if exit_code is not None and int(exit_code) != 0:
                    invocation_failure = True
            except Exception:
                pass
    return {
        "invocation_failure": invocation_failure,
        "output_commit_count": int(output_commit_count),
        "successful_tool_result_count": int(successful_tool_result_count),
        "side_effect_event_count": int(side_effect_event_count),
        "external_write_event_count": int(external_write_event_count),
        "checkpoint_anchor_count": int(checkpoint_anchor_count),
    }


def _replay_utility_for_anchor(*, anchor, events, first_failure_index, run_context):
    event_index = int(anchor.get("event_index") or 0)
    anchor_type = str(anchor.get("anchor_type") or "").strip().lower()
    checkpoint_id = str(anchor.get("checkpoint_id") or "").strip()
    score = 1.0
    rationale = []
    if checkpoint_id:
        score = min(1.0, score + 0.1)
        rationale.append("checkpoint anchor includes resumable state reference")
    if int((run_context or {}).get("external_write_event_count") or 0) > 0:
        if checkpoint_id:
            score = min(1.0, score + 0.1)
            rationale.append("checkpoint anchor improves continuation confidence for side-effecting run")
        else:
            score -= 0.25
            rationale.append("side-effecting run without checkpoint anchor lowers continuation confidence")
    if int((run_context or {}).get("successful_tool_result_count") or 0) <= 0:
        score -= 0.2
        rationale.append("no successful tool result committed before this boundary")
    if int((run_context or {}).get("output_commit_count") or 0) <= 1:
        score -= 0.15
        rationale.append("minimal output state captured for continuation")
    if first_failure_index is not None and event_index >= int(first_failure_index):
        score -= 0.2
        rationale.append("boundary is at/after first failure event")
    if bool((run_context or {}).get("invocation_failure")):
        score -= 0.35
        rationale.append("invocation failure signals detected (likely argument/launch issue)")
    if anchor_type == "output.commit" and int((run_context or {}).get("output_commit_count") or 0) <= 1:
        score -= 0.15
        rationale.append("output.commit exists but lacks rich continuation state")
    score = max(0.0, min(1.0, float(score)))
    return {
        "replay_utility_score": float(score),
        "continuation_viability": _continuation_viability(score),
        "replay_utility_rationale": rationale,
    }


def _recommended_utility_with_validation_mode(item, *, validation_mode):
    score = float(item.get("replay_utility_score") or 0.0)
    rationale = list(item.get("replay_utility_rationale") or [])
    mode = str(validation_mode or "").strip().lower()
    checkpoint_ref = str(item.get("from_checkpoint_id") or "").strip()
    side_effect = bool(item.get("side_effect"))
    external_write = bool(item.get("external_write"))
    if mode == "deterministic" and (side_effect or external_write):
        if checkpoint_ref:
            score = min(1.0, score + 0.15)
            rationale.append("deterministic mode prefers checkpoint anchor on side-effecting path")
        else:
            score = max(0.0, score - 0.2)
            rationale.append("deterministic mode penalizes non-checkpoint anchor on side-effecting path")
    return score, rationale


def _best_anchor_for_step(step_id, anchors):
    sid = str(step_id or "").strip()
    if not sid:
        return None
    candidates = [item for item in (anchors or []) if str(item.get("step_id") or "").strip() == sid]
    if not candidates:
        return None
    ranked = sorted(
        candidates,
        key=lambda item: (
            float(_boundary_strength(item.get("anchor_type"))),
            str(item.get("timestamp") or ""),
        ),
        reverse=True,
    )
    return ranked[0]


def _evaluate_recommended_candidates(*, base_run_id, recommended, anchors, validation_mode):
    evaluated = []
    for item in list(recommended or []):
        checkpoint_candidate = str(item.get("from_checkpoint_id") or "").strip()
        step_candidate = str(item.get("from_step_id") or "").strip()
        side_effect_signals = {}
        if step_candidate:
            best = _best_anchor_for_step(step_candidate, anchors)
            if best:
                side_effect_signals = dict(best.get("side_effect_signals") or {})
        probe = _build_resume_envelope(
            base_run_id=base_run_id,
            from_step_id=step_candidate,
            from_checkpoint_id=checkpoint_candidate,
            anchor_category=str(item.get("anchor_type") or "").strip(),
            side_effect_signals=side_effect_signals,
            validation_mode=validation_mode,
            validation_checks={"status": "pass"},
        )
        admission = probe.get("admission") if isinstance(probe.get("admission"), dict) else {}
        admission_allowed = bool(admission.get("allowed"))
        admission_reasons = list(admission.get("reasons") or [])
        stability = probe.get("stability") if isinstance(probe.get("stability"), dict) else {}
        side_effects = probe.get("side_effects") if isinstance(probe.get("side_effects"), dict) else {}
        deterministic_mode = str(validation_mode or "").strip().lower() == "deterministic"
        side_effecting_run = bool(item.get("side_effecting_run"))
        if deterministic_mode and side_effecting_run and (not checkpoint_candidate):
            admission_allowed = False
            reason = "deterministic mode requires checkpoint anchor on side-effecting runs"
            if reason not in admission_reasons:
                admission_reasons.append(reason)
        raw_utility = float(item.get("replay_utility_score") or 0.0)
        utility_score, utility_rationale = _recommended_utility_with_validation_mode(
            {
                "replay_utility_score": raw_utility,
                "replay_utility_rationale": list(item.get("replay_utility_rationale") or []),
                "from_checkpoint_id": checkpoint_candidate or None,
                "side_effect": bool(side_effects.get("side_effect") or item.get("side_effect")),
                "external_write": bool(side_effects.get("external_write") or item.get("external_write")),
            },
            validation_mode=validation_mode,
        )
        evaluated.append(
            {
                "anchor_id": str(item.get("anchor_id") or "").strip() or None,
                "anchor_type": str(item.get("anchor_type") or "").strip() or None,
                "from_step_id": step_candidate or None,
                "from_checkpoint_id": checkpoint_candidate or None,
                "admission_allowed": admission_allowed,
                "admission_reasons": admission_reasons,
                "stability_rank": str(stability.get("rank") or item.get("stability_rank") or "").strip() or None,
                "stability_score": float(stability.get("score") or item.get("stability_score") or 0.0),
                "boundary_strength": float(stability.get("boundary_strength") or item.get("boundary_strength") or 0.0),
                "idempotency_risk": str(side_effects.get("idempotency_risk") or item.get("idempotency_risk") or "unknown"),
                "side_effect": bool(side_effects.get("side_effect") or item.get("side_effect")),
                "external_write": bool(side_effects.get("external_write") or item.get("external_write")),
                "failure_proximity": item.get("failure_proximity"),
                "failure_proximity_score": item.get("failure_proximity_score"),
                "replay_utility_score": float(utility_score),
                "continuation_viability": _continuation_viability(utility_score),
                "replay_utility_rationale": utility_rationale,
                "recommendation_rationale": list(stability.get("rationale") or item.get("recommendation_rationale") or []),
            }
        )
    evaluated.sort(
        key=lambda value: (
            int(bool(value.get("admission_allowed"))),
            float(value.get("replay_utility_score") or 0.0),
            float(value.get("stability_score") or 0.0),
            float(value.get("failure_proximity_score") or 0.0),
        ),
        reverse=True,
    )
    return evaluated


def run_has_step_id(run_id, step_id, *, event_limit=50000, read_run_record, read_trace_events_for_run, read_trace_events):
    rid = str(run_id or "").strip()
    sid = str(step_id or "").strip()
    if not rid or not sid:
        return False
    record = read_run_record(rid) or {}
    preferred_log = str(record.get("trace_log_path") or "").strip()
    events = read_trace_events_for_run(rid, limit=max(1, min(50000, int(event_limit))), trace_log_path=preferred_log)
    if not events:
        events = read_trace_events(limit=max(1, min(50000, int(event_limit))), filters={"run_id": rid})
    for event in events:
        if str(event.get("step_id") or "").strip() == sid:
            return True
    return False


def run_has_checkpoint_id(
    run_id,
    checkpoint_id,
    *,
    event_limit=50000,
    read_run_record,
    read_trace_events_for_run,
    read_trace_events,
):
    rid = str(run_id or "").strip()
    cid = str(checkpoint_id or "").strip()
    if not rid or not cid:
        return False
    record = read_run_record(rid) or {}
    preferred_log = str(record.get("trace_log_path") or "").strip()
    events = read_trace_events_for_run(rid, limit=max(1, min(50000, int(event_limit))), trace_log_path=preferred_log)
    if not events:
        events = read_trace_events(limit=max(1, min(50000, int(event_limit))), filters={"run_id": rid})
    for event in events:
        event_type = str(event.get("event_type") or "").strip()
        payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
        checkpoint_id = ""
        if event_type == "observe_checkpoint":
            checkpoint_id = str(payload.get("checkpoint_id") or "").strip()
        elif event_type == "checkpoint":
            checkpoint_id = str(payload.get("checkpoint_id") or "").strip()
            if not checkpoint_id:
                contract = payload.get("contract_v1") if isinstance(payload.get("contract_v1"), dict) else {}
                anchor = contract.get("anchor") if isinstance(contract.get("anchor"), dict) else {}
                checkpoint_id = str(anchor.get("anchor_id") or "").strip()
        if checkpoint_id == cid:
            return True
    return False


def _derive_replay_command_from_events(
    run_id,
    *,
    read_run_record,
    read_trace_events_for_run,
    read_trace_events,
):
    rid = str(run_id or "").strip()
    if not rid:
        return ""
    record = read_run_record(rid) or {}
    preferred_log = str(record.get("trace_log_path") or "").strip()
    events = read_trace_events_for_run(rid, limit=5000, trace_log_path=preferred_log)
    if not events:
        events = read_trace_events(limit=5000, filters={"run_id": rid})
    for event in events:
        payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
        argv = payload.get("command_argv")
        if isinstance(argv, list):
            replay_argv = [str(part) for part in argv if str(part).strip()]
            if replay_argv:
                return replay_argv
        command = str(payload.get("command") or "").strip()
        if command:
            return command
    return ""


def resolve_replay_plan(
    args,
    *,
    read_run_record,
    run_has_step_id,
    run_has_checkpoint_id,
    read_trace_events_for_run,
    read_trace_events,
    resolve_ui_url_for_command,
    collect_run_anchors_fn=None,
):
    base_run_id = str(args.run_id or "").strip()
    if not base_run_id:
        raise SystemExit("run_id is required")
    base = read_run_record(base_run_id)
    if not base:
        raise SystemExit(f"run_id not found: {base_run_id}")
    base_argv = base.get("argv")
    if isinstance(base_argv, list) and base_argv:
        replay_command = [str(part) for part in base_argv if str(part)]
    else:
        replay_command = str(base.get("command") or "").strip()
    if not replay_command:
        replay_command = _derive_replay_command_from_events(
            base_run_id,
            read_run_record=read_run_record,
            read_trace_events_for_run=read_trace_events_for_run,
            read_trace_events=read_trace_events,
        )
    if not replay_command:
        raise SystemExit(f"run command missing for run_id: {base_run_id}")
    run_name = str(args.run_name or "").strip()
    if not run_name:
        run_name = f"replay:{base_run_id}"
    from_step_id = str(getattr(args, "from_step_id", "") or "").strip()
    from_checkpoint_id = str(getattr(args, "from_checkpoint_id", "") or "").strip()
    use_recommended = bool(getattr(args, "recommended", False))
    explain_requested = bool(getattr(args, "explain", False))
    validation_mode = str(getattr(args, "validation_mode", "") or "tolerant").strip().lower()
    if validation_mode not in {"deterministic", "tolerant"}:
        raise SystemExit("validation_mode must be one of: deterministic, tolerant")
    if use_recommended and (from_step_id or from_checkpoint_id):
        raise SystemExit("--recommended cannot be combined with explicit anchor flags")
    recommendation_used = {}
    recommendation_context = {}
    if use_recommended and (not from_step_id) and (not from_checkpoint_id):
        if collect_run_anchors_fn is None:
            raise SystemExit("recommended anchor resolution unavailable")
        anchors_payload = collect_run_anchors_fn(base_run_id, event_limit=5000) or {}
        recommended = list(anchors_payload.get("recommended_replay_anchors") or [])
        anchors = list(anchors_payload.get("anchors") or [])
        evaluated = _evaluate_recommended_candidates(
            base_run_id=base_run_id,
            recommended=recommended,
            anchors=anchors,
            validation_mode=validation_mode,
        )
        selected = None
        for item in evaluated:
            if bool(item.get("admission_allowed")):
                selected = item
                break
        if not selected:
            if str(validation_mode or "").strip().lower() == "deterministic":
                side_effecting = any(bool(item.get("side_effecting_run")) for item in list(recommended or []))
                checkpoint_available = any(bool(item.get("checkpoint_anchor_available")) for item in list(recommended or []))
                if side_effecting and (not checkpoint_available):
                    raise SystemExit(
                        "no admissible recommended replay anchors found on source run; "
                        "deterministic side-effecting run requires checkpoint anchor. "
                        "hint: hive trace checkpoint <run_id> <checkpoint_id> --step-name <step_name> --state-ref <state_ref>"
                    )
            raise SystemExit("no admissible recommended replay anchors found on source run")
        from_checkpoint_id = str(selected.get("from_checkpoint_id") or "").strip()
        from_step_id = str(selected.get("from_step_id") or "").strip()
        recommendation_used = {
            "anchor_id": str(selected.get("anchor_id") or "").strip() or None,
            "anchor_type": str(selected.get("anchor_type") or "").strip() or None,
            "stability_rank": str(selected.get("stability_rank") or "").strip() or None,
            "stability_score": float(selected.get("stability_score") or 0.0),
            "replay_utility_score": float(selected.get("replay_utility_score") or 0.0),
            "continuation_viability": str(selected.get("continuation_viability") or "").strip() or None,
            "admission_allowed": bool(selected.get("admission_allowed")),
            "recommendation_rationale": list(selected.get("recommendation_rationale") or []),
            "replay_utility_rationale": list(selected.get("replay_utility_rationale") or []),
            "admission_reasons": list(selected.get("admission_reasons") or []),
        }
        if from_checkpoint_id:
            recommendation_used["anchor_ref_type"] = "checkpoint_id"
        elif from_step_id:
            recommendation_used["anchor_ref_type"] = "step_id"
        skipped = []
        for item in evaluated:
            if str(item.get("anchor_id") or "").strip() == str(selected.get("anchor_id") or "").strip():
                continue
            skipped.append(
                {
                    "anchor_id": str(item.get("anchor_id") or "").strip() or None,
                    "anchor_type": str(item.get("anchor_type") or "").strip() or None,
                    "admission_allowed": bool(item.get("admission_allowed")),
                    "admission_reasons": list(item.get("admission_reasons") or []),
                    "stability_rank": str(item.get("stability_rank") or "").strip() or None,
                    "stability_score": float(item.get("stability_score") or 0.0),
                    "replay_utility_score": float(item.get("replay_utility_score") or 0.0),
                    "continuation_viability": str(item.get("continuation_viability") or "").strip() or None,
                }
            )
        recommendation_context = {
            "mode": "auto",
            "evaluated_count": len(evaluated),
            "selected": dict(recommendation_used),
            "skipped": skipped[:5],
        }
    if from_step_id and from_checkpoint_id:
        raise SystemExit("Choose only one of --from-step-id or --from-checkpoint-id")
    if validation_mode == "deterministic" and (not from_step_id) and (not from_checkpoint_id):
        raise SystemExit("deterministic validation-mode requires --from-step-id or --from-checkpoint-id")
    if from_step_id and not run_has_step_id(base_run_id, from_step_id):
        raise SystemExit(f"step_id not found on source run: {from_step_id}")
    if from_checkpoint_id and not run_has_checkpoint_id(base_run_id, from_checkpoint_id):
        raise SystemExit(f"checkpoint_id not found on source run: {from_checkpoint_id}")
    raw_selected = list(getattr(args, "select_step", []) or [])
    if raw_selected and from_checkpoint_id:
        raise SystemExit("--select-step cannot be used with --from-checkpoint-id")
    if raw_selected and not from_step_id:
        raise SystemExit("--select-step currently requires --from-step-id")
    selected_steps = []
    seen_selected = set()
    for raw in raw_selected:
        sid = str(raw or "").strip()
        if not sid or sid in seen_selected:
            continue
        if not run_has_step_id(base_run_id, sid):
            raise SystemExit(f"selected step_id not found on source run: {sid}")
        seen_selected.add(sid)
        selected_steps.append(sid)
    replay_cwd = str(args.cwd or "").strip() or str(base.get("cwd") or "").strip() or None
    record_fields = {
        "replay_of_run_id": base_run_id,
        "source": "replay",
        "replay_validation_mode": validation_mode,
    }
    anchors_payload = None
    if collect_run_anchors_fn is not None and (from_step_id or from_checkpoint_id or use_recommended):
        anchors_payload = collect_run_anchors_fn(base_run_id, event_limit=5000) or {}
    if from_step_id:
        record_fields["replay_from_step_id"] = from_step_id
        record_fields["replay_anchor_type"] = "step_id"
        record_fields["replay_anchor_category"] = "step.generic"
    if from_checkpoint_id:
        record_fields["replay_from_checkpoint_id"] = from_checkpoint_id
        record_fields["replay_anchor_type"] = "checkpoint_id"
        record_fields["replay_anchor_category"] = "checkpoint.state"
    step_anchor_signals = {}
    anchor_category = None
    if from_checkpoint_id:
        anchor_category = "checkpoint.state"
    elif from_step_id:
        anchor_category = "step.generic"
        best = _best_anchor_for_step(from_step_id, (anchors_payload or {}).get("anchors") or [])
        if best:
            inferred = str(best.get("anchor_type") or "").strip()
            if inferred:
                anchor_category = inferred
                record_fields["replay_anchor_category"] = inferred
            step_anchor_signals = dict(best.get("side_effect_signals") or {})
    branch_preview = {
        "mode": "selected_subgraph_preview" if selected_steps else "full_replay_preview",
        "selected_step_ids": selected_steps,
        "preview_only": bool(selected_steps),
        "selection_validation": {
            "anchor_step_id": from_step_id or None,
            "requires_anchor_step": bool(selected_steps),
            "selected_count": len(selected_steps),
        },
    }
    validation_checks = {
        "mode": validation_mode,
        "anchor_present": bool(from_step_id or from_checkpoint_id),
        "anchor_type": "checkpoint_id" if from_checkpoint_id else ("step_id" if from_step_id else None),
        "selected_step_count": len(selected_steps),
        "status": "pass",
        "notes": [],
    }
    if validation_mode == "deterministic":
        if not validation_checks["anchor_present"]:
            validation_checks["status"] = "fail"
            validation_checks["notes"].append("anchor required for deterministic mode")
        else:
            validation_checks["notes"].append("anchor present")
    else:
        validation_checks["notes"].append("tolerant mode allows non-anchored replay")
    if selected_steps:
        record_fields["replay_selected_step_ids"] = list(selected_steps)
    if recommendation_used:
        record_fields["replay_recommended_anchor"] = dict(recommendation_used)
    if explain_requested and (collect_run_anchors_fn is not None) and (not recommendation_context):
        explain_payload = collect_run_anchors_fn(base_run_id, event_limit=5000) or {}
        explain_candidates = _evaluate_recommended_candidates(
            base_run_id=base_run_id,
            recommended=list(explain_payload.get("recommended_replay_anchors") or []),
            anchors=list(explain_payload.get("anchors") or []),
            validation_mode=validation_mode,
        )
        selected = None
        for item in explain_candidates:
            if from_checkpoint_id and str(item.get("from_checkpoint_id") or "") == from_checkpoint_id:
                selected = item
                break
            if from_step_id and str(item.get("from_step_id") or "") == from_step_id:
                selected = item
                break
        skipped = []
        for item in explain_candidates:
            if selected and str(item.get("anchor_id") or "") == str(selected.get("anchor_id") or ""):
                continue
            skipped.append(item)
        recommendation_context = {
            "mode": "advisory",
            "evaluated_count": len(explain_candidates),
            "selected": selected or {},
            "skipped": skipped[:5],
        }
    resume_envelope = _build_resume_envelope(
        base_run_id=base_run_id,
        from_step_id=from_step_id,
        from_checkpoint_id=from_checkpoint_id,
        anchor_category=anchor_category,
        side_effect_signals=step_anchor_signals if from_step_id else {},
        validation_mode=validation_mode,
        validation_checks=validation_checks,
    )
    return {
        "base_run_id": base_run_id,
        "replay_command": replay_command,
        "run_name": run_name,
        "replay_cwd": replay_cwd,
        "from_step_id": from_step_id,
        "from_checkpoint_id": from_checkpoint_id,
        "validation_mode": validation_mode,
        "validation_checks": validation_checks,
        "anchor_category": anchor_category,
        "branch_preview": branch_preview,
        "resume_envelope": resume_envelope,
        "recommendation_used": recommendation_used,
        "recommendation_context": recommendation_context,
        "record_fields": record_fields,
        "ui_url": resolve_ui_url_for_command(args),
    }


def execute_replay_from_plan(plan, *, timeout_sec=None, run_command_observed, build_ui_url):
    result = run_command_observed(
        plan["replay_command"],
        run_name=plan["run_name"],
        cwd=plan["replay_cwd"],
        timeout_sec=timeout_sec,
        agent_id="observer.replay",
        open_ui_url=plan["ui_url"],
        record_fields=plan["record_fields"],
    )
    line = (
        f"run_id={result['run_id']} status={result['status']} duration_ms={result['duration_ms']} "
        f"replay_of={plan['base_run_id']}"
    )
    if plan["from_step_id"]:
        line += f" from_step_id={plan['from_step_id']}"
    if plan["from_checkpoint_id"]:
        line += f" from_checkpoint_id={plan['from_checkpoint_id']}"
    if plan.get("anchor_category"):
        line += f" anchor_type={plan['anchor_category']}"
    line += f" validation_mode={plan['validation_mode']}"
    checks = plan.get("validation_checks") if isinstance(plan.get("validation_checks"), dict) else {}
    if checks:
        line += f" validation_status={checks.get('status')}"
    print(line)
    if plan["ui_url"]:
        print(f"ui={build_ui_url(plan['ui_url'], result['run_id'])}")
    return int(result["exit_code"])


def handle_trace_replay(args, *, resolve_replay_plan_fn, execute_replay_from_plan_fn):
    plan = resolve_replay_plan_fn(args)
    return execute_replay_from_plan_fn(plan, timeout_sec=args.timeout_sec or None)


def handle_trace_replay_plan(
    args,
    *,
    resolve_replay_plan_fn,
    execute_replay_from_plan_fn,
    write_replay_plan_artifact_fn=None,
):
    try:
        plan = resolve_replay_plan_fn(args)
    except SystemExit as exc:
        message = str(exc)
        if bool(getattr(args, "json", False)):
            run_id = str(getattr(args, "run_id", "") or "").strip() or None
            validation_mode = str(getattr(args, "validation_mode", "") or "tolerant").strip().lower()
            suggested_checkpoint_command = None
            if (
                bool(getattr(args, "recommended", False))
                and validation_mode == "deterministic"
                and "requires checkpoint anchor" in message
                and run_id
            ):
                suggested_checkpoint_command = (
                    f"hive trace checkpoint {run_id} ckpt:auto --auto-id --from-step-id <step_id> "
                    f"--step-name <step_name> --state-ref <state_ref>"
                )
            payload = {
                "ok": False,
                "reason": "replay_plan_resolution_failed",
                "error": message,
                "run_id": run_id,
                "validation_mode": validation_mode,
                "suggested_checkpoint_command": suggested_checkpoint_command,
            }
            print(json.dumps(payload, separators=(",", ":")))
            return 1
        raise
    payload = {
        "replay_of_run_id": plan["base_run_id"],
        "run_name": plan["run_name"],
        "replay_command": plan["replay_command"],
        "replay_cwd": plan["replay_cwd"],
        "from_step_id": plan["from_step_id"] or None,
        "from_checkpoint_id": plan["from_checkpoint_id"] or None,
        "validation_mode": plan["validation_mode"],
        "validation_checks": plan.get("validation_checks") or {},
        "anchor_type": plan.get("anchor_category") or None,
        "branch_preview": plan.get("branch_preview") or {},
        "resume_envelope": plan.get("resume_envelope") or {},
        "recommendation_used": plan.get("recommendation_used") or {},
        "recommendation_context": plan.get("recommendation_context") or {},
        "record_fields": plan["record_fields"],
        "source_window": {
            "source_run_id": plan["base_run_id"],
            "anchor": {
                "anchor_type": "checkpoint_id"
                if plan["from_checkpoint_id"]
                else ("step_id" if plan["from_step_id"] else None),
                "anchor_id": plan["from_checkpoint_id"] or plan["from_step_id"] or None,
                "canonical_anchor_type": plan.get("anchor_category") or None,
            },
            "selected_step_ids": list(
                ((plan.get("branch_preview") or {}).get("selected_step_ids") or [])
            ),
            "selection_mode": str(((plan.get("branch_preview") or {}).get("mode") or "")).strip() or None,
            "validation_mode": plan["validation_mode"],
        },
        "does_execute": False,
    }
    emit_artifact = bool(getattr(args, "emit_artifact", False))
    artifact_path = str(getattr(args, "artifact_path", "") or "").strip()
    if artifact_path:
        emit_artifact = True
    if emit_artifact:
        if write_replay_plan_artifact_fn is None:
            raise SystemExit("replay-plan artifact writer is unavailable")
        payload["artifact_path"] = write_replay_plan_artifact_fn(payload, artifact_path=artifact_path)
    if bool(args.apply):
        if bool(args.json):
            raise SystemExit("Choose only one of --apply or --json")
        if bool((plan.get("branch_preview") or {}).get("preview_only")):
            raise SystemExit("--select-step is preview-only in replay-plan for now; rerun without --apply")
        resume_envelope = payload.get("resume_envelope") if isinstance(payload.get("resume_envelope"), dict) else {}
        admission = resume_envelope.get("admission") if isinstance(resume_envelope.get("admission"), dict) else {}
        if not bool(admission.get("allowed")):
            reasons = ", ".join([str(item) for item in (admission.get("reasons") or []) if str(item).strip()]) or "resume admission failed"
            raise SystemExit(f"replay admission denied: {reasons}")
        if payload.get("artifact_path"):
            print(f"artifact={payload['artifact_path']}")
        return execute_replay_from_plan_fn(plan, timeout_sec=args.timeout_sec or None)
    if args.json:
        print(json.dumps(payload, separators=(",", ":")))
        return 0
    print(_term.section("plan"))
    print(
        f"  {_term.key('replay_of')}={payload['replay_of_run_id']} "
        f"{_term.key('run_name')}={payload['run_name']} "
        f"{_term.key('anchor_step')}={payload['from_step_id']} "
        f"{_term.key('anchor_checkpoint')}={payload['from_checkpoint_id']} "
        f"{_term.key('anchor_type')}={payload['anchor_type']} "
        f"{_term.key('validation_mode')}={payload['validation_mode']}"
    )
    checks = payload.get("validation_checks") if isinstance(payload.get("validation_checks"), dict) else {}
    if checks:
        notes = ",".join([str(item) for item in (checks.get("notes") or []) if str(item).strip()]) or "-"
        print(_term.section("validation"))
        print(f"  {_term.key('validation_status')}={_term.status_text(checks.get('status'))}")
        _print_wrapped_kv(_term.key("validation_notes"), notes, indent="  ")
    resume_envelope = payload.get("resume_envelope") if isinstance(payload.get("resume_envelope"), dict) else {}
    if resume_envelope:
        print(_term.section("resume"))
        admission = resume_envelope.get("admission") if isinstance(resume_envelope.get("admission"), dict) else {}
        stability = resume_envelope.get("stability") if isinstance(resume_envelope.get("stability"), dict) else {}
        rationale = ",".join([str(item) for item in (stability.get("rationale") or []) if str(item).strip()]) or "-"
        admission_label = _term.ok("True") if bool(admission.get("allowed")) else _term.err("False")
        print(
            f"  {_term.key('resume_admission')}={admission_label} "
            f"{_term.key('stability_rank')}={_term.rank_text(((resume_envelope.get('stability') or {}).get('rank')))}"
        )
        _print_wrapped_kv(_term.key("stability_rationale"), rationale, indent="  ")
        if not bool(admission.get("allowed")):
            reasons = ",".join([str(item) for item in (admission.get("reasons") or []) if str(item).strip()]) or "-"
            _print_wrapped_kv(_term.key("admission_reasons"), reasons, indent="  ")
    recommendation = payload.get("recommendation_used") if isinstance(payload.get("recommendation_used"), dict) else {}
    if recommendation:
        print(_term.section("recommended_anchor"))
        reason = ",".join([str(item) for item in (recommendation.get("recommendation_rationale") or []) if str(item).strip()]) or "-"
        print(
            f"  {_term.key('recommended_anchor')}={recommendation.get('anchor_id')} "
            f"{_term.key('recommended_rank')}={_term.rank_text(recommendation.get('stability_rank'))} "
            f"{_term.key('recommended_utility')}={recommendation.get('replay_utility_score')} "
            f"{_term.key('recommended_viability')}={recommendation.get('continuation_viability')}"
        )
        _print_wrapped_kv(_term.key("recommended_reason"), reason, indent="  ")
    rec_ctx = payload.get("recommendation_context") if isinstance(payload.get("recommendation_context"), dict) else {}
    skipped = list(rec_ctx.get("skipped") or [])
    if bool(getattr(args, "explain", False)) and rec_ctx:
        selected = rec_ctx.get("selected") if isinstance(rec_ctx.get("selected"), dict) else {}
        print(_term.section("explain"))
        print(
            f"  {_term.key('recommendation_explain_mode')}={rec_ctx.get('mode')} "
            f"{_term.key('evaluated')}={int(rec_ctx.get('evaluated_count') or 0)}"
        )
        if selected:
            selected_reason = ",".join([str(item) for item in (selected.get("recommendation_rationale") or []) if str(item).strip()]) or "-"
            selected_admission = ",".join([str(item) for item in (selected.get("admission_reasons") or []) if str(item).strip()]) or "-"
            print(
                f"  {_term.key('selected_anchor')}={selected.get('anchor_id')} "
                f"{_term.key('selected_score')}={selected.get('stability_score')} "
                f"{_term.key('selected_boundary')}={selected.get('boundary_strength')} "
                f"{_term.key('selected_idempotency')}={selected.get('idempotency_risk')} "
                f"{_term.key('selected_side_effect')}={selected.get('side_effect')} "
                f"{_term.key('selected_external_write')}={selected.get('external_write')} "
                f"{_term.key('selected_utility')}={selected.get('replay_utility_score')} "
                f"{_term.key('selected_viability')}={selected.get('continuation_viability')}"
            )
            _print_wrapped_kv(_term.key("selected_reason"), selected_reason, indent="  ")
            _print_wrapped_kv(_term.key("selected_admission_reasons"), selected_admission, indent="  ")
        explain_rows = []
        if selected:
            explain_rows.append({"role": "selected", **selected})
        for item in skipped[:5]:
            explain_rows.append({"role": "skipped", **item})
        if explain_rows:
            widths = {
                "role": 8,
                "anchor_id": max(10, max(len(str(item.get("anchor_id") or "-")) for item in explain_rows)),
                "type": max(11, max(len(str(item.get("anchor_type") or "-")) for item in explain_rows)),
                "rank": max(12, max(len(str(item.get("stability_rank") or "-")) for item in explain_rows)),
                "score": 5,
                "utility": 7,
                "viability": max(9, max(len(str(item.get("continuation_viability") or "-")) for item in explain_rows)),
                "admit": 5,
            }
            header = "  ".join(
                [
                    _term.pad(_term.key("ROLE"), widths["role"]),
                    _term.pad(_term.key("ANCHOR"), widths["anchor_id"]),
                    _term.pad(_term.key("TYPE"), widths["type"]),
                    _term.pad(_term.key("RANK"), widths["rank"]),
                    _term.pad(_term.key("SCORE"), widths["score"], align="right"),
                    _term.pad(_term.key("UTILITY"), widths["utility"], align="right"),
                    _term.pad(_term.key("VIABILITY"), widths["viability"]),
                    _term.pad(_term.key("ADMIT"), widths["admit"]),
                ]
            )
            print(f"  {header}")
            print(_term.muted("  " + "-" * max(20, _term.visible_len(header))))
            for item in explain_rows:
                score = item.get("stability_score")
                utility = item.get("replay_utility_score")
                score_text = "-" if score is None else f"{float(score):.2f}"
                utility_text = "-" if utility is None else f"{float(utility):.2f}"
                allowed = bool(item.get("admission_allowed"))
                if str(item.get("role")) == "selected":
                    role_text = _term.ok("selected")
                else:
                    role_text = _term.warn("skipped")
                print(
                    "  "
                    + "  ".join(
                        [
                            _term.pad(role_text, widths["role"]),
                            _term.pad(str(item.get("anchor_id") or "-"), widths["anchor_id"]),
                            _term.pad(str(item.get("anchor_type") or "-"), widths["type"]),
                            _term.pad(_term.rank_text(item.get("stability_rank") or "-"), widths["rank"]),
                            _term.pad(score_text, widths["score"], align="right"),
                            _term.pad(utility_text, widths["utility"], align="right"),
                            _term.pad(str(item.get("continuation_viability") or "-"), widths["viability"]),
                            _term.pad(_term.ok("yes") if allowed else _term.err("no"), widths["admit"]),
                        ]
                    )
                )
    if skipped:
        print(_term.section("skipped_summary"))
        print(f"  {_term.key('recommended_skipped')}:")
        for item in skipped[:5]:
            anchor_id = str(item.get("anchor_id") or "-")
            reasons = [str(val) for val in (item.get("admission_reasons") or []) if str(val).strip()]
            reason_text = ", ".join(reasons) if reasons else "-"
            print(f"    - {anchor_id}")
            for line in _term.wrap_text(
                reason_text,
                initial_indent="      reasons: ",
                subsequent_indent="               ",
            ):
                print(line)
    branch = payload.get("branch_preview") if isinstance(payload.get("branch_preview"), dict) else {}
    if branch:
        print(_term.section("branch_preview"))
        selected = ",".join([str(item) for item in (branch.get("selected_step_ids") or []) if str(item).strip()]) or "-"
        print(
            f"  {_term.key('branch_mode')}={branch.get('mode')} "
            f"{_term.key('selected_steps')}={selected} "
            f"{_term.key('preview_only')}={bool(branch.get('preview_only'))}"
        )
    print(_term.section("execution"))
    if payload.get("artifact_path"):
        print(f"  {_term.key('artifact')}={payload['artifact_path']}")
    _print_wrapped_kv(_term.key("command"), payload["replay_command"], indent="  ")
    _print_wrapped_kv(_term.key("cwd"), payload["replay_cwd"], indent="  ")
    print(_term.hint("next=hive trace replay <run_id> [--from-step-id <id> | --from-checkpoint-id <id>] --no-open"))
    return 0


def collect_run_anchors(run_id, *, event_limit=5000, read_run_record, read_trace_events_for_run, read_trace_events):
    rid = str(run_id or "").strip()
    if not rid:
        raise ValueError("run_id is required")
    limit = max(1, min(50000, int(event_limit or 5000)))
    record = read_run_record(rid) or {}
    preferred_log = str(record.get("trace_log_path") or "").strip()
    events = read_trace_events_for_run(rid, limit=limit, trace_log_path=preferred_log)
    if not events:
        events = read_trace_events(limit=limit, filters={"run_id": rid})
    step_ids = []
    step_seen = set()
    checkpoint_ids = []
    ckpt_seen = set()
    anchors = []
    anchor_seen = set()
    step_anchor_types = {}
    anchor_type_counts = {}
    first_failure_index = None
    run_context = _run_replay_context(events)
    side_effecting_run = bool(
        int((run_context or {}).get("external_write_event_count") or 0) > 0
        or int((run_context or {}).get("side_effect_event_count") or 0) > 0
    )
    checkpoint_anchor_available = bool(int((run_context or {}).get("checkpoint_anchor_count") or 0) > 0)
    for idx, event in enumerate(events):
        if first_failure_index is None and str(event.get("outcome") or "").strip().lower() == "failed":
            first_failure_index = idx
        anchor_type = canonical_anchor_type_for_event(event)
        step_id = str(event.get("step_id") or "").strip()
        if step_id and step_id not in step_seen:
            step_seen.add(step_id)
            step_ids.append(step_id)
        if step_id and anchor_type:
            types = step_anchor_types.setdefault(step_id, [])
            if anchor_type not in types:
                types.append(anchor_type)
        event_type = str(event.get("event_type") or "")
        if event_type == "observe_checkpoint":
            payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
            checkpoint_id = str(payload.get("checkpoint_id") or "").strip()
            if checkpoint_id and checkpoint_id not in ckpt_seen:
                ckpt_seen.add(checkpoint_id)
                checkpoint_ids.append(checkpoint_id)
        elif event_type == "checkpoint":
            payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
            checkpoint_id = str(payload.get("checkpoint_id") or "").strip()
            if not checkpoint_id:
                contract = payload.get("contract_v1") if isinstance(payload.get("contract_v1"), dict) else {}
                anchor = contract.get("anchor") if isinstance(contract.get("anchor"), dict) else {}
                checkpoint_id = str(anchor.get("anchor_id") or "").strip()
            if checkpoint_id and checkpoint_id not in ckpt_seen:
                ckpt_seen.add(checkpoint_id)
                checkpoint_ids.append(checkpoint_id)
        anchor_id = ""
        checkpoint_id = ""
        tool_call_id = str(event.get("tool_call_id") or "").strip()
        if event_type == "observe_checkpoint":
            payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
            checkpoint_id = str(payload.get("checkpoint_id") or "").strip()
            anchor_id = checkpoint_id
        elif event_type == "checkpoint":
            payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
            checkpoint_id = str(payload.get("checkpoint_id") or "").strip()
            if not checkpoint_id:
                contract = payload.get("contract_v1") if isinstance(payload.get("contract_v1"), dict) else {}
                anchor = contract.get("anchor") if isinstance(contract.get("anchor"), dict) else {}
                checkpoint_id = str(anchor.get("anchor_id") or "").strip()
            anchor_id = checkpoint_id
        elif step_id:
            anchor_id = step_id
        if anchor_type and anchor_id:
            key = (anchor_type, anchor_id)
            if key not in anchor_seen:
                anchor_seen.add(key)
                side_effect_signals = _extract_side_effect_signals(event)
                anchors.append(
                    {
                        "anchor_id": anchor_id,
                        "anchor_type": anchor_type,
                        "step_id": step_id or None,
                        "checkpoint_id": checkpoint_id or None,
                        "tool_call_id": tool_call_id or None,
                        "event_type": str(event.get("event_type") or ""),
                        "timestamp": str(event.get("timestamp") or ""),
                        "event_index": int(idx),
                        "side_effect_signals": side_effect_signals,
                    }
                )
            anchor_type_counts[anchor_type] = int(anchor_type_counts.get(anchor_type) or 0) + 1
    recommended = []
    for anchor in anchors:
        checkpoint_id = str(anchor.get("checkpoint_id") or "").strip()
        step_id = str(anchor.get("step_id") or "").strip()
        resume = _build_resume_envelope(
            base_run_id=rid,
            from_step_id=step_id if (not checkpoint_id) else "",
            from_checkpoint_id=checkpoint_id,
            anchor_category=str(anchor.get("anchor_type") or "").strip(),
            side_effect_signals=anchor.get("side_effect_signals") or {},
            validation_mode="tolerant",
            validation_checks={"status": "pass"},
        )
        stability = resume.get("stability") if isinstance(resume.get("stability"), dict) else {}
        admission = resume.get("admission") if isinstance(resume.get("admission"), dict) else {}
        event_index = int(anchor.get("event_index") or 0)
        failure_proximity = None
        failure_proximity_score = None
        if first_failure_index is not None:
            delta = int(first_failure_index) - event_index
            failure_proximity = abs(int(delta))
            if delta >= 0:
                # Prefer anchors closer to failure while remaining in committed past.
                failure_proximity_score = max(0.0, 1.0 - (float(delta) / float(max(1, first_failure_index + 1))))
            else:
                # Anchors after first failed event are less useful for replay diagnosis.
                failure_proximity_score = 0.05
        rationale = list(stability.get("rationale") or [])
        utility = _replay_utility_for_anchor(
            anchor=anchor,
            events=events,
            first_failure_index=first_failure_index,
            run_context=run_context,
        )
        if failure_proximity_score is not None:
            if float(failure_proximity_score) >= 0.7:
                rationale.append("anchor is close to first failure boundary")
            elif float(failure_proximity_score) <= 0.1:
                rationale.append("anchor occurs after first failure boundary")
        rationale.extend(list(utility.get("replay_utility_rationale") or []))
        recommended.append(
            {
                "anchor_id": str(anchor.get("anchor_id") or "").strip(),
                "anchor_type": str(anchor.get("anchor_type") or "").strip(),
                "timestamp": str(anchor.get("timestamp") or "").strip() or None,
                "from_step_id": step_id or None,
                "from_checkpoint_id": checkpoint_id or None,
                "stability_rank": str(stability.get("rank") or "").strip() or "weak_anchor",
                "stability_score": float(stability.get("score") or 0.0),
                "boundary_strength": float(stability.get("boundary_strength") or 0.0),
                "idempotency_risk": str(((resume.get("side_effects") or {}).get("idempotency_risk")) or "unknown"),
                "side_effect": bool(((resume.get("side_effects") or {}).get("side_effect"))),
                "external_write": bool(((resume.get("side_effects") or {}).get("external_write"))),
                "admission_allowed": bool(admission.get("allowed")),
                "admission_reasons": list(admission.get("reasons") or []),
                "failure_proximity": failure_proximity,
                "failure_proximity_score": failure_proximity_score,
                "replay_utility_score": float(utility.get("replay_utility_score") or 0.0),
                "continuation_viability": str(utility.get("continuation_viability") or "").strip() or "minimal",
                "replay_utility_rationale": list(utility.get("replay_utility_rationale") or []),
                "side_effecting_run": side_effecting_run,
                "checkpoint_anchor_available": checkpoint_anchor_available,
                "recommendation_rationale": rationale,
            }
        )
    recommended.sort(
        key=lambda item: (
            int(bool(item.get("admission_allowed"))),
            float(item.get("replay_utility_score") or 0.0),
            float(item.get("stability_score") or 0.0),
            float(item.get("failure_proximity_score") or 0.0),
            str(item.get("timestamp") or ""),
        ),
        reverse=True,
    )
    return {
        "run_id": rid,
        "step_ids": step_ids,
        "checkpoint_ids": checkpoint_ids,
        "step_count": len(step_ids),
        "checkpoint_count": len(checkpoint_ids),
        "anchors": anchors,
        "anchor_count": len(anchors),
        "step_anchor_types": step_anchor_types,
        "anchor_type_counts": anchor_type_counts,
        "recommended_replay_anchors": recommended[:10],
    }


def handle_trace_anchors(args, *, maybe_auto_reconcile, read_run_record, collect_run_anchors_fn):
    maybe_auto_reconcile()
    run_id = str(args.run_id or "").strip()
    if not run_id:
        raise SystemExit("run_id is required")
    record = read_run_record(run_id)
    if not record:
        raise SystemExit(f"run_id not found: {run_id}")
    payload = collect_run_anchors_fn(run_id, event_limit=args.event_limit)
    if args.json:
        print(json.dumps(payload, separators=(",", ":")))
        return 0
    print(_term.section("summary"))
    print(
        f"  {_term.key('run_id')}={payload['run_id']} "
        f"{_term.key('step_count')}={payload['step_count']} "
        f"{_term.key('checkpoint_count')}={payload['checkpoint_count']} "
        f"{_term.key('anchor_count')}={int(payload.get('anchor_count') or 0)}"
    )
    if payload["step_ids"]:
        print(_term.section("step_ids"))
        for item in payload["step_ids"]:
            print(f"  {item}")
    if payload["checkpoint_ids"]:
        print(_term.section("checkpoint_ids"))
        for item in payload["checkpoint_ids"]:
            print(f"  {item}")
    anchor_type_counts = payload.get("anchor_type_counts") if isinstance(payload.get("anchor_type_counts"), dict) else {}
    if anchor_type_counts:
        print(_term.section("anchor_type_counts"))
        for name, count in sorted(anchor_type_counts.items(), key=lambda item: str(item[0])):
            print(f"  {_term.pad(name, 18)} {int(count)}")
    recommended = list(payload.get("recommended_replay_anchors") or [])
    if recommended:
        print(_term.section("recommended_replay_anchors"))
        rows = recommended[:5]
        widths = {
            "mark": 1,
            "anchor_id": max(10, max(len(str(item.get("anchor_id") or "-")) for item in rows)),
            "type": max(11, max(len(str(item.get("anchor_type") or "-")) for item in rows)),
            "rank": max(12, max(len(str(item.get("stability_rank") or "-")) for item in rows)),
            "score": 5,
            "utility": 7,
            "viability": max(9, max(len(str(item.get("continuation_viability") or "-")) for item in rows)),
            "admission": 9,
            "risk": max(4, max(len(str(item.get("idempotency_risk") or "-")) for item in rows)),
            "ext": 3,
        }
        header = "  ".join(
            [
                _term.pad("", widths["mark"]),
                _term.pad(_term.key("ANCHOR"), widths["anchor_id"]),
                _term.pad(_term.key("TYPE"), widths["type"]),
                _term.pad(_term.key("RANK"), widths["rank"]),
                _term.pad(_term.key("SCORE"), widths["score"], align="right"),
                _term.pad(_term.key("UTILITY"), widths["utility"], align="right"),
                _term.pad(_term.key("VIABILITY"), widths["viability"]),
                _term.pad(_term.key("ADMISSION"), widths["admission"]),
                _term.pad(_term.key("RISK"), widths["risk"]),
                _term.pad(_term.key("EXT"), widths["ext"], align="right"),
            ]
        )
        print(header)
        print(_term.muted("  " + "-" * max(20, _term.visible_len(header) - 2)))
        for item in rows:
            admission_label = _term.ok("true") if bool(item.get("admission_allowed")) else _term.err("false")
            score = item.get("stability_score")
            score_text = "-" if score is None else f"{float(score):.2f}"
            utility = item.get("replay_utility_score")
            utility_text = "-" if utility is None else f"{float(utility):.2f}"
            marker = _term.ok("*") if item is rows[0] else " "
            print(
                "  ".join(
                    [
                        _term.pad(marker, widths["mark"]),
                        _term.pad(str(item.get("anchor_id") or "-"), widths["anchor_id"]),
                        _term.pad(str(item.get("anchor_type") or "-"), widths["type"]),
                        _term.pad(_term.rank_text(item.get("stability_rank") or "-"), widths["rank"]),
                        _term.pad(score_text, widths["score"], align="right"),
                        _term.pad(utility_text, widths["utility"], align="right"),
                        _term.pad(str(item.get("continuation_viability") or "-"), widths["viability"]),
                        _term.pad(admission_label, widths["admission"]),
                        _term.pad(str(item.get("idempotency_risk") or "-"), widths["risk"]),
                        _term.pad("Y" if bool(item.get("external_write")) else "N", widths["ext"], align="right"),
                    ]
                )
            )
    if (not payload["step_ids"]) and (not payload["checkpoint_ids"]):
        print(_term.warn("No anchors found on run."))
    return 0
