feat(orchestrator): triage, dialog-bound cards and silent expired drops on the hub
093: triage.py classifies every request as open, failed, expired or stale; POST /api/requests/dismiss hides many requests hub-wide under one passkey signature with the usual undo window, ledger dismissals.json. 094: an ask or hooked decision lives as long as its Claude dialog: the hook waits the hub Settings' hook wait (1-60 min, default 60), PostToolUse, Stop, UserPromptSubmit and SessionEnd hooks close the session's cards, and a card whose hook stopped waiting reads open in Claude. Closes are bound to a per-session closer token whose sha256 the hub stores, so a local process cannot close another session's cards or forge a choice. GET /api/match/closed lets the page drop closed cards within 5 s. 096: the release signs dismissals of dropped expired cards together with the inbox entries; no radio reaches the agent. 088: the prune list is no longer capped at 50 tasks. 091: nvidia-smi's error line reaches the GPU row as its cause; limits take a batch of staged values under one proof. MEDUSA: 57 findings accepted as false positives after an independent skeptic review and the operator's word (MM-SCAN-058 regex PLA matching replay/place/replace, CODEGEN-SCAN-001 on Map.delete and labels, fixed nvidia-smi argv, localhost-only hook URLs, passkey in tooltips). Gate missed on the operator's word: break 8 %, the E2E runs after the page bundle; operator must run make orchestrator-hook and restart every Claude Code session after the install. 🎯 Fix: 92 % 💥 Break: 8 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: 100 % 🏆 Score: 85 🚦 Gate: ⛔ break 8 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
909ea85605
commit
8ee52644c8
25 files changed
+1531
-130
No files matched your search
@@ -43,6 +43,7 @@ from .signed import (
|
||||
verifier,
|
||||
)
|
||||
from .tasking import task_request
|
||||
from .triage import DISMISS_VERB, dismiss_entry, dismiss_request
|
||||
|
||||
BATCH_LIMIT = 100
|
||||
INBOX_KINDS = ("review", "ask", "decision", "operator", "rule")
|
||||
@@ -176,11 +177,16 @@ class Approving:
|
||||
|
||||
def apply(self, batch: dict) -> None:
|
||||
"""Args:
|
||||
batch: settled item by item; operator rows after every other
|
||||
item, so a commit row's job never starts before the reviews
|
||||
its verify steps check are decided.
|
||||
batch: its dismissals of a Match release first, through
|
||||
apply_dismissals(), then the rest settled item by item;
|
||||
operator rows after every other item, so a commit row's job
|
||||
never starts before the reviews its verify steps check are
|
||||
decided.
|
||||
"""
|
||||
for item in sorted(batch["items"], key=lambda item: item["kind"] == "operator"):
|
||||
dismissed = [item for item in batch["items"] if item["verb"] == DISMISS_VERB]
|
||||
if dismissed:
|
||||
self.apply_dismissals({**batch, "items": dismissed})
|
||||
for item in sorted((item for item in batch["items"] if item["verb"] != DISMISS_VERB), key=lambda item: item["kind"] == "operator"):
|
||||
try:
|
||||
outcome = self.settle_item(item, batch["proof"] if item["signed"] is not None else None)
|
||||
except (OSError, ToolError) as error:
|
||||
@@ -318,6 +324,29 @@ class Approving:
|
||||
raise Conflict({"status": "held"})
|
||||
return items
|
||||
|
||||
def released(self, raw: object) -> list[dict]:
|
||||
"""Args:
|
||||
raw: the page's entries: inbox entries (checked()) and the dismiss
|
||||
entries (dismissable()) of a Match release, which one
|
||||
signature covers together.
|
||||
|
||||
Returns:
|
||||
The batch items of the inbox entries, then of the dismissals.
|
||||
|
||||
Raises:
|
||||
ToolError as checked() for no inbox entry and no dismissal, and
|
||||
for two items of one request.
|
||||
"""
|
||||
dropped = [entry for entry in raw if dismiss_entry(entry)] if isinstance(raw, list) else []
|
||||
if not dropped:
|
||||
return self.checked(raw)
|
||||
kept = [entry for entry in raw if not dismiss_entry(entry)]
|
||||
items = (self.checked(kept) if kept else []) + self.dismissable(dropped)
|
||||
keys = [(item["kind"], item["id"]) for item in items]
|
||||
if len(set(keys)) != len(keys):
|
||||
raise ToolError("items must be distinct")
|
||||
return items
|
||||
|
||||
def sign(self, body: bytes) -> dict:
|
||||
payload = decode(body)
|
||||
expect(payload, ("items",))
|
||||
@@ -338,18 +367,28 @@ class Approving:
|
||||
signed = self.prune_changes(raw)
|
||||
elif settings_request(raw):
|
||||
signed = self.settings_changes(raw)
|
||||
elif dismiss_request(raw):
|
||||
signed = [item["signed"] for item in self.dismissable(raw)]
|
||||
elif enable_request(raw):
|
||||
signed = self.enable_items(raw)
|
||||
return {**self.challenge_for(signed), "enables": signed[0]["rule"]}
|
||||
else:
|
||||
signed = signed_of(self.checked(raw))
|
||||
signed = signed_of(self.released(raw))
|
||||
return self.challenge_for(signed)
|
||||
|
||||
def approve(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"items", "proof"}: the entries released() takes and the
|
||||
one passkey assertion over their signed items; the hub
|
||||
verifies a dismissal's signature itself, since it acts on it.
|
||||
"""
|
||||
payload = decode(body)
|
||||
expect(payload, ("items", "proof"))
|
||||
items = self.checked(payload["items"])
|
||||
items = self.released(payload["items"])
|
||||
proof = self.covered(payload["proof"], signed_of(items), time.time())
|
||||
for item in items:
|
||||
if item["verb"] == DISMISS_VERB:
|
||||
self.operator_proven(proof, item["signed"])
|
||||
return self.batches.add(items, "operator", proof, self.apply)
|
||||
|
||||
def undo(self, batch_id: str) -> dict:
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
|
||||
from .choosing import EVERYONE, PICKED, answer_text, decision_status
|
||||
@@ -12,6 +14,7 @@ from .fields import (
|
||||
MCP_WAIT_CAP,
|
||||
OPTION_LIMIT,
|
||||
PATH_LIMIT,
|
||||
TEXT_LIMIT,
|
||||
WAIT_CAP,
|
||||
bounded,
|
||||
decode,
|
||||
@@ -30,6 +33,97 @@ ASK_TEXTS = {"command": COMMAND_LIMIT, "cwd": PATH_LIMIT, "session": 200, "agent
|
||||
ANSWERS = {"allow": "allowed", "deny": "denied"}
|
||||
RECOMMENDED = "(Recommended)"
|
||||
TERMINAL = "terminal"
|
||||
ENDED = "ended"
|
||||
IN_CLAUDE = "claude"
|
||||
IN_CLAUDE_WORDS = "Open in Claude: answer it there; its hook stopped waiting for the hub"
|
||||
RAN = "PostToolUse"
|
||||
TURN_ENDS = ("Stop", "UserPromptSubmit")
|
||||
SESSION_END = "SessionEnd"
|
||||
CLOSING = (RAN, *TURN_ENDS, SESSION_END)
|
||||
ANSWERS_LIMIT = 8
|
||||
ANSWER_LIMIT = 4000
|
||||
|
||||
|
||||
def dialog_state(record: dict, now: float) -> str:
|
||||
"""Args:
|
||||
record: an ask or a decision.
|
||||
now: the current time in epoch seconds.
|
||||
|
||||
Returns:
|
||||
Where its card stands over the lifecycle of its Claude dialog:
|
||||
pending while the hook waits for the hub; IN_CLAUDE once the hook
|
||||
stopped waiting on a bound record (the hook registration closes it
|
||||
by CLOSING), expired on an unbound one; allowed, denied or decided
|
||||
once the hub answered; TERMINAL once Claude answered it, ENDED once
|
||||
its session ended.
|
||||
"""
|
||||
if record["status"] != "pending" or record.get("expires", now + 1) > now:
|
||||
return record["status"]
|
||||
return IN_CLAUDE if record.get("bound") else "expired"
|
||||
|
||||
|
||||
def ran_answers(raw: object) -> dict[str, str]:
|
||||
"""Args:
|
||||
raw: {question: answer} of an AskUserQuestion call that ran, at most
|
||||
ANSWERS_LIMIT texts of at most ANSWER_LIMIT characters each.
|
||||
|
||||
Returns:
|
||||
The answers by stripped question, each answer stripped.
|
||||
"""
|
||||
if not isinstance(raw, dict) or len(raw) > ANSWERS_LIMIT or not all(isinstance(question, str) and isinstance(answer, str) and len(question) <= TEXT_LIMIT and len(answer) <= ANSWER_LIMIT for question, answer in raw.items()):
|
||||
raise ToolError(f"answers must map at most {ANSWERS_LIMIT} questions to answers of at most {ANSWER_LIMIT} characters")
|
||||
visible([{"question": question, "answer": answer} for question, answer in raw.items()])
|
||||
return {question.strip(): answer.strip() for question, answer in raw.items()}
|
||||
|
||||
|
||||
def bound_of(payload: dict) -> bool:
|
||||
"""Returns:
|
||||
The optional bound flag the hook sends when its registration also
|
||||
closes the session's cards (CLOSING), popped from payload; False when
|
||||
absent.
|
||||
"""
|
||||
bound = payload.pop("bound", False)
|
||||
if not isinstance(bound, bool):
|
||||
raise ToolError("bound must be true or false")
|
||||
return bound
|
||||
|
||||
|
||||
def closer_of(payload: dict) -> str:
|
||||
"""Args:
|
||||
payload: a registration or a close report, holding the optional
|
||||
closer, the hook's per-session token (permission_hook.closer_token()).
|
||||
|
||||
Returns:
|
||||
The sha256 hex digest of the closer, popped from payload, the only
|
||||
form the hub keeps; empty when absent, as an older hook sends it.
|
||||
"""
|
||||
if "closer" not in payload:
|
||||
return ""
|
||||
token = field(payload, "closer")
|
||||
payload.pop("closer")
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def closes(record: dict, presented: str) -> bool:
|
||||
"""Args:
|
||||
record: an ask or a decision.
|
||||
presented: closer_of() a close report, empty without a closer.
|
||||
|
||||
Returns:
|
||||
True only when the record stores a closer digest (closer_of() of its
|
||||
registration) and presented equals it, compared in constant time.
|
||||
"""
|
||||
stored = record.get("closer_digest", "")
|
||||
return bool(stored) and bool(presented) and hmac.compare_digest(stored, presented)
|
||||
|
||||
|
||||
def ran_closes(record: dict, presented: str) -> bool:
|
||||
"""Returns:
|
||||
Whether a RAN report with presented may close the record: by
|
||||
closes(), or for a record of an older hook, which stores no closer
|
||||
digest, by its call_key alone.
|
||||
"""
|
||||
return closes(record, presented) or not record.get("closer_digest")
|
||||
|
||||
|
||||
def ask_state(ask: dict, now: float) -> dict:
|
||||
@@ -95,20 +189,24 @@ class Asking:
|
||||
def ask(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: the hook's ask: tool, ASK_TEXTS, timeout, optionally its diff
|
||||
and sealed patches, and the call's signing.call_key(), which
|
||||
an older hook leaves out; ask_ran() closes the ask by it.
|
||||
and sealed patches, the call's signing.call_key(), which
|
||||
an older hook leaves out (ask_ran() closes the ask by it),
|
||||
bound (bound_of()) and closer (closer_of()), whose digest
|
||||
alone the ask keeps as closer_digest.
|
||||
"""
|
||||
payload = decode(body)
|
||||
diff = valid_diff(payload.pop("diff")) if "diff" in payload else None
|
||||
sealed = valid_sealed(payload.pop("sealed"), diff) if "sealed" in payload else {}
|
||||
key = field(payload, "call_key") if "call_key" in payload else ""
|
||||
payload.pop("call_key", None)
|
||||
bound = bound_of(payload)
|
||||
closer = closer_of(payload)
|
||||
expect(payload, ("tool", *ASK_TEXTS, "timeout"))
|
||||
values = {name: bounded(payload, name, limit) for name, limit in ASK_TEXTS.items()}
|
||||
visible(values)
|
||||
lifetime = seconds(payload, "timeout", ASK_LIFETIME)
|
||||
created = time.time()
|
||||
fields = {**values, "tool": field(payload, "tool").strip(), "call_key": key, "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)}
|
||||
fields = {**values, "tool": field(payload, "tool").strip(), "call_key": key, "bound": bound, "closer_digest": closer, "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)}
|
||||
with self.asks.changed:
|
||||
ask_id = self.asks.fresh()
|
||||
if diff is not None:
|
||||
@@ -121,28 +219,92 @@ class Asking:
|
||||
|
||||
def ask_ran(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"call_key", "session"}: the PostToolUse report of a tool
|
||||
call that ran, keyed by signing.call_key().
|
||||
body: what a hook of the CLOSING events reports, each with the
|
||||
session_id of its stdin: {"event": RAN, "call_key", "session"}
|
||||
and for an AskUserQuestion call its "answers" (ran_answers())
|
||||
once a tool call ran, keyed by signing.call_key(); an older
|
||||
hook sends only call_key and session, which counts as RAN.
|
||||
{"event", "session"} for a TURN_ENDS event, which ends a turn
|
||||
with every dialog of the main agent closed (a denial or an
|
||||
interrupt in Claude), and for SESSION_END. Each optionally
|
||||
carries closer, the session's token (closer_of()).
|
||||
|
||||
Returns:
|
||||
{"closed"}: the id of the oldest ask of that session and key still
|
||||
pending and created before the report, now TERMINAL, as answered
|
||||
in the terminal; null when none is. An ask of another session or
|
||||
one already decided stays as it is. Nothing is approved or
|
||||
{"asks", "decisions"}: the ids of the records now closed, each
|
||||
created before the report and of exactly that session. RAN closes
|
||||
the oldest pending ask of that key and, per question, the oldest
|
||||
pending decision of that key that ran_closes() admits, the
|
||||
decision with its answer as choice only when closes() holds, all
|
||||
TERMINAL (answered in Claude); a TURN_ENDS event closes every
|
||||
pending record of the main agent that closes() admits TERMINAL,
|
||||
never one of a subagent, whose dialog may still be open while the
|
||||
main agent waits; SESSION_END closes every pending record that
|
||||
closes() admits ENDED. A record of another session, one already
|
||||
decided or, for TURN_ENDS and SESSION_END, one without the
|
||||
matching closer digest stays as it is. Nothing is approved or
|
||||
denied, and no signature is relayed.
|
||||
"""
|
||||
payload = decode(body)
|
||||
expect(payload, ("call_key", "session"))
|
||||
key = field(payload, "call_key")
|
||||
event = payload.get("event", RAN)
|
||||
if not isinstance(event, str) or event not in CLOSING:
|
||||
raise ToolError(f"event must be one of {', '.join(CLOSING)}")
|
||||
keyed = event == RAN
|
||||
optional = ("event", "answers", "closer") if keyed else ("event", "closer")
|
||||
expect(payload, (*(("call_key",) if keyed else ()), "session", *(name for name in optional if name in payload)))
|
||||
session = bounded(payload, "session", ASK_TEXTS["session"])
|
||||
if not session:
|
||||
raise ToolError("session must not be empty")
|
||||
presented = closer_of(payload)
|
||||
now = time.time()
|
||||
found = sorted((ask for ask in self.asks.pending() if ask.get("call_key") == key and ask["session"] == session and ask["created_ts"] <= now), key=lambda ask: (ask["created_ts"], ask["id"]))
|
||||
if keyed:
|
||||
key = field(payload, "call_key")
|
||||
answers = ran_answers(payload["answers"]) if "answers" in payload else {}
|
||||
return {"asks": self.close_ran(session, key, presented, now), "decisions": self.close_answered(session, key, answers, presented, now)}
|
||||
status = ENDED if event == SESSION_END else TERMINAL
|
||||
main = event in TURN_ENDS
|
||||
asks = [ask["id"] for ask in self.asks.pending() if ask["session"] == session and ask["created_ts"] <= now and not (main and ask["agent"]) and closes(ask, presented) and self.asks.decide(ask["id"], {"status": status})[1]]
|
||||
decisions = [decision["id"] for decision in self.decisions.pending() if decision.get("hooked") and decision["session"] == session and decision["created_ts"] <= now and not (main and decision.get("subagent")) and closes(decision, presented) and self.decisions.decide(decision["id"], {"status": status})[1]]
|
||||
for ask_id in asks:
|
||||
sealed_file(self.reviews.pages, "ask", ask_id).unlink(missing_ok=True)
|
||||
return {"asks": asks, "decisions": decisions}
|
||||
|
||||
def close_ran(self, session: str, key: str, presented: str, now: float) -> list[str]:
|
||||
"""Args:
|
||||
presented: closer_of() the report, empty without a closer.
|
||||
|
||||
Returns:
|
||||
The id of the oldest pending ask of session and key created by
|
||||
now that ran_closes() admits, closed TERMINAL; empty when none is.
|
||||
"""
|
||||
found = sorted((ask for ask in self.asks.pending() if ask.get("call_key") == key and ask["session"] == session and ask["created_ts"] <= now and ran_closes(ask, presented)), key=lambda ask: (ask["created_ts"], ask["id"]))
|
||||
closed = next((ask["id"] for ask in found if self.asks.decide(ask["id"], {"status": TERMINAL})[1]), None)
|
||||
if closed is not None:
|
||||
sealed_file(self.reviews.pages, "ask", closed).unlink(missing_ok=True)
|
||||
return {"closed": closed}
|
||||
if closed is None:
|
||||
return []
|
||||
sealed_file(self.reviews.pages, "ask", closed).unlink(missing_ok=True)
|
||||
return [closed]
|
||||
|
||||
def close_answered(self, session: str, key: str, answers: dict[str, str], presented: str, now: float) -> list[str]:
|
||||
"""Args:
|
||||
answers: ran_answers() of the call, empty for a call of another
|
||||
tool.
|
||||
presented: closer_of() the report, empty without a closer.
|
||||
|
||||
Returns:
|
||||
The ids of the decisions closed TERMINAL: per question, the
|
||||
oldest pending decision the hook asked for session and key by
|
||||
now that ran_closes() admits, its choice the answer to its
|
||||
question when closes() holds, else None, as when answers lacks
|
||||
it.
|
||||
"""
|
||||
found = sorted((decision for decision in self.decisions.pending() if decision.get("hooked") and decision.get("call_key") == key and decision["session"] == session and decision["created_ts"] <= now and ran_closes(decision, presented)), key=lambda decision: (decision["created_ts"], decision["id"]))
|
||||
closed: list[str] = []
|
||||
asked: set[str] = set()
|
||||
for decision in found:
|
||||
choice = answers.get(decision["question"]) if closes(decision, presented) else None
|
||||
if decision["question"] not in asked and self.decisions.decide(decision["id"], {"status": TERMINAL, "choice": choice})[1]:
|
||||
asked.add(decision["question"])
|
||||
closed.append(decision["id"])
|
||||
return closed
|
||||
|
||||
def ask_wait(self, ask_id: str, query: dict[str, list[str]]) -> dict:
|
||||
wait = instant(query, "wait")
|
||||
@@ -182,9 +344,21 @@ class Asking:
|
||||
multi one takes several options as a pick (choosing.picks),
|
||||
its recommendation is the options labelled RECOMMENDED
|
||||
(the first of them for a single one), and a signed pick is
|
||||
kept for the hook instead of being posted.
|
||||
kept for the hook instead of being posted. Optionally the
|
||||
call's signing.call_key() and subagent, the agent_type of a
|
||||
subagent's call, by which ask_ran() closes it, bound
|
||||
(bound_of()) and closer (closer_of()), whose digest alone
|
||||
the decision keeps as closer_digest; an older hook leaves
|
||||
them out.
|
||||
"""
|
||||
payload = decode(body)
|
||||
key = field(payload, "call_key") if "call_key" in payload else ""
|
||||
subagent = bounded(payload, "subagent", ASK_TEXTS["agent"]) if "subagent" in payload else ""
|
||||
visible({"subagent": subagent})
|
||||
bound = bound_of(payload)
|
||||
closer = closer_of(payload)
|
||||
for name in ("call_key", "subagent"):
|
||||
payload.pop(name, None)
|
||||
expect(payload, ("question", "options", "session", "timeout", "multi"))
|
||||
question, parsed = choice_of(payload)
|
||||
multi = payload["multi"]
|
||||
@@ -200,7 +374,7 @@ class Asking:
|
||||
raise ToolError(f"the asking session's name holds {EVERYONE}")
|
||||
marked = [option["label"] for option in parsed if option["label"].endswith(RECOMMENDED)]
|
||||
recommended = PICKED.join(marked) if multi else next(iter(marked), "")
|
||||
fields = {"question": question, "options": parsed, "agent": asker, "recommended": recommended, "session": session, "hooked": True, "multi": multi}
|
||||
fields = {"question": question, "options": parsed, "agent": asker, "recommended": recommended, "session": session, "hooked": True, "multi": multi, "call_key": key, "subagent": subagent, "bound": bound, "closer_digest": closer}
|
||||
record = self.decisions.add({**fields, "status": "pending", "choice": None, "decided": None, "proof": None, "created_ts": created, "expires": created + seconds(payload, "timeout", ASK_LIFETIME)})
|
||||
return {"id": record["id"], "status": record["status"]}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ FIELDS = {
|
||||
"tool": (re.compile(LINE.format(200)), "one line of 1 to 200 characters"),
|
||||
"id": (re.compile(r"[0-9a-f]{16}"), "an id the Agent Orchestrator returned"),
|
||||
"call_key": (re.compile(r"[0-9a-f]{64}"), "the sha256 hex digest signing.call_key() gives the tool call"),
|
||||
"closer": (re.compile(r"[A-Za-z0-9_-]{32,128}"), "the hook's closer token of the session, 32 to 128 URL-safe characters"),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ ENTRY = re.compile(r"/api/stream/([0-9]{1,12})")
|
||||
BOARD = re.compile(r"/api/board/([a-z-]{1,32})")
|
||||
UPLOADS = "/api/uploads"
|
||||
MATCH_ROUTE = "/api/match"
|
||||
CLOSED_ROUTE = "/api/match/closed"
|
||||
PREVIEWS_ROUTE = "/api/runner/previews"
|
||||
RESTART_ROUTE = "/api/runner/restart"
|
||||
MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"}
|
||||
@@ -61,6 +62,7 @@ TASKS_ROUTE = "/api/tasks"
|
||||
GATES_ROUTE = "/api/gates"
|
||||
QUEUE_ROUTE = "/api/queue"
|
||||
PRUNE_ROUTE = "/api/prune"
|
||||
DISMISS_ROUTE = "/api/requests/dismiss"
|
||||
TOKEN_ROUTE = "/api/cleanup/token"
|
||||
VIEW_ROUTE = "/api/view"
|
||||
USAGE_ROUTE = "/api/usage"
|
||||
@@ -97,7 +99,7 @@ ACCOUNTS_IMPORT = {"/api/accounts/import/preview": "preview", "/api/accounts/imp
|
||||
SCHEDULES_ROUTE = "/api/schedules"
|
||||
LIMITS_ROUTE = "/api/limits"
|
||||
LIMITS_SIGN_ROUTE = "/api/limits/sign"
|
||||
ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE, LIMITS_SIGN_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, RULE_MATCH_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, QUEUE_ROUTE, PRUNE_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
|
||||
ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE, LIMITS_SIGN_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, RULE_MATCH_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, QUEUE_ROUTE, PRUNE_ROUTE, DISMISS_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
|
||||
|
||||
|
||||
class Handler(Exchange):
|
||||
@@ -172,6 +174,8 @@ class Handler(Exchange):
|
||||
self.answer(lambda: served(hub.tree.file.with_name(SKILLS_INDEX)), HTTPStatus.OK)
|
||||
elif path == MATCH_ROUTE:
|
||||
self.answer(hub.match_cards, HTTPStatus.OK)
|
||||
elif path == CLOSED_ROUTE:
|
||||
self.answer(hub.match_closed, HTTPStatus.OK)
|
||||
elif path == ACCOUNTS_ROUTE:
|
||||
self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK)
|
||||
elif path == ACCOUNTS_EXPORT:
|
||||
@@ -275,6 +279,8 @@ class Handler(Exchange):
|
||||
return lambda body: self.answer(lambda: hub.change_queue(body), HTTPStatus.ACCEPTED)
|
||||
if path == PRUNE_ROUTE:
|
||||
return lambda body: self.answer(lambda: hub.prune(body), HTTPStatus.ACCEPTED)
|
||||
if path == DISMISS_ROUTE:
|
||||
return lambda body: self.answer(lambda: hub.dismiss_requests(body), HTTPStatus.ACCEPTED)
|
||||
if path == TOKEN_ROUTE:
|
||||
return lambda body: self.answer(lambda: hub.token_row(body), HTTPStatus.CREATED)
|
||||
if inbox:
|
||||
|
||||
@@ -68,6 +68,7 @@ from .tasking import Tasking
|
||||
from .timeline import Timeline
|
||||
from .transcripts import Transcripts
|
||||
from .tree import TREE_HEARTBEAT, Tree
|
||||
from .triage import Triage
|
||||
from .view import RADIO_WINDOW, View
|
||||
from .viewstore import ViewStore
|
||||
from .voicenotes import VoiceNotes
|
||||
@@ -96,7 +97,7 @@ def environment(templates: Path) -> jinja2.Environment:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Queueing, Scheduling, Limiting, Prunes, Firewall, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language):
|
||||
class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Queueing, Scheduling, Limiting, Prunes, Firewall, Triage, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language):
|
||||
council: Path
|
||||
pages: Path
|
||||
public_port: int
|
||||
@@ -150,6 +151,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
|
||||
live_state: LiveState
|
||||
accounts: Accounts
|
||||
schedule_settings: Schedules
|
||||
dismissals: Ledger
|
||||
|
||||
def hosts(self) -> tuple[str, str]:
|
||||
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
|
||||
@@ -252,6 +254,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
|
||||
answers=Ledger(state / "answers.json"),
|
||||
messages=messages,
|
||||
rule_requests=Ledger(state / "rule-requests.json"),
|
||||
dismissals=Ledger(state / "dismissals.json"),
|
||||
uploads=uploads,
|
||||
host_state=host_state,
|
||||
transcripts=Transcripts(transcripts),
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import time
|
||||
|
||||
from .approving import INBOX_KINDS
|
||||
from .asking import IN_CLAUDE_WORDS
|
||||
from .choosing import answered, decision_status
|
||||
from .council import read_claims
|
||||
from .denying import requester_of
|
||||
@@ -20,7 +21,21 @@ LAPSE_WINDOW = 86400
|
||||
|
||||
|
||||
def item_base() -> dict:
|
||||
return {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": ""}
|
||||
return {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": "", "stale": False, "claude": False}
|
||||
|
||||
|
||||
def lapsed_item(item: dict, record: dict) -> dict:
|
||||
"""Args:
|
||||
item: the inbox item of a record lapsed_of() keeps.
|
||||
record: that ask or decision.
|
||||
|
||||
Returns:
|
||||
The item with its expires; a bound record's (asking.dialog_state()
|
||||
IN_CLAUDE) also with claude true and IN_CLAUDE_WORDS as blocked, as
|
||||
its dialog is open in Claude and the hub learns when it closes.
|
||||
"""
|
||||
claude = {"claude": True, "blocked": IN_CLAUDE_WORDS} if record.get("bound") else {}
|
||||
return {**item, "expires": record["expires"], **claude}
|
||||
|
||||
|
||||
def lapsed_of(records: list[dict], now: float, called: bool) -> list[dict]:
|
||||
@@ -54,7 +69,7 @@ class Inbox:
|
||||
created = iso_epoch(review["created"]) or now
|
||||
gate = review.get("gate", "")
|
||||
agent = review.get("agent", "")
|
||||
fields = {"title": review["title"], "detail": review["branch"], "green": gate == "pass", "gate": gate, "score": review.get("score", ""), "directory": review["worktree"], "agent": agent, "to": requester_of(claims, agent)[0], "diff": review.get("diff_files")}
|
||||
fields = {"title": review["title"], "detail": review["branch"], "green": gate == "pass", "gate": gate, "score": review.get("score", ""), "directory": review["worktree"], "agent": agent, "to": requester_of(claims, agent)[0], "diff": review.get("diff_files"), "stale": self.review_moved(review)}
|
||||
items.append({**base, "kind": "review", "id": review["id"], "ts": created, **fields})
|
||||
items += [self.inbox_ask(base, ask, claims, directory) for ask in self.asks.pending() if ask["expires"] > now]
|
||||
items += [decision_item(base, decision) for decision in self.decisions.pending() if decision_status(decision, now) == "pending"]
|
||||
@@ -67,7 +82,7 @@ class Inbox:
|
||||
busy = row["task"] in held
|
||||
answer = self.answers.get(row["task"])
|
||||
fields = {"answered": answer["label"] if answered(answer, row) else "", "title": row["command"], "detail": row["why"], "agent": adder(tasks[row["task"]]), "to": requester_of(claims, adder(tasks[row["task"]]))[0], "command": row["command"], "directory": row["directory"], "sha256": digest(row["command"]), "check": row["check"], "options": row["options"], "recommended": row["recommended"]}
|
||||
state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"]), "blocked": row_blocked(row, reasons)}
|
||||
state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"]), "blocked": row_blocked(row, reasons), "stale": self.row_moved(row)}
|
||||
items.append({**base, "kind": "operator", "id": row["task"], "ts": self.watch.first(row["task"], now), **fields, **state})
|
||||
listed = {row["task"] for row in rows}
|
||||
for task, job in consoles.items():
|
||||
@@ -75,7 +90,7 @@ class Inbox:
|
||||
fields = {"title": job["command"], "command": job["command"], "directory": job["directory"], "job": console_of(job), "settled": True}
|
||||
items.append({**base, "kind": "operator", "id": task, "ts": job["created_ts"], **fields})
|
||||
items += self.request_items(base, now, claims)
|
||||
return self.marked_items(items, now)
|
||||
return self.marked_items(self.triaged(items), now)
|
||||
|
||||
def marked_items(self, items: list[dict], now: float) -> list[dict]:
|
||||
for item in items:
|
||||
@@ -90,15 +105,17 @@ class Inbox:
|
||||
|
||||
def lapsed_items(self, now: float, directory: Directory) -> list[dict]:
|
||||
"""Returns:
|
||||
An item as inbox() builds it, with its expires, of every ask and
|
||||
decision lapsed_of() keeps; the Inbox lists none of them, Match
|
||||
keeps each greyed until the operator denies it.
|
||||
An item as inbox() builds it, through lapsed_item(), of every ask
|
||||
and decision lapsed_of() keeps and no dismissal hides; the
|
||||
snapshot lists them apart from the inbox, Match keeps each greyed
|
||||
until the operator denies it or, for a bound one, a hook closes
|
||||
it (asking.CLOSING).
|
||||
"""
|
||||
claims = read_claims(self.council)
|
||||
base = item_base()
|
||||
asks = [{**self.inbox_ask(base, ask, claims, directory), "expires": ask["expires"]} for ask in lapsed_of(self.asks.pending(), now, True)]
|
||||
decisions = [{**decision_item(base, decision), "to": requester_of(claims, decision["agent"])[0], "expires": decision["expires"]} for decision in lapsed_of(self.decisions.pending(), now, False)]
|
||||
return self.marked_items(asks + decisions, now)
|
||||
asks = [lapsed_item(self.inbox_ask(base, ask, claims, directory), ask) for ask in lapsed_of(self.asks.pending(), now, True)]
|
||||
decisions = [lapsed_item({**decision_item(base, decision), "to": requester_of(claims, decision["agent"])[0]}, decision) for decision in lapsed_of(self.decisions.pending(), now, False)]
|
||||
return self.marked_items(self.triaged(asks + decisions), now)
|
||||
|
||||
def linked(self, command: str) -> list[dict]:
|
||||
"""Returns:
|
||||
|
||||
@@ -22,6 +22,7 @@ class Ledger:
|
||||
self.file = file
|
||||
self.changed = threading.Condition()
|
||||
self.items: dict[str, dict] = {}
|
||||
self.moves = 0
|
||||
if file.is_file():
|
||||
self.items = json.loads(file.read_text(encoding="utf-8"))
|
||||
|
||||
@@ -93,6 +94,7 @@ class Ledger:
|
||||
return dict(record), False
|
||||
updated = {**record, **changes}
|
||||
self.write({**self.items, item_id: updated})
|
||||
self.moves += 1
|
||||
self.changed.notify_all()
|
||||
return dict(updated), True
|
||||
|
||||
|
||||
@@ -121,9 +121,11 @@ class Limiting:
|
||||
|
||||
def save_limits(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {limits, proof}: the whole limits object and, when a value
|
||||
loosens against the limits in force at this save, the
|
||||
passkey proof over signing.limits_item() of exactly it.
|
||||
body: {limits, proof}: the whole limits object, which carries a
|
||||
batch of staged changes at once (requirement 091), and,
|
||||
when any value of it loosens against the limits in force at
|
||||
this save, one passkey proof over signing.limits_item() of
|
||||
exactly it, which covers every looser value of the batch.
|
||||
|
||||
Returns:
|
||||
limits_view() after the write; ToolError (400) for limits
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import time
|
||||
|
||||
from .asking import IN_CLAUDE, IN_CLAUDE_WORDS
|
||||
from .council import NEWS, read_claims
|
||||
from .denying import LAPSED, requester_of
|
||||
from .diffs import stored_diff
|
||||
@@ -38,6 +39,24 @@ def expired_card(card: dict, expires: float) -> dict:
|
||||
return {**card, "blocked": EXPIRED_REASONS[card["kind"]], "blocked_kind": EXPIRED, "expires": expires}
|
||||
|
||||
|
||||
def claude_card(card: dict, expires: float) -> dict:
|
||||
"""Args:
|
||||
card: the waiting_card() of a bound ask or decision lapsed_of()
|
||||
keeps (inbox.lapsed_item()).
|
||||
expires: when its hook stopped waiting, in epoch seconds.
|
||||
|
||||
Returns:
|
||||
The card greyed with blocked_kind IN_CLAUDE, IN_CLAUDE_WORDS and its
|
||||
expires time: no stale or expired stamp, as its dialog is still open
|
||||
in Claude until a hook closes it.
|
||||
"""
|
||||
return {**card, "blocked": IN_CLAUDE_WORDS, "blocked_kind": IN_CLAUDE, "expires": expires}
|
||||
|
||||
|
||||
def lapsed_card(card: dict, item: dict) -> dict:
|
||||
return (claude_card if item["claude"] else expired_card)(card, item["expires"])
|
||||
|
||||
|
||||
def repository_of(common_dir: str) -> str:
|
||||
return common_dir.removesuffix("/.git") if common_dir.endswith("/.git") else common_dir
|
||||
|
||||
@@ -66,10 +85,12 @@ class Matching:
|
||||
def match_cards(self) -> dict:
|
||||
"""Returns:
|
||||
{"now", "cards"}: every card waiting on the operator, none held
|
||||
by a release in its undo window or while it applies; a held
|
||||
by a release in its undo window or while it applies and none
|
||||
dismissed (Triage.hidden_refs()); a held
|
||||
command card keeps its snapshot, so an undo shows it unchanged;
|
||||
an expired ask or decision stays, greyed by expired_card(),
|
||||
until the operator denies it.
|
||||
an expired ask or decision stays, greyed by lapsed_card(),
|
||||
until the operator denies it or, for a bound one, a hook closes
|
||||
it.
|
||||
"""
|
||||
now = time.time()
|
||||
claims = read_claims(self.council)
|
||||
@@ -77,7 +98,9 @@ class Matching:
|
||||
reviews = self.reviews.pending()
|
||||
labels = score_labels(self.scripts.skills)
|
||||
senders = {review["id"]: review.get("agent", "") for review in reviews}
|
||||
cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"])]
|
||||
hidden = self.hidden_refs()
|
||||
consoles = self.consoles()
|
||||
cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"]) and not self.review_hidden(hidden, review["id"])]
|
||||
tasks = read_register(self.council / REGISTER)
|
||||
blocked = self.blocked_rows(now)
|
||||
kinds = blocked_kinds(self.jobs.listed())
|
||||
@@ -86,14 +109,14 @@ class Matching:
|
||||
roots = denied_roots(self.settings_files()[0])
|
||||
scan = self.tree.get()
|
||||
for row in rows:
|
||||
if f"operator:{row['task']}" in releasing:
|
||||
if f"operator:{row['task']}" in releasing or self.row_hidden(hidden, row, consoles):
|
||||
continue
|
||||
owner = adder(tasks[row["task"]])
|
||||
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0], "blocked": row_blocked(row, blocked), "blocked_kind": row_blocked_kind(row, kinds)})
|
||||
directory = self.directory(claims, read_jsonl(self.council / NEWS), now)
|
||||
items = self.inbox(now, tasks, directory)
|
||||
cards += [self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels) for item in items if self.waits(item)]
|
||||
cards += [expired_card(self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels), item["expires"]) for item in self.lapsed_items(now, directory) if self.waits(item)]
|
||||
cards += [lapsed_card(self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels), item) for item in self.lapsed_items(now, directory) if self.waits(item)]
|
||||
asked = {row["task"] for row in operator_rows(tasks) if row["check"] == "decision"}
|
||||
for answer in self.answers.listed():
|
||||
if answer["id"] not in asked:
|
||||
@@ -105,15 +128,26 @@ class Matching:
|
||||
store.remove(snapshot["id"])
|
||||
return {"now": now, "cards": cards}
|
||||
|
||||
def match_closed(self) -> dict:
|
||||
"""Returns:
|
||||
{"closed"}: how many asks, decisions and reviews left pending
|
||||
since the hub started, read from the ledgers' counters without
|
||||
building a card or the state; a page that sees it move fetches
|
||||
Match and the state at once instead of at its next interval.
|
||||
"""
|
||||
return {"closed": self.asks.moves + self.decisions.moves + self.reviews.moves}
|
||||
|
||||
def match_open(self, inbox: list[dict]) -> int:
|
||||
"""Returns:
|
||||
How many cards match_cards() lists that can be decided, by its
|
||||
filters without building them: pending reviews, open command rows
|
||||
not held by a release and without a row_blocked() reason, and the
|
||||
inbox items waits() keeps.
|
||||
not held by a release and without a row_blocked() reason, none
|
||||
dismissed, and the inbox items waits() keeps.
|
||||
"""
|
||||
reviews = sum(1 for review in self.reviews.pending() if not self.batches.holds("review", review["id"]))
|
||||
rows = sum(1 for row in self.open_rows() if not self.batches.holds("operator", row["task"]) and not row_blocked(row, {}))
|
||||
hidden = self.hidden_refs()
|
||||
consoles = self.consoles()
|
||||
reviews = sum(1 for review in self.reviews.pending() if not self.batches.holds("review", review["id"]) and not self.review_hidden(hidden, review["id"]))
|
||||
rows = sum(1 for row in self.open_rows() if not self.batches.holds("operator", row["task"]) and not row_blocked(row, {}) and not self.row_hidden(hidden, row, consoles))
|
||||
return reviews + rows + sum(1 for item in inbox if self.waits(item))
|
||||
|
||||
def commit_card(self, review: dict, born: float | None, labels: dict | None) -> dict:
|
||||
|
||||
@@ -20,11 +20,12 @@ TRENDS = ("off", "regression", "velocity")
|
||||
TREND_DAYS = (1, 365)
|
||||
THRESHOLDS = tuple(range(0, ALWAYS + 1, 10))
|
||||
WPM = (5, 40)
|
||||
LATE = ("rates", "morse", "undo", "popups", "agents", "forecast", "match")
|
||||
LATE = ("rates", "morse", "undo", "popups", "agents", "forecast", "match", "hook")
|
||||
AGENT_SWITCHES = ("sound", "aloud", "bubbles")
|
||||
AGENTS_LIMIT = 200
|
||||
UNDO_RANGE = (0, 60)
|
||||
MATCH_REFRESH = (1, 60)
|
||||
HOOK_WAIT = (1, 60)
|
||||
POPUP_SOURCES = ("resources", "mayday", "dream")
|
||||
POPUP_UNTIL = 4102444800
|
||||
NOTIFY = "notify.json"
|
||||
@@ -62,6 +63,7 @@ SETTINGS = {
|
||||
"agents": {},
|
||||
"forecast": False,
|
||||
"match": {"refresh": 2},
|
||||
"hook": {"wait": 60},
|
||||
}
|
||||
RATE_CHIP = (2, 9)
|
||||
SPACE_AXES = ("none", "time", "spawn")
|
||||
@@ -217,6 +219,21 @@ def match_setting(raw: object) -> dict:
|
||||
return {"refresh": refresh}
|
||||
|
||||
|
||||
def hook_setting(raw: object) -> dict:
|
||||
"""Args:
|
||||
raw: {"wait"}: whole minutes the PermissionRequest hook waits for the
|
||||
hub while Claude shows its own dialog; scripts/orchestrator.sh
|
||||
hook writes it into the hook's --timeout and its settings.json
|
||||
timeout, so it applies from the next make orchestrator-hook.
|
||||
"""
|
||||
entry = section(raw, "hook", tuple(SETTINGS["hook"]))
|
||||
low, high = HOOK_WAIT
|
||||
wait = entry["wait"]
|
||||
if isinstance(wait, bool) or not isinstance(wait, int) or not low <= wait <= high:
|
||||
raise ToolError(f"hook.wait must be whole minutes from {low} to {high}")
|
||||
return {"wait": wait}
|
||||
|
||||
|
||||
def popups_setting(raw: object) -> dict:
|
||||
data = section(raw, "popups", POPUP_SOURCES)
|
||||
popups = {}
|
||||
@@ -288,6 +305,7 @@ def valid_settings(raw: object) -> dict:
|
||||
"agents": agents_setting(data["agents"]),
|
||||
"forecast": flag(data["forecast"], "forecast"),
|
||||
"match": match_setting(data["match"]),
|
||||
"hook": hook_setting(data["hook"]),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from .asking import ask_state
|
||||
from .choosing import answered, decision_status
|
||||
from .asking import dialog_state
|
||||
from .choosing import answered
|
||||
from .council import MAYDAY_ACTIVE, NEWS, message_rows, read_claims, sessions
|
||||
from .crons import cron_event
|
||||
from .errors import Missing, ToolError
|
||||
@@ -69,13 +69,13 @@ class Timeline:
|
||||
ref = {key: review.get(key, "") for key in ("id", "status", "gate", "score", "branch", "worktree", "tree", "files")}
|
||||
rows.append(event({"id": f"review:{review['id']}", "ts": created, "kind": "review", "title": review["title"], "text": review["notes"][:STREAM_CUT], "waiting": review["status"] == "pending", "ref": ref}))
|
||||
for ask in self.asks.listed():
|
||||
state = ask_state(ask, now)
|
||||
if ask["created_ts"] <= end and (state["status"] == "pending" or ask["created_ts"] >= begin):
|
||||
ref = {"id": ask["id"], "status": state["status"], "cwd": ask["cwd"], "tool": ask["tool"], "warnings": signing.warnings(ask["command"])}
|
||||
status = dialog_state(ask, now)
|
||||
if ask["created_ts"] <= end and (status == "pending" or ask["created_ts"] >= begin):
|
||||
ref = {"id": ask["id"], "status": status, "cwd": ask["cwd"], "tool": ask["tool"], "warnings": signing.warnings(ask["command"])}
|
||||
who = {"agent": directory.at(ask["session"], ask["created_ts"]), "now": directory.now(ask["session"]), "session": ask["session"]}
|
||||
rows.append(event({"id": f"ask:{ask['id']}", "ts": ask["created_ts"], "kind": "ask", **who, "title": ask["tool"], "text": ask["command"], "waiting": state["status"] == "pending", "ref": ref}))
|
||||
rows.append(event({"id": f"ask:{ask['id']}", "ts": ask["created_ts"], "kind": "ask", **who, "title": ask["tool"], "text": ask["command"], "waiting": status == "pending", "ref": ref}))
|
||||
for decision in self.decisions.listed():
|
||||
status = decision_status(decision, now)
|
||||
status = dialog_state(decision, now)
|
||||
if decision["created_ts"] <= end and (status == "pending" or decision["created_ts"] >= begin):
|
||||
ref = {**{key: decision.get(key, "") for key in ("id", "choice", "recommended", "options")}, "status": status}
|
||||
text = " · ".join(option["label"] for option in decision["options"])
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
from .council import NEWS, read_claims
|
||||
from .errors import Conflict, Missing, ToolError
|
||||
from .fields import decode, expect
|
||||
from .jobs import console_of
|
||||
from .previewing import card_id, merge_hash, review_card
|
||||
from .records import digest, read_jsonl, shown
|
||||
from .register import REGISTER, read_register
|
||||
from .signed import signing
|
||||
|
||||
REQUEST_KINDS = ("open", "expired", "stale", "failed")
|
||||
ALL = "all"
|
||||
SCOPES = (*REQUEST_KINDS, ALL)
|
||||
FAILED_JOBS = ("failed", "refused")
|
||||
DISMISS_VERB = "dismiss"
|
||||
DISMISS_KEYS = ("kind", "target", "id", "scope")
|
||||
DISMISS_LIMIT = 100
|
||||
REF_LIMIT = 200
|
||||
TITLE_LIMIT = 200
|
||||
TITLE_SHOWN = 80
|
||||
|
||||
|
||||
def request_kind(item: dict) -> str:
|
||||
"""Args:
|
||||
item: an inbox item, or one of lapsed_items(), the only items that
|
||||
carry expires.
|
||||
|
||||
Returns:
|
||||
Its one request kind: expired for a lapsed ask or decision, open for
|
||||
a lapsed bound one (claude), whose dialog is still open in Claude;
|
||||
failed for an operator row whose last hub job failed or the runner
|
||||
refused; stale for a review or row whose tree or merge preview moved
|
||||
since it was added; open for every other request.
|
||||
"""
|
||||
if "expires" in item:
|
||||
return "open" if item["claude"] else "expired"
|
||||
job = item["job"]
|
||||
if item["kind"] == "operator" and job is not None and job["status"] in FAILED_JOBS:
|
||||
return "failed"
|
||||
return "stale" if item["stale"] else "open"
|
||||
|
||||
|
||||
def request_mark(command: str, job: dict | None) -> str:
|
||||
"""Args:
|
||||
command: the command the request shows, "" for one without.
|
||||
job: the hub job console it shows, None for none.
|
||||
|
||||
Returns:
|
||||
What a dismissal binds besides kind and id, so a row whose command
|
||||
changed or that ran again shows again.
|
||||
"""
|
||||
return digest(json.dumps([command, "" if job is None else job["id"]]))
|
||||
|
||||
|
||||
def dismiss_entry(entry: object) -> bool:
|
||||
return isinstance(entry, dict) and entry.get("kind") == signing.DISMISS_KIND
|
||||
|
||||
|
||||
def dismiss_request(raw: object) -> bool:
|
||||
return isinstance(raw, list) and bool(raw) and all(dismiss_entry(entry) for entry in raw)
|
||||
|
||||
|
||||
def hides(hidden: tuple[dict[str, str], set[str]], key: str, mark: str) -> bool:
|
||||
"""Args:
|
||||
hidden: Triage.hidden_refs().
|
||||
key: <kind>:<id> of a request.
|
||||
mark: its request_mark().
|
||||
"""
|
||||
dismissed, pending = hidden
|
||||
return key in pending or dismissed.get(key) == mark
|
||||
|
||||
|
||||
class Triage:
|
||||
def hidden_refs(self) -> tuple[dict[str, str], set[str]]:
|
||||
"""Returns:
|
||||
The request_mark() of every dismissed request by <kind>:<id>, and
|
||||
the keys a dismissal holds in its undo window; hides() keeps both
|
||||
out of the snapshot, Match and the badge for every browser.
|
||||
"""
|
||||
dismissed = {key: mark for record in self.dismissals.listed() for key, mark in record["refs"].items()}
|
||||
pending = {f"{item['kind']}:{item['id']}" for batch in self.batches.listed() for item in batch["items"] if item["verb"] == DISMISS_VERB}
|
||||
return dismissed, pending
|
||||
|
||||
def triaged(self, items: list[dict]) -> list[dict]:
|
||||
"""Returns:
|
||||
The items hides() keeps, each with its request_kind() as request.
|
||||
"""
|
||||
hidden = self.hidden_refs()
|
||||
return [{**item, "request": request_kind(item)} for item in items if not hides(hidden, f"{item['kind']}:{item['id']}", request_mark(item["command"], item["job"]))]
|
||||
|
||||
def review_hidden(self, hidden: tuple[dict[str, str], set[str]], review_id: str) -> bool:
|
||||
return hides(hidden, review_card(review_id), request_mark("", None))
|
||||
|
||||
def row_hidden(self, hidden: tuple[dict[str, str], set[str]], row: dict, consoles: dict[str, dict]) -> bool:
|
||||
return hides(hidden, card_id(row["task"]), request_mark(row["command"], console_of(consoles.get(row["task"]))))
|
||||
|
||||
def review_moved(self, review: dict) -> bool:
|
||||
"""Returns:
|
||||
Whether the commit card of a pending review is stale, read from
|
||||
the ledgers alone: its staged tree changed, or the runner saw its
|
||||
worktree's HEAD move.
|
||||
"""
|
||||
preview = self.merge_previews.get(review_card(review["id"])) or {}
|
||||
return review.get("live_tree") not in (None, review["tree"]) or bool(preview.get("moved"))
|
||||
|
||||
def row_moved(self, row: dict) -> bool:
|
||||
"""Returns:
|
||||
Whether the command card of an open row is stale by its merge
|
||||
preview: the snapshot Match took is bound to another HEAD, merge
|
||||
base or diff than the preview the runner sent last. A changed
|
||||
payload file marks only the card, which reads the files.
|
||||
"""
|
||||
snapshot = self.match_snapshots.get(card_id(row["task"]))
|
||||
preview = self.preview_of(row)
|
||||
if row["check"] == "decision" or snapshot is None or preview is None or not snapshot.get("previewed"):
|
||||
return False
|
||||
return snapshot["command_sha256"] == digest(row["command"]) and snapshot["hash"] != merge_hash(row, preview)
|
||||
|
||||
def listed_requests(self) -> dict[str, dict]:
|
||||
"""Returns:
|
||||
Every request the snapshot lists, the inbox and the lapsed asks
|
||||
and decisions, by <kind>:<id>.
|
||||
"""
|
||||
now = time.time()
|
||||
claims = read_claims(self.council)
|
||||
directory = self.directory(claims, read_jsonl(self.council / NEWS), now)
|
||||
items = self.inbox(now, read_register(self.council / REGISTER), directory) + self.lapsed_items(now, directory)
|
||||
return {f"{item['kind']}:{item['id']}": item for item in items}
|
||||
|
||||
def dismissable(self, raw: object) -> list[dict]:
|
||||
"""Args:
|
||||
raw: the page's entries, each {"kind": "dismiss", "target", "id",
|
||||
"scope"}: the inbox kind and id of a request the snapshot
|
||||
lists, and the chip it is deleted from, one of SCOPES.
|
||||
|
||||
Returns:
|
||||
One batch item per entry, its signed the dismiss_item() the
|
||||
passkey signs: a listed request no batch holds whose request
|
||||
kind is the scope, any kind under the scope all.
|
||||
|
||||
Raises:
|
||||
ToolError for a malformed entry, Missing for a request the
|
||||
snapshot no longer lists, Conflict for a held one or one of
|
||||
another kind than its scope.
|
||||
"""
|
||||
if not isinstance(raw, list) or not 1 <= len(raw) <= DISMISS_LIMIT:
|
||||
raise ToolError(f"items must be a list of 1 to {DISMISS_LIMIT} requests")
|
||||
listed = self.listed_requests()
|
||||
chosen: list[dict] = []
|
||||
for entry in raw:
|
||||
if not isinstance(entry, dict):
|
||||
raise ToolError("every item must be an object with kind, target, id and scope")
|
||||
expect(entry, DISMISS_KEYS)
|
||||
target, item_id, scope = entry["target"], entry["id"], entry["scope"]
|
||||
if not all(isinstance(value, str) and 0 < len(value) <= REF_LIMIT for value in (target, item_id)) or not isinstance(scope, str) or scope not in SCOPES:
|
||||
raise ToolError(f"target and id must name a listed request and scope be one of {', '.join(SCOPES)}")
|
||||
item = listed.get(f"{target}:{item_id}")
|
||||
if item is None:
|
||||
raise Missing(shown(item_id)[:REF_LIMIT])
|
||||
if item["held"]:
|
||||
raise Conflict({"id": item_id, "status": "held"})
|
||||
if scope not in (ALL, item["request"]):
|
||||
raise Conflict({"id": item_id, "status": item["request"]})
|
||||
signed = signing.dismiss_item(target, item_id, item["request"], request_mark(item["command"], item["job"]))
|
||||
if any(other["signed"] == signed for other in chosen):
|
||||
raise ToolError("items must be distinct")
|
||||
chosen.append({"kind": target, "id": item_id, "verb": DISMISS_VERB, "label": "", "sha256": "", "title": shown(item["title"])[:TITLE_LIMIT], "gate": "", "request": item["request"], "signed": signed, "note": None})
|
||||
return chosen
|
||||
|
||||
def dismiss_requests(self, body: bytes) -> dict:
|
||||
"""Args:
|
||||
body: {"items", "proof"}: the page's entries (dismissable()) and
|
||||
the one passkey assertion over their dismiss items.
|
||||
|
||||
Returns:
|
||||
The batch in its undo window, without proof and timer; the
|
||||
requests leave the snapshot at once, /api/inbox/undo brings them
|
||||
back until apply_dismissals() settles the batch.
|
||||
"""
|
||||
payload = decode(body)
|
||||
expect(payload, ("items", "proof"))
|
||||
items = self.dismissable(payload["items"])
|
||||
self.proven(payload["proof"], [item["signed"] for item in items])
|
||||
return self.batches.add(items, "operator", None, self.apply_dismissals)
|
||||
|
||||
def apply_dismissals(self, batch: dict) -> None:
|
||||
"""Args:
|
||||
batch: dismissed requests past their undo window. Each stays out
|
||||
of the hub while its request_mark() holds; an open ask whose
|
||||
hook still waits is also denied without a reason, so its hook
|
||||
stops waiting for a card nobody sees, while one open in
|
||||
Claude stays pending for its dialog. No agent gets a radio
|
||||
message.
|
||||
"""
|
||||
now = time.time()
|
||||
refs = {f"{item['kind']}:{item['id']}": item["signed"]["mark"] for item in batch["items"]}
|
||||
self.dismissals.add({"refs": refs, "ts": now})
|
||||
waiting = [item["id"] for item in batch["items"] if item["kind"] == "ask" and item["request"] == "open" and (self.asks.get(item["id"]) or {"expires": now})["expires"] > now]
|
||||
denied = [ask_id for ask_id in waiting if self.asks.decide(ask_id, {"status": "denied", "proof": None})[1]]
|
||||
titles = ", ".join(item["title"][:TITLE_SHOWN] for item in batch["items"])
|
||||
self.log.add({"kind": "approval", "title": f"Deleted {len(refs)} requests: {titles}"[:TITLE_LIMIT], "text": f"{len(denied)} open asks denied ({batch['source']})", "ref": {"verb": DISMISS_VERB, "items": sorted(refs), "denied": denied, "source": batch["source"]}})
|
||||
@@ -156,6 +156,7 @@ class View:
|
||||
"speech": {**self.speech.describe(), "gate": self.speech_gate.state()},
|
||||
"people": people,
|
||||
"inbox": inbox,
|
||||
"lapsed": self.lapsed_items(now, directory),
|
||||
"badges": badges(self.match_open(inbox), claims, self.jobs.listed(), now),
|
||||
"pending": self.batches.listed(),
|
||||
"rules": self.rule_rows(now),
|
||||
|
||||
Reference in new issue
Block a user