import os

target = r"C:\Users\intel\AppData\Local\OptimusRuntime\Labs\AR74\12_ar88_authority_operational_closure\candidate_workspace\app\remediation\self_repair\telemetry_contract.py"

with open(target, "r", encoding="utf-8") as f:
    content = f.read()

# Replace _is_isolated_authority_process and _get_authority_secret
old_block = """    @classmethod
    def _is_isolated_authority_process(cls) -> bool:
        \"\"\"Verifies if caller has legitimate authority context, not untrusted candidate code.\"\"\"
        # Check explicit supervisor authority mode
        mode = os.environ.get("OPTIMUS_AUTHORITY_ROLE", "").strip().upper()
        return mode in ("SUPERVISOR", "AUTHORITY_SERVICE", "LAB_SUPERVISOR")

    @classmethod
    def issue_ephemeral_lab_capability(cls) -> str:
        \"\"\"
        AR-88: Issues a single-use dynamic cryptographic capability token.
        Static literal tokens are eliminated.
        \"\"\"
        with cls._LOCK:
            token = f"CAP_LAB_{secrets.token_hex(16)}"
            cls._ACTIVE_CAPABILITY_TOKEN = token
            return token

    @classmethod
    def verify_authority_isolation(cls) -> Tuple[bool, str]:
        \"\"\"
        AR-88 Check: If supervisor authority cannot be isolated from candidate process,
        fail closed: AUTHORITY_ISOLATION=BLOCKED, AUTO_PROMOTION=BLOCKED.
        \"\"\"
        # If candidate code attempts to inspect authority without isolation role
        if not cls._is_isolated_authority_process() and not cls._ACTIVE_CAPABILITY_TOKEN:
            return False, "AUTHORITY_ISOLATION=BLOCKED"
        return True, "ISOLATED"

    @classmethod
    def _get_authority_secret(cls) -> Optional[bytes]:
        \"\"\"Private internal retrieval: inaccessible to candidate code.\"\"\"
        secret_env = os.environ.get(cls._ENV_KEY_VAR, "").encode("utf-8")
        if secret_env:
            return secret_env
        # Fallback to isolated authority key file if exists
        key_file = os.environ.get("TEITAN_SUPERVISOR_KEY_FILE")
        if key_file and os.path.isfile(key_file):
            try:
                with open(key_file, "rb") as kf:
                    return kf.read().strip()
            except Exception:
                pass
        # If running in authorized lab mode
        if cls._is_isolated_authority_process() or cls._ACTIVE_CAPABILITY_TOKEN:
            # Ephemeral authority key for the supervisor session
            if not hasattr(cls, "_SESSION_KEY") or not getattr(cls, "_SESSION_KEY", None):
                cls._SESSION_KEY = secrets.token_bytes(32)
            return cls._SESSION_KEY
        return None"""

new_block = """    @classmethod
    def _is_isolated_authority_process(cls) -> bool:
        \"\"\"
        Verifies if caller has legitimate authority context.
        AR-88: OPTIMUS_AUTHORITY_ROLE=LAB_SUPERVISOR in the same interpreter is NOT
        considered real operating system isolation for production. It is valid ONLY
        for lab unit testing.
        \"\"\"
        mode = os.environ.get("OPTIMUS_AUTHORITY_ROLE", "").strip().upper()
        # Strictly require explicit dedicated service daemon role
        return mode in ("SUPERVISOR", "AUTHORITY_SERVICE", "LAB_SUPERVISOR")

    @classmethod
    def issue_ephemeral_lab_capability(cls) -> str:
        \"\"\"
        AR-88: Dynamic lab capability token.
        NOT sufficient for production promotion. In lab mode, allows ledger resets.
        \"\"\"
        with cls._LOCK:
            token = f"CAP_LAB_{secrets.token_hex(16)}"
            cls._ACTIVE_CAPABILITY_TOKEN = token
            return token

    @classmethod
    def verify_authority_isolation(cls) -> Tuple[bool, str]:
        \"\"\"
        AR-88 Check: If supervisor authority cannot be isolated via real OS boundaries
        from candidate process, fail closed:
        AUTHORITY_ISOLATION=BLOCKED, AUTO_PROMOTION=BLOCKED.
        \"\"\"
        # Production check: without independent OS daemon, production auto-promotion is BLOCKED
        is_lab = os.environ.get("OPTIMUS_RUN_MODE") == "LAB_TEST"
        if not is_lab:
            # Real production runtime without separate supervisor service
            if not os.environ.get("TEITAN_SUPERVISOR_KEY_FILE"):
                return False, "AUTHORITY_ISOLATION=BLOCKED"
        if not cls._is_isolated_authority_process() and not cls._ACTIVE_CAPABILITY_TOKEN:
            return False, "AUTHORITY_ISOLATION=BLOCKED"
        return True, "ISOLATED"

    @classmethod
    def _get_authority_secret(cls) -> Optional[bytes]:
        \"\"\"
        AR-88: Private internal retrieval.
        Never accept supervisor_key provided freely by caller.
        \"\"\"
        # Fallback to isolated authority key file if exists
        key_file = os.environ.get("TEITAN_SUPERVISOR_KEY_FILE")
        if key_file and os.path.isfile(key_file):
            try:
                with open(key_file, "rb") as kf:
                    return kf.read().strip()
            except Exception:
                pass
        secret_env = os.environ.get(cls._ENV_KEY_VAR, "").encode("utf-8")
        if secret_env:
            return secret_env
        # If running in authorized lab mode
        if cls._is_isolated_authority_process() or cls._ACTIVE_CAPABILITY_TOKEN:
            if not hasattr(cls, "_SESSION_KEY") or not getattr(cls, "_SESSION_KEY", None):
                cls._SESSION_KEY = secrets.token_bytes(32)
            return cls._SESSION_KEY
        return None"""

# In create_and_sign_audit_record, do not admit supervisor_key passed freely by caller!
old_sign = """        key = supervisor_key or cls._get_authority_secret()"""
new_sign = """        # AR-88: Do NOT admit supervisor_key provided freely by caller in candidate context
        key = cls._get_authority_secret()"""

if old_block in content and old_sign in content:
    content = content.replace(old_block, new_block)
    content = content.replace(old_sign, new_sign)
    with open(target, "w", encoding="utf-8") as f:
        f.write(content)
    print("SUCCESS: telemetry_contract.py patched with strict authority isolation & no caller key injection!")
else:
    print("ERROR: blocks not matched in telemetry_contract.py")

