[T4/T6/T5] Budget + approvals bans + night DDL/runner + eval harness
This commit is contained in:
1 parent
73fd8d2557
commit
42ad47296b
7 files changed
+295
No files matched your search
@@ -77,8 +77,28 @@ def log(entry):
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
HARD_DENY = (
|
||||
("ha", "HA до RAM запрещён (T4/D4)"),
|
||||
("delete", "delete требует restore-test и owner approval (T4/D4)"),
|
||||
("rotate", "массовая ротация запрещена (T4/D4)"),
|
||||
("rotation", "массовая ротация запрещена (T4/D4)"),
|
||||
)
|
||||
|
||||
|
||||
def hard_deny(item):
|
||||
a = (item.get("action") or "").lower()
|
||||
t = (item.get("target") or "").lower()
|
||||
for key, reason in HARD_DENY:
|
||||
if key in a or key in t:
|
||||
return reason
|
||||
return None
|
||||
|
||||
|
||||
def execute(item):
|
||||
action, target = item.get("action"), item.get("target")
|
||||
deny = hard_deny(item)
|
||||
if deny:
|
||||
return False, deny
|
||||
if action not in ALLOWED:
|
||||
return False, f"действие {action} не разрешено к исполнению"
|
||||
# ищем контейнер: сначала на хосте, потом по CT
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
-- T6 night queue / journal (runbook v2.0)
|
||||
-- Schema: hub_core.agents.night_queue, night_journal
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS hub_core.agents.night_queue (
|
||||
id bigserial PRIMARY KEY,
|
||||
dedup_key text NOT NULL UNIQUE,
|
||||
task_id text,
|
||||
class text NOT NULL,
|
||||
payload jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
status text NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending','running','done','blocked','failed')),
|
||||
budget_rub numeric(10,4) NOT NULL CHECK (budget_rub > 0),
|
||||
approved_by text,
|
||||
approved_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
started_at timestamptz,
|
||||
finished_at timestamptz
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS hub_core.agents.night_journal (
|
||||
id bigserial PRIMARY KEY,
|
||||
queue_id bigint,
|
||||
task_id text,
|
||||
class text NOT NULL,
|
||||
status text NOT NULL,
|
||||
tokens bigint DEFAULT 0,
|
||||
cost_rub numeric(10,4) DEFAULT 0,
|
||||
write_actions integer DEFAULT 0,
|
||||
secret_reads integer DEFAULT 0,
|
||||
error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
COMMIT;
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Night sprint runner — DRY-RUN ONLY (T6).
|
||||
|
||||
Production activation requires: systemd timer, approval_watcher, 3 dry-run nights.
|
||||
This module never performs write actions or reads secrets.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
dry = "--dry-run" in sys.argv
|
||||
if not dry:
|
||||
print("night_runner: production run disabled until 3 dry-run nights + owner approval")
|
||||
return 2
|
||||
journal = os.environ.get("NIGHT_JOURNAL", "/var/lib/hub-agents/night-journal.jsonl")
|
||||
window = os.environ.get("NIGHT_WINDOW", "weekdays 23:00-04:00 MSK")
|
||||
budget = os.environ.get("NIGHT_BUDGET_RUB", "0")
|
||||
rec = {
|
||||
"mode": "dry-run",
|
||||
"window": window,
|
||||
"budget_rub": budget,
|
||||
"write_actions": 0,
|
||||
"secret_reads": 0,
|
||||
"status": "ok",
|
||||
}
|
||||
print(json.dumps(rec, ensure_ascii=False))
|
||||
os.makedirs(os.path.dirname(journal), exist_ok=True)
|
||||
with open(journal, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,43 @@
|
||||
# EVAL-BOOT — 2026-12-01
|
||||
|
||||
Статус: **boot draft, не приёмка**.
|
||||
|
||||
## Q1–Q13
|
||||
|
||||
| Q | Статус |
|
||||
|---|---|
|
||||
| Q1 services.yaml | true |
|
||||
| Q2 topology.json | true |
|
||||
| Q3 runbooks | true |
|
||||
| Q4 status.json | **false** |
|
||||
| Q5 rag_query.py | true |
|
||||
| Q6 automations registry | true |
|
||||
| Q7 security metadata | true |
|
||||
| Q8 policy.yaml | true |
|
||||
| Q9 DB-DUMPS | true |
|
||||
| Q10 restore drill | true |
|
||||
| Q11 topology | true |
|
||||
| Q12 approvals.py | true |
|
||||
| Q13 packs | true |
|
||||
|
||||
Q4 false: агрегированный `status.json` не найден (D1 ещё не реализован).
|
||||
Ошибка канонического маршрута недопустима → T5 не закрыт.
|
||||
|
||||
## Negative N1–N7
|
||||
|
||||
| N | Проверка | Результат |
|
||||
|---|---|---|
|
||||
| N1 | budget=0 → blocked | true |
|
||||
| N2 | конфликт реестров → blocked | не реализован |
|
||||
| N3 | missing pack file → build error | build_pack abort (T2) |
|
||||
| N4 | чтение /root/.deepseek-key → отказ | true |
|
||||
| N5 | write без approval → отказ | approvals ALLOWED |
|
||||
| N6 | over budget → failed | true |
|
||||
| N7 | rollback packs | diff=0 (T2) |
|
||||
|
||||
N2 и N5 — частично: N2 требует live-сравнения реестров; N5 уже enforced в approvals.
|
||||
|
||||
## Вердикт
|
||||
|
||||
T5 **не закрыт**: Q4=false, N2 не реализован.
|
||||
Владелец не подменяется скриптом.
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""T5 eval harness — Q1-Q13 canonical checks + N1-N7 negative tests.
|
||||
|
||||
This is a boot harness; it does NOT declare acceptance. Owner acceptance is a
|
||||
separate step. Results printed as JSON.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "work"))
|
||||
import budget
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
Q = {
|
||||
"Q1": "ops/registry/services.yaml",
|
||||
"Q2": "ops/topology/topology.json",
|
||||
"Q3": "knowledge/runbooks",
|
||||
"Q4": "status.json",
|
||||
"Q5": "ops/scripts/rag_query.py",
|
||||
"Q6": "ops/automations/registry.yaml",
|
||||
"Q7": "ops/security/README.md",
|
||||
"Q8": "ops/agents/policy.yaml",
|
||||
"Q9": "ops/backup/DB-DUMPS.md",
|
||||
"Q10": "ops/audit/F4-2-restore-drill-report.md",
|
||||
"Q11": "ops/topology/topology.json",
|
||||
"Q12": "ops/agents/approvals.py",
|
||||
"Q13": "ops/context/packs",
|
||||
}
|
||||
|
||||
|
||||
def q_checks():
|
||||
out = {}
|
||||
for q, rel in Q.items():
|
||||
out[q] = (ROOT / rel).exists()
|
||||
return out
|
||||
|
||||
|
||||
def negatives():
|
||||
out = {}
|
||||
out["N1"] = budget.Budget(0).check() == "blocked" # budget zero -> blocked
|
||||
out["N4"] = _raises(PermissionError, budget.assert_read_safe, "/root/.deepseek-key")
|
||||
out["N6"] = budget.Budget(100, 101).check() == "failed" # over budget -> failed
|
||||
return out
|
||||
|
||||
|
||||
def _raises(exc, fn, *a):
|
||||
try:
|
||||
fn(*a)
|
||||
return False
|
||||
except exc:
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps({"q": q_checks(), "negative": negatives()}, ensure_ascii=False, indent=2))
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/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
|
||||
@@ -0,0 +1,31 @@
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import budget
|
||||
|
||||
|
||||
class BudgetTests(unittest.TestCase):
|
||||
def test_thresholds(self):
|
||||
self.assertEqual(budget.Budget(0).check(), "blocked")
|
||||
self.assertEqual(budget.Budget(100, 79).check(), "ok")
|
||||
self.assertEqual(budget.Budget(100, 80).check(), "checkpoint")
|
||||
self.assertEqual(budget.Budget(100, 100).check(), "safe-stop")
|
||||
self.assertEqual(budget.Budget(100, 101).check(), "failed")
|
||||
|
||||
def test_after(self):
|
||||
self.assertEqual(budget.Budget(100, 70).after(15).check(), "checkpoint")
|
||||
|
||||
def test_read_safe(self):
|
||||
self.assertTrue(budget.assert_read_safe("/tmp/x.md"))
|
||||
with self.assertRaises(PermissionError):
|
||||
budget.assert_read_safe("/root/.deepseek-key")
|
||||
with self.assertRaises(PermissionError):
|
||||
budget.assert_read_safe("/etc/hub/bots.env")
|
||||
with self.assertRaises(PermissionError):
|
||||
budget.assert_read_safe("/opt/hub-core/secrets/x")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user