Budget guard: ratio 2.07 measured, limit 142; limit read from .env at each check

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Kral
2026-10-05 14:47:54 +02:00
parent c062df2ec5
commit ae37617a0d
2 changed files with 18 additions and 1 deletions

View File

@@ -34,9 +34,24 @@ def spent(since=None):
return round(sum(json.loads(l)["usd"] for l in open(LEDGER) if json.loads(l)["day"] >= since), 4)
def _env_budget():
"""BUDGET_LIMIT_USD and BUDGET_RESERVE_USD from .env (read at each check: a change applies at once)."""
vals = {"BUDGET_LIMIT_USD": os.environ.get("BUDGET_LIMIT_USD", "45"),
"BUDGET_RESERVE_USD": os.environ.get("BUDGET_RESERVE_USD", "0")}
try:
for line in open(os.path.join(ROOT, ".env")):
k, _, v = line.strip().partition("=")
if k in vals and v:
vals[k] = v
except OSError:
pass
return float(vals["BUDGET_LIMIT_USD"]), float(vals["BUDGET_RESERVE_USD"])
def check_budget():
# BUDGET_RESERVE_USD: ledger USD kept back (second teacher test later); the guard stops at limit - reserve
limit = float(os.environ.get("BUDGET_LIMIT_USD", "45")) - float(os.environ.get("BUDGET_RESERVE_USD", "0"))
limit_raw, reserve = _env_budget()
limit = limit_raw - reserve
s = spent()
if s >= limit:
raise BudgetExceeded(f"cycle spend {s} USD >= limit {limit} USD")