Spaces:
Runtime error
Runtime error
Add MemoryLedger
Browse files
memory.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from typing import List, Dict, Optional
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MemoryLedger:
|
| 7 |
+
"""MEM-01/05: Memory ledger with JSON persistence tracing worker violation histories."""
|
| 8 |
+
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.entries: List[Dict[str, str]] = []
|
| 11 |
+
|
| 12 |
+
def add(self, worker_id: str, violation_type: str, evidence: str) -> None:
|
| 13 |
+
"""Adds a new memory, truncating evidence to 200 chars to avoid prompt bloat."""
|
| 14 |
+
clipped_evidence = evidence[:200]
|
| 15 |
+
self.entries.append(
|
| 16 |
+
{
|
| 17 |
+
"worker_id": worker_id,
|
| 18 |
+
"violation_type": violation_type,
|
| 19 |
+
"evidence": clipped_evidence,
|
| 20 |
+
}
|
| 21 |
+
)
|
| 22 |
+
# Maintain hard cap of 5000
|
| 23 |
+
if len(self.entries) > 5000:
|
| 24 |
+
self.entries.pop(0)
|
| 25 |
+
|
| 26 |
+
def retrieve(self, worker_id: str, violation_type: str) -> List[Dict[str, str]]:
|
| 27 |
+
"""MEM-02: Exact keyword match filtering returning max 3 items."""
|
| 28 |
+
matches = [
|
| 29 |
+
e
|
| 30 |
+
for e in self.entries
|
| 31 |
+
if e["worker_id"] == worker_id and e["violation_type"] == violation_type
|
| 32 |
+
]
|
| 33 |
+
# Return top_k=3 (the 3 most recent logically, so fetch from end or just standard)
|
| 34 |
+
return matches[-3:]
|
| 35 |
+
|
| 36 |
+
def clear(self) -> None:
|
| 37 |
+
"""MEM-04: Clear ledger for memory ablation experiments."""
|
| 38 |
+
self.entries.clear()
|
| 39 |
+
|
| 40 |
+
def save(self, path: Optional[str] = None) -> None:
|
| 41 |
+
"""MEM-01: Serializes the entire chain manually to JSON to prevent mid-rollout disk friction."""
|
| 42 |
+
if path is None:
|
| 43 |
+
path = os.path.join(os.path.dirname(__file__), "data", "memory_ledger.json")
|
| 44 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 45 |
+
with open(path, "w") as f:
|
| 46 |
+
json.dump(self.entries, f, indent=2)
|
| 47 |
+
|
| 48 |
+
def load(self, path: Optional[str] = None) -> None:
|
| 49 |
+
"""Reloads ledger state."""
|
| 50 |
+
load_path = (
|
| 51 |
+
path
|
| 52 |
+
if path is not None
|
| 53 |
+
else os.path.join(os.path.dirname(__file__), "data", "memory_ledger.json")
|
| 54 |
+
)
|
| 55 |
+
try:
|
| 56 |
+
with open(load_path, "r") as f:
|
| 57 |
+
self.entries = json.load(f)
|
| 58 |
+
except FileNotFoundError:
|
| 59 |
+
self.entries = []
|