Files
skills/orchestrator/kvb_orchestrator/gating.py
T
Kevin Veen-BirkenbachandClaude Opus 5.5 8726ed37a7 fix(kvb-org-organize): move the council root out of /tmp with a lossless migration
councilroot.py resolves one durable council root for every script and migrates the old /tmp root under the held locks: a preflight conflict moves nothing, each legacy file is renamed to a staging name before it is copied so a late writer is merged by the catch-up, id-less journals merge by line multiset, a differing whole file is kept beside its namesake, and a crash marker makes install copy the skills and report. One settings-file list, managed drop-ins included, serves councilroot.py and queue.py. Tests run once on unify/skills-20261114 after the merge (operator order 2026-11-14).

🎯 Fix: 88 %
💥 Break: 7 %
💸 Tokens: 100 %
⏱️ Velocity: 100 %
🛡️ Security: 100 %
🏆 Score: 82
🚦 Gate: ⛔ fix 88 % < 90, break 7 % > 5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:18:41 +00:00

115 lines
4.7 KiB
Python

from __future__ import annotations
import sqlite3
import time
from contextlib import closing
from pathlib import Path
from types import ModuleType
from .errors import ToolError
from .fields import decode, expect
from .jobs import GATE_JOB
from .signed import signing
from .skill_scripts import script_module
GATES_SCRIPT = "kvb-check-gate/scripts/gates.py"
GATES_DB = "gates.db"
GATE_TASK = "gates"
CHANGE_LIMIT = 100
CHANGE_KEYS = ("kind", "argv")
def gate_request(raw: object) -> bool:
return isinstance(raw, list) and bool(raw) and all(isinstance(entry, dict) and entry.get("kind") == GATE_JOB for entry in raw)
def shown_command(argv: list[str]) -> str:
return " ".join(["gates.py", *argv])
def gates_module(script: Path) -> ModuleType | None:
"""Returns:
The installed gates.py as a module, for its opened(), resolve() and
parents_of(), which only read the database and the parent journals;
loaded again after an install changed it, None when it is missing or
does not load.
"""
return script_module(script)
def branch_gates(gates: ModuleType, db: sqlite3.Connection, repo: str, branch: str) -> dict:
return {
"parents": [{"parent": parent, "source": source} for parent, source in gates.parents_of(db, repo, branch)],
"rules": dict(db.execute("SELECT action, level FROM rules WHERE repo = ? AND branch = ?", (repo, branch))),
"resolved": {action: dict(zip(("level", "source"), gates.resolve(db, repo, branch, action))) for action in gates.ACTIONS},
}
def read_gates(gates: ModuleType | None, db: Path, scan: dict) -> dict:
"""Args:
gates: the gates.py module, or None.
db: gates.db under the read-only mount of the durable council root.
scan: the tree; its repositories and branches are the ones shown.
Returns:
{repo: {branch: {parents, rules, resolved}}} as `gates.py show --json`
prints it, read through gates.opened() with the database read-only,
the kept parent journal from the same mount and without git; {}
without the script or a readable database.
"""
if gates is None or not db.is_file():
return {}
try:
with closing(gates.opened(db, False, db.parent)) as connection:
return {repo["path"]: {entry["name"]: branch_gates(gates, connection, repo["path"], entry["name"]) for entry in repo["branches"]} for repo in scan["repos"]}
except sqlite3.Error:
return {}
class Gating:
def gate_view(self, scan: dict) -> dict:
try:
return read_gates(gates_module(self.scripts.skills / GATES_SCRIPT), self.kept / GATES_DB, scan)
except Exception: # noqa: BLE001
return {}
def gate_changes(self, raw: object) -> list[dict]:
"""Args:
raw: the page's items, each {"kind": "gate", "argv"} with the
gates.py arguments of one rule set|drop or parents add|drop;
the staged changes go under one passkey assertion.
Returns:
The signed items, each with an argv signing.gate_argv() accepts.
"""
if not isinstance(raw, list) or not 1 <= len(raw) <= CHANGE_LIMIT:
raise ToolError(f"items must be a list of 1 to {CHANGE_LIMIT} gate changes")
signed: list[dict] = []
for entry in raw:
if not isinstance(entry, dict):
raise ToolError("every item must be an object with kind and argv")
expect(entry, CHANGE_KEYS)
try:
item = signing.gate_item(signing.gate_argv(entry["argv"]))
except signing.Refused as error:
raise ToolError(f"gate change: {error}") from None
if item in signed:
raise ToolError("items must be distinct")
signed.append(item)
return signed
def change_gates(self, body: bytes) -> dict:
payload = decode(body)
expect(payload, ("items", "proof"))
items = self.gate_changes(payload["items"])
proof = self.covered(payload["proof"], items, time.time())
for item in items:
self.operator_proven(proof, item)
ids = []
for item in items:
fields = {"kind": GATE_JOB, "task": GATE_TASK, "argv": item["argv"], "command": shown_command(item["argv"]), "directory": "", "sha256": "", "status": "queued", "proof": proof}
ids.append(self.jobs.add({**fields, "code": None, "output": "", "created_ts": time.time(), "started": None, "finished": None})["id"])
commands = [shown_command(item["argv"]) for item in items]
self.log.add({"kind": "run", "title": f"Gate change signed: {len(items)}", "text": "\n".join(commands), "ref": {"jobs": ids, "status": "queued"}})
return {"jobs": ids, "status": "queued"}