"""Two small hardening changes, applied on top of the pinned commit (lab only).
1) Scanner suppression trusts an asset list, not words in the alert.
2) A model reply that says TP but fails the CTI schema stays TP (fail closed)."""
p = "alert_triage_copilot/agent.py"; s = open(p).read()

old_rule = """    if any(term in text for term in scanner_terms) and any(
        term in text for term in approved_terms
    ):"""
new_rule = """    registered = {ip.strip() for ip in os.getenv("REGISTERED_SCANNERS", "").split(",") if ip.strip()}
    if alert.source_ip in registered and any(term in text for term in scanner_terms):"""
assert s.count(old_rule) == 1; s = s.replace(old_rule, new_rule)

old_exc = """    except (json.JSONDecodeError, ValueError, KeyError) as e:
        # Fallback: return a low-confidence decision"""
new_exc = """    except (json.JSONDecodeError, ValueError, KeyError) as e:
        data = locals().get("data")  # set only if the JSON itself parsed
        if isinstance(data, dict) and data.get("classification") == "TP":
            steps = (data.get("remediation_steps") or [])[:3]
            steps += ["Escalate to the SOC lead for manual review."] * (3 - len(steps))
            return TriageDecision(
                alert_id=alert_id, classification=Classification.TRUE_POSITIVE,
                confidence=float(data.get("confidence", 0.5)),
                reasoning=f"Model said TP; reply failed schema ({type(e).__name__}), kept as TP. " + str(data.get("reasoning", ""))[:500],
                recommended_action="Manual review: model output needed repair.",
                mitre_tactics=data.get("mitre_tactics", []),
                mitre_technique_id=data.get("mitre_technique_id") or "T0000",
                severity_justification=data.get("severity_justification") or "Model classified as TP.",
                remediation_steps=steps,
            )
        # Fallback: return a low-confidence decision"""
assert s.count(old_exc) == 1; s = s.replace(old_exc, new_exc)
open(p, "w").write(s); print("hardening applied")
