diff --git a/healing.py b/healing.py index 81ae7a0..418e23b 100644 --- a/healing.py +++ b/healing.py @@ -4,6 +4,47 @@ import time from datetime import datetime, timedelta +def _read_last_heal_line(history_file, chunk_size=4096, max_scan_bytes=262144): + """ + Returns the most recent line containing 'HEAL:' by scanning from file tail. + Falls back to a full forward scan if no marker is found in the tail window. + """ + file_size = os.path.getsize(history_file) + if file_size <= 0: + return None + + with open(history_file, "rb") as f: + pos = file_size + scanned = 0 + buffer = b"" + + while pos > 0 and scanned < max_scan_bytes: + to_read = min(chunk_size, pos, max_scan_bytes - scanned) + pos -= to_read + f.seek(pos) + chunk = f.read(to_read) + buffer = chunk + buffer + scanned += to_read + + lines = buffer.splitlines() + if pos > 0 and lines: + # Drop potential partial line at the chunk boundary. + lines = lines[1:] + + for raw_line in reversed(lines): + line = raw_line.decode("utf-8", errors="replace").strip() + if "HEAL:" in line: + return line + + # Fallback for unusual files where recent tail has no HEAL marker. + last_heal_line = None + with open(history_file) as f: + for line in f: + if "HEAL:" in line: + last_heal_line = line.strip() + return last_heal_line + + def should_heal(history_file, drift_fingerprint, min_interval=900): """ Prevents heal flapping by suppressing repeated no-op heals. @@ -12,13 +53,10 @@ def should_heal(history_file, drift_fingerprint, min_interval=900): if not os.path.exists(history_file): return True - with open(history_file) as f: - lines = [l.strip() for l in f.readlines() if "HEAL:" in l] - - if not lines: + last = _read_last_heal_line(history_file) + if not last: return True - last = lines[-1] ts_str, msg = last.split(" - ", 1) last_time = datetime.fromisoformat(ts_str) last_fingerprint = "" diff --git a/tests/test_agent.py b/tests/test_agent.py index 597c1dc..80741f5 100644 --- a/tests/test_agent.py +++ b/tests/test_agent.py @@ -52,6 +52,18 @@ class HealGateTests(unittest.TestCase): self.assertTrue(should_heal(path, "xyz999", min_interval=900)) + def test_should_heal_reads_recent_heal_from_tail(self): + now = datetime.now().isoformat() + with tempfile.NamedTemporaryFile(mode="w", delete=False) as tmp: + for idx in range(4000): + tmp.write(f"noise line {idx}\n") + tmp.write( + f"{now} - HEAL: drift_fingerprint=tail123 heal_result=success post_drift_fingerprint=\n" + ) + path = tmp.name + + self.assertFalse(should_heal(path, "tail123", min_interval=900)) + class PostHealVerificationTests(unittest.TestCase): @patch("healing.time.sleep", return_value=None)