"""conftest for ANU v3.1 Codex Micro Refinement Loop regression suite (task-2662).

Pinning rationale: the repo-level ``tests/conftest.py`` injects
``WORKSPACE_ROOT`` (default ``/home/jay/workspace``) at the front of
``sys.path``.  Inside this worktree the ``utils`` package only contains the
newly added modules — they are absent in the canonical workspace tree, so
``from utils.anu_codex_micro_refinement_loop import …`` would otherwise
resolve to the canonical (stale) ``utils`` package.

We force ``WORKSPACE_ROOT`` to point at this worktree's root before any
``utils`` import happens, and pop any pre-cached ``utils`` module so the
canonical package is not bound to ``sys.modules['utils']``.
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

_WORKTREE_ROOT = Path(__file__).resolve().parents[2]

os.environ["WORKSPACE_ROOT"] = str(_WORKTREE_ROOT)

if str(_WORKTREE_ROOT) in sys.path:
    sys.path.remove(str(_WORKTREE_ROOT))
sys.path.insert(0, str(_WORKTREE_ROOT))

for _cached in ("utils", "utils.anu_codex_micro_refinement_loop", "utils.codex_cc_decision_loop"):
    if _cached in sys.modules:
        cached_mod = sys.modules[_cached]
        cached_file = getattr(cached_mod, "__file__", "") or ""
        if not cached_file.startswith(str(_WORKTREE_ROOT)):
            del sys.modules[_cached]
