One rule table replaces the two lists: each allow, ask and deny rule shows its hits from the extracted dry-run matcher, ask patterns the matcher never grants read never granted instead of unused, and the table scrolls in its own container below 600 px. Tests run once on unify/skills-20261114 after the merge (operator order 2026-11-14). 🎯 Fix: 85 % 💥 Break: 10 % 💸 Tokens: 100 % ⏱️ Velocity: 103 % 🛡️ Security: 100 % 🏆 Score: 74 🚦 Gate: ⛔ fix 85 % < 90, break 10 % > 5; velocity 103 % > 100: ask the operator before the commit Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
139 lines
7.1 KiB
Python
139 lines
7.1 KiB
Python
from __future__ import annotations
|
|
|
|
import time
|
|
|
|
from .denying import request_status, request_words, requester_of
|
|
from .errors import Conflict, Missing, ToolError
|
|
from .fields import WAIT_CAP, bounded, decode, expect, field, seconds
|
|
from .records import iso_epoch
|
|
from .rules import EVERY_AGENT, rule_fields, rule_matches, signed_fields, subject_of
|
|
from .signed import signing
|
|
|
|
# Trip-wire: MCP carries no caller identity, so an agent may name itself anew for each request; AGENT_CAP only spreads the queue, TOTAL_CAP is the bound.
|
|
AGENT_CAP = 3
|
|
TOTAL_CAP = 20
|
|
WHY_LIMIT = 1000
|
|
RECENT_DAYS = 7
|
|
RULE_FIELDS = ("kind", "tool", "pattern", "scope", "expires")
|
|
REQUEST_STATE = ("id", "status", "rule", "reason", "decided")
|
|
|
|
|
|
def request_state(record: dict, now: float) -> dict:
|
|
return {**{key: record[key] for key in REQUEST_STATE}, "status": request_status(record, now)}
|
|
|
|
|
|
def created_of(record: dict) -> float:
|
|
return record["created_ts"] if "created_ts" in record else iso_epoch(record["created"]) or 0.0
|
|
|
|
|
|
def matched(record: dict, subjects: list[dict], now: float) -> int:
|
|
"""Args:
|
|
record: id, kind, tool, pattern, scope and expires of a rule, with
|
|
agents when it applies to one agent or group only.
|
|
subjects: what recent_subjects() lists for the rule's kind.
|
|
now: the current time in epoch seconds.
|
|
|
|
Returns:
|
|
How many subjects the rule would have approved.
|
|
"""
|
|
kind_name = record["kind"]
|
|
payload = signing.rule_payload(record["id"], [kind_name], record["tool"], record["pattern"], record["scope"], int(record["expires"]))
|
|
if "agents" in record:
|
|
payload = signing.targeted(payload, record["agents"])
|
|
rule = {**{key: record[key] for key in RULE_FIELDS}, "enabled": True, "proof": {"payload": payload, "assertion": None}}
|
|
return sum(rule_matches(rule, kind_name, subject, now) for subject in subjects)
|
|
|
|
|
|
class Requesting:
|
|
def open_requests(self, now: float) -> list[dict]:
|
|
return [record for record in self.rule_requests.pending() if request_status(record, now) == "pending"]
|
|
|
|
def rule_request(self, arguments: dict) -> dict:
|
|
expect(arguments, (*RULE_FIELDS, "agent", "why"))
|
|
now = time.time()
|
|
fields = {name: value for name, value in rule_fields(arguments, EVERY_AGENT, now).items() if name in RULE_FIELDS}
|
|
if fields["kind"] == "decision" and fields["scope"] != "*":
|
|
raise ToolError("a decision rule takes scope *, as the rules form does")
|
|
name = field(arguments, "agent").strip()
|
|
why = bounded(arguments, "why", WHY_LIMIT).strip()
|
|
if not why:
|
|
raise ToolError("why must name the purpose of the requested rule")
|
|
|
|
def capped(records: list[dict]) -> None:
|
|
pending = [record for record in records if request_status(record, now) == "pending"]
|
|
if len(pending) >= TOTAL_CAP:
|
|
raise ToolError(f"{TOTAL_CAP} rule requests wait for the operator; ask again once some are answered")
|
|
if sum(1 for record in pending if record["agent"] == name) >= AGENT_CAP:
|
|
raise ToolError(f"{name} already has {AGENT_CAP} pending rule requests; wait for their answer with rule_request_wait")
|
|
|
|
record = self.rule_requests.add_checked({**fields, "agent": name, "why": why, "status": "pending", "rule": None, "reason": "", "channel": "", "proof": None, "decided": None, "created_ts": now}, capped)
|
|
self.log.add({"kind": "rule", "title": f"Rule request from {name}: {request_words(record)}", "text": why, "ref": {"request": record["id"]}})
|
|
return {"id": record["id"], "status": record["status"], "url": self.url()}
|
|
|
|
def rule_request_wait(self, arguments: dict) -> dict:
|
|
expect(arguments, ("id", "timeout_seconds"))
|
|
request_id = field(arguments, "id")
|
|
record = self.rule_requests.wait(request_id, seconds(arguments, "timeout_seconds", WAIT_CAP))
|
|
if record is None:
|
|
raise ToolError(f"no rule request {request_id}")
|
|
return request_state(record, time.time())
|
|
|
|
def recent_subjects(self, kind_name: str, now: float) -> list[dict]:
|
|
"""Returns:
|
|
The asks, reviews or decisions of the last RECENT_DAYS as a rule
|
|
of that kind is matched against them.
|
|
"""
|
|
ledger = {"ask": self.asks, "review": self.reviews, "decision": self.decisions}[kind_name]
|
|
since = now - RECENT_DAYS * 86400
|
|
return [subject_of(kind_name, entry, self.deciders(kind_name, entry)) for entry in ledger.listed() if created_of(entry) >= since]
|
|
|
|
def dry_run(self, record: dict, now: float) -> dict:
|
|
"""Returns:
|
|
How many of the asks, reviews or decisions of the last
|
|
RECENT_DAYS the requested rule would have approved, matched by
|
|
the same code that applies a stored rule.
|
|
"""
|
|
subjects = self.recent_subjects(record["kind"], now)
|
|
return {"matched": matched(record, subjects, now), "total": len(subjects), "days": RECENT_DAYS}
|
|
|
|
def request_items(self, base: dict, now: float, claims: list[dict]) -> list[dict]:
|
|
items = []
|
|
for record in self.open_requests(now):
|
|
rule = {key: record[key] for key in RULE_FIELDS}
|
|
fields = {"title": f"Rule: {request_words(record)}", "agent": record["agent"], "to": requester_of(claims, record["agent"])[0], "detail": record["why"], "rule": rule, "dry_run": self.dry_run(record, now), "deniable": True}
|
|
items.append({**base, "kind": "rule", "id": record["id"], "ts": record["created_ts"], **fields})
|
|
return items
|
|
|
|
def pending_request(self, request_id: str) -> dict:
|
|
record = self.rule_requests.get(request_id)
|
|
if record is None:
|
|
raise Missing(request_id)
|
|
state = request_state(record, time.time())
|
|
if state["status"] != "pending":
|
|
raise Conflict(state)
|
|
if self.batches.holds("rule", request_id):
|
|
raise Conflict({"id": request_id, "status": "held"})
|
|
return record
|
|
|
|
def sign_request(self, request_id: str) -> dict:
|
|
record = self.pending_request(request_id)
|
|
return {**self.rule_offer(rule_fields(record, EVERY_AGENT, time.time())), "sign": True}
|
|
|
|
def accept_request(self, request_id: str, body: bytes) -> dict:
|
|
payload = decode(body)
|
|
expect(payload, ("rule", "assertion"))
|
|
record = self.pending_request(request_id)
|
|
now = time.time()
|
|
rule = payload["rule"]
|
|
fields = signed_fields(rule, now)
|
|
if [fields[key] for key in RULE_FIELDS] != [record[key] for key in RULE_FIELDS]:
|
|
raise ToolError("the signed rule must be exactly the requested one")
|
|
proof = self.proven_rule(rule, payload["assertion"])
|
|
self.offered(rule, now)
|
|
decided, changed = self.rule_requests.decide(request_id, {"status": "accepted", "rule": rule["id"]})
|
|
if not changed:
|
|
raise Conflict(request_state(decided, now))
|
|
self.store_rule(rule, fields, proof, True, now)
|
|
self.log.add({"kind": "rule", "title": f"Rule request accepted: {request_words(record)}", "text": f"from {record['agent']}", "ref": {"request": request_id, "rule": rule["id"]}})
|
|
return request_state(decided, now)
|