72 lines
2.1 KiB
Python
72 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Budget enforcement for agent tasks (T4, runbook v2.0 §0.6).
|
|
|
|
Semantics:
|
|
- absent/zero budget -> blocked
|
|
- spent >= 80% -> checkpoint
|
|
- spent >= 100% -> safe-stop
|
|
- spent > 100% -> failed + rollback
|
|
|
|
Journal is a JSONL mirror; canonical PG table `hub_core.agents.accepted_log`
|
|
is filled by the same record path when DSN is available.
|
|
"""
|
|
import json
|
|
import os
|
|
import time
|
|
from pathlib import Path
|
|
|
|
JOURNAL = "/var/lib/hub-budget/journal.jsonl"
|
|
|
|
|
|
class Budget:
|
|
def __init__(self, limit_rub, spent_rub=0.0):
|
|
self.limit = float(limit_rub)
|
|
self.spent = float(spent_rub)
|
|
|
|
def check(self):
|
|
if self.limit <= 0:
|
|
return "blocked"
|
|
ratio = self.spent / self.limit
|
|
if ratio > 1.0:
|
|
return "failed"
|
|
if ratio >= 1.0:
|
|
return "safe-stop"
|
|
if ratio >= 0.8:
|
|
return "checkpoint"
|
|
return "ok"
|
|
|
|
def after(self, cost_rub):
|
|
return Budget(self.limit, self.spent + float(cost_rub or 0))
|
|
|
|
|
|
def record(task_id, tokens, cost_rub, accepted=False, manual_fixes=0):
|
|
Path(JOURNAL).parent.mkdir(parents=True, exist_ok=True)
|
|
entry = {
|
|
"task_id": task_id,
|
|
"tokens": int(tokens or 0),
|
|
"cost_rub": float(cost_rub or 0),
|
|
"accepted": bool(accepted),
|
|
"manual_fixes": int(manual_fixes or 0),
|
|
"ts": time.time(),
|
|
}
|
|
with open(JOURNAL, "a", encoding="utf-8") as f:
|
|
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
|
return entry
|
|
|
|
|
|
def assert_read_safe(path):
|
|
"""T4 read-protocol: forbid secrets, env, /root, symlink targets."""
|
|
p = os.path.abspath(path)
|
|
low = p.lower()
|
|
if low.startswith("/root"):
|
|
raise PermissionError(f"read blocked: /root/* ({p})")
|
|
base = os.path.basename(p)
|
|
if base.endswith(".env") or ".env." in base:
|
|
raise PermissionError(f"read blocked: env file ({p})")
|
|
if "/secrets" in low or base.startswith(".secret"):
|
|
raise PermissionError(f"read blocked: secrets ({p})")
|
|
if os.path.islink(p):
|
|
real = os.path.realpath(p)
|
|
raise PermissionError(f"read blocked: symlink {p} -> {real}")
|
|
return True
|