import os

target = r"C:\Users\intel\AppData\Local\OptimusRuntime\Labs\AR74\12_ar88_authority_operational_closure\candidate_workspace\artifacts\brain_host\brain_host_tls.py"

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

old_updater = """                                    def _canonical_task_bridge_updater(update_payload):
                                        if not isinstance(update_payload, dict):
                                            return False
                                        target_tid = str(update_payload.get("task_id") or update_payload.get("mission_id") or tid).strip()
                                        with OPERATIONAL_TASKS_LOCK:
                                            if target_tid in OPERATIONAL_TASKS:
                                                t_entry = OPERATIONAL_TASKS[target_tid]
                                                new_st = update_payload.get("task_status") or update_payload.get("status")
                                                if new_st:
                                                    t_entry["task_status"] = new_st
                                                    t_entry["status"] = new_st
                                                    t_entry["state"] = update_payload.get("state") or new_st
                                                    t_entry["canonical_terminal_status"] = new_st
                                                act_ev = update_payload.get("activity_event")
                                                if act_ev:
                                                    t_entry[act_ev.lower()] = True
                                                    activities = t_entry.setdefault("activity", [])
                                                    activities.append({
                                                        "timestamp": time.time(),
                                                        "event": act_ev,
                                                        "status": update_payload.get("status") or t_entry.get("status"),
                                                        "message": update_payload.get("message") or act_ev,
                                                        "incident_id": update_payload.get("incident_id"),
                                                        "shadow_run_id": update_payload.get("shadow_run_id"),
                                                    })
                                                return True
                                        return False"""

new_updater = """                                    def _canonical_task_bridge_updater(update_payload):
                                        if not isinstance(update_payload, dict):
                                            return False
                                        # AR-88 Requirement 4: Strictly isolate callback to the original tid
                                        target_tid = str(update_payload.get("task_id") or update_payload.get("mission_id") or "").strip()
                                        if target_tid and target_tid != tid:
                                            logger.warning(f"[BrainHost] Unauthorized attempt by callback to update task_id {target_tid} != bound {tid}; REJECTED.")
                                            return False
                                        with OPERATIONAL_TASKS_LOCK:
                                            if tid in OPERATIONAL_TASKS:
                                                t_entry = OPERATIONAL_TASKS[tid]
                                                # AR-88: Hook events MUST NOT overwrite mission terminal status (e.g. FAILED -> PATCH_NOT_GENERATED)
                                                # Task status remains the mission terminal status unless verified auto-promotion occurred.
                                                new_st = update_payload.get("task_status")
                                                if new_st and new_st in ("COMPLETED_AND_E2E_VERIFIED", "VERIFIED_SUCCESS"):
                                                    t_entry["task_status"] = new_st
                                                    t_entry["status"] = new_st
                                                    t_entry["state"] = "COMPLETED"
                                                    t_entry["canonical_terminal_status"] = new_st
                                                
                                                act_ev = update_payload.get("activity_event")
                                                if act_ev:
                                                    t_entry[act_ev.lower()] = True
                                                    activities = t_entry.setdefault("activity", [])
                                                    activities.append({
                                                        "timestamp": time.time(),
                                                        "event": act_ev,
                                                        "status": update_payload.get("status") or t_entry.get("status"),
                                                        "message": update_payload.get("message") or act_ev,
                                                        "incident_id": update_payload.get("incident_id"),
                                                        "shadow_run_id": update_payload.get("shadow_run_id"),
                                                    })
                                                return True
                                        return False"""

if old_updater in content:
    content = content.replace(old_updater, new_updater)
    with open(target, "w", encoding="utf-8") as f:
        f.write(content)
    print("SUCCESS: brain_host_tls.py updater strictly bound to tid and protects terminal status!")
else:
    print("ERROR: old_updater not found in brain_host_tls.py")

