# threat_engine_agent/reporter.py import json import os import logging import time from datetime import datetime class LocalStateReporter: """ Manages the health manifest on Triton. Acts as the 'Black Box' recorder for Argus to query. """ def __init__( self, state_file="/root/threat-engine-agent/threat-agent-state.json", node_name="unknown", ): self.state_file = state_file self.node_name = node_name self.started_at_epoch = time.time() # Ensure the directory is writable os.makedirs(os.path.dirname(os.path.abspath(self.state_file)), exist_ok=True) def _load_previous_state(self): try: with open(self.state_file, "r") as f: data = json.load(f) return data if isinstance(data, dict) else {} except Exception: return {} def _get_int(self, payload, key, default=0): try: return int(payload.get(key, default)) except Exception: return default def _normalize_hourly_buckets(self, previous): raw = previous.get("_rolling_24h_buckets", previous.get("rolling_24h_buckets", {})) if not isinstance(raw, dict): return {} normalized = {} for hour_key, metrics in raw.items(): try: hour = int(hour_key) except Exception: continue if not isinstance(metrics, dict): continue normalized[str(hour)] = { "drift_events": max(0, int(metrics.get("drift_events", 0))), "drift_heal_attempts": max(0, int(metrics.get("drift_heal_attempts", 0))), "heals": max(0, int(metrics.get("heals", 0))), "heal_failures": max(0, int(metrics.get("heal_failures", 0))), } return normalized def _roll_24h_counters( self, previous, now_epoch, drift_events_increment, heal_result, ): current_hour = int(now_epoch // 3600) min_hour = current_hour - 23 buckets = self._normalize_hourly_buckets(previous) # Prune data outside rolling 24-hour window. buckets = { hour_key: metrics for hour_key, metrics in buckets.items() if int(hour_key) >= min_hour } hour_key = str(current_hour) bucket = buckets.setdefault( hour_key, { "drift_events": 0, "drift_heal_attempts": 0, "heals": 0, "heal_failures": 0, }, ) bucket["drift_events"] += max(0, int(drift_events_increment)) if heal_result is not None: bucket["drift_heal_attempts"] += 1 bucket["heals"] += 1 if heal_result != "success": bucket["heal_failures"] += 1 drift_events_24h = sum(v["drift_events"] for v in buckets.values()) drift_heal_attempts_24h = sum(v["drift_heal_attempts"] for v in buckets.values()) heals_24h = sum(v["heals"] for v in buckets.values()) heal_failures_24h = sum(v["heal_failures"] for v in buckets.values()) return ( buckets, drift_events_24h, drift_heal_attempts_24h, heals_24h, heal_failures_24h, ) def update_status( self, is_synced, ban_count, last_error=None, missing_count=0, extra_count=0, metadata_drift_count=0, last_drift_fingerprint="", last_heal_result=None, last_heal_timestamp=None, checks_increment=0, drift_events_increment=0, heal_result=None, ): """ Writes the current health snapshot to a JSON file. """ previous = self._load_previous_state() effective_heal_result = ( last_heal_result if last_heal_result is not None else previous.get("last_heal_result") ) effective_last_heal_timestamp = ( last_heal_timestamp if last_heal_timestamp is not None else previous.get("last_heal_timestamp") ) if heal_result is not None: effective_heal_result = heal_result if effective_last_heal_timestamp is None: effective_last_heal_timestamp = datetime.now().isoformat() now_epoch = time.time() checks_total = max(0, self._get_int(previous, "checks_total", 0)) checks_total += max(0, int(checks_increment)) drift_events_total = max(0, self._get_int(previous, "drift_events_total", 0)) drift_events_total += max(0, int(drift_events_increment)) heals_total = max(0, self._get_int(previous, "heals_total", 0)) heal_failures_total = max(0, self._get_int(previous, "heal_failures_total", 0)) drift_heal_attempts_total = max( 0, self._get_int(previous, "drift_heal_attempts_total", 0) ) if heal_result is not None: heals_total += 1 drift_heal_attempts_total += 1 if heal_result != "success": heal_failures_total += 1 ( rolling_24h_buckets, drift_events_24h, drift_heal_attempts_24h, heals_24h, heal_failures_24h, ) = self._roll_24h_counters( previous=previous, now_epoch=now_epoch, drift_events_increment=drift_events_increment, heal_result=heal_result, ) uptime_seconds = max(0, int(now_epoch - self.started_at_epoch)) status_data = { "node_name": self.node_name, "last_check": datetime.now().isoformat(), "status": "HEALTHY" if is_synced else "DESYNC_DETECTED", "is_synced": is_synced, "kernel_ban_count": ban_count, "last_error": last_error, "missing_count": missing_count, "extra_count": extra_count, "metadata_drift_count": metadata_drift_count, "last_drift_fingerprint": last_drift_fingerprint, "last_heal_result": effective_heal_result, "last_heal_timestamp": effective_last_heal_timestamp, "uptime_seconds": uptime_seconds, "checks_total": checks_total, "drift_events_total": drift_events_total, "drift_heal_attempts_total": drift_heal_attempts_total, "drift_events_24h": drift_events_24h, "drift_heal_attempts_24h": drift_heal_attempts_24h, "heals_24h": heals_24h, "heal_failures_24h": heal_failures_24h, "heals_total": heals_total, "heal_failures_total": heal_failures_total, "_rolling_24h_buckets": rolling_24h_buckets, } try: # Atomic write: Write to a temp file then rename to avoid corruption temp_file = f"{self.state_file}.tmp" with open(temp_file, 'w') as f: json.dump(status_data, f, indent=4) os.replace(temp_file, self.state_file) except Exception as e: logging.error(f"Reporter: Failed to write state file: {e}") def get_history_file(self): base, _ = os.path.splitext(self.state_file) return f"{base}.history" def log_heal_event( self, kernel_count, missing_count, extra_count, metadata_drift_count, drift_fingerprint, reason, heal_result, post_drift_fingerprint, ): """ Records a specific healing event in a persistent history log. """ history_file = self.get_history_file() timestamp = datetime.now().isoformat() try: with open(history_file, 'a') as f: f.write( f"{timestamp} - HEAL: reason={reason} " f"kernel={kernel_count} missing={missing_count} " f"extra={extra_count} metadata={metadata_drift_count} " f"drift_fingerprint={drift_fingerprint} " f"heal_result={heal_result} " f"post_drift_fingerprint={post_drift_fingerprint}\n" ) except Exception as e: logging.error(f"Reporter: Failed to write to history log: {e}")