feat(hub): requirements 023 to 031 and line comments on grant-time code

023 box heads: one head band per box under its top border; in widget mode
its controls join the widget title band.
024 Match card content: merge cards show their diff (the runner previews a
review's tree against its worktree HEAD), every card carries legal and
architecture scores, the null under command cards is gone.
025 Radio speak card: no hint text, a rounder flowing card, a MAYDAY toggle
beside push to talk.
026 widget zoom: zoom a widget's content by keyboard and the context menu.
027 slash skill suggestions: every field that messages agents suggests
skills after a slash, from a skills index the tree timer writes.
028 Resources accounts: an Accounts panel (provider, renewal, resets, usage
and remaining, host-local, emails never in git) and panel checkboxes.
029 Controls layout: Rules and Groups pages laid out.
030 Yes/No answers as buttons, and nothing hides: rows the runner cannot
run stay greyed with the reason.
031 mic in fields.
Line comments (operator 2026-11-24): wherever code waits for a grant
(Waits on Operator, the stream, the review overlay) selected lines or a
right-clicked row take a comment that marks its lines and collects on the
card; Deny opens with them as the reason and Call preselected, Grant sends
them after the signed grant as one post. Requirement 003 decision 4 and
its contract follow.

Tests are written for every requirement and run once on this head.

🎯 Fix: 80 %
💥 Break: 20 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: ~95 %
🏆 Score: 61
🚦 Gate: ⛔ fix 80 % < 90, break 20 % > 5; security ~95 % < 100: ask the operator before the commit

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-25 01:22:03 +00:00
1 parent 7d1926e3de
commit 2722cda1b5
120 files changed
+5372 -486

No files matched your search

+168
View File
@@ -0,0 +1,168 @@
from __future__ import annotations
import contextlib
import datetime
import re
from pathlib import Path
from .errors import Missing, ToolError
from .fields import FIELDS, decode, visible
from .ledger import Ledger
from .records import read_jsonl
from .resources import HOUR, RESOURCES, TOKENS, rows_between
from .settings import flag, section
ACCOUNTS = "accounts.json"
SESSION_ACCOUNTS = "session-accounts.jsonl"
KEYS = ("provider", "email", "renewal", "reset", "resubscribe", "autorenew", "limit", "note")
MOMENT = ("day", "time")
EMAIL = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})*\.[A-Za-z]{2,24}")
TIME = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]")
DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
PROVIDER = re.compile(r"(?=[^\x00-\x1f\x7f]*\S)[^\x00-\x1f\x7f]{1,40}")
NOTE_LIMIT = 200
LIMIT_CAP = 10**15
RECENT = 8 * 24 * HOUR
COUNTS = ("input", "output", "cache_read", "cache_write")
def moment(value: object, name: str) -> dict:
"""Returns:
{day, time}: day 0 for Sunday to 6 for Saturday as Date.getDay()
counts, time HH:MM local; anything else raises ToolError.
"""
data = section(value, name, MOMENT)
day, time = data["day"], data["time"]
if isinstance(day, bool) or not isinstance(day, int) or not 0 <= day <= 6:
raise ToolError(f"{name}.day must be a weekday from 0 (Sunday) to 6 (Saturday)")
if not isinstance(time, str) or not TIME.fullmatch(time):
raise ToolError(f"{name}.time must be a time HH:MM")
return {"day": day, "time": time}
def resubscribe(value: object) -> str:
if value == "":
return ""
if isinstance(value, str) and DATE.fullmatch(value):
with contextlib.suppress(ValueError):
return datetime.date.fromisoformat(value).isoformat()
raise ToolError("resubscribe must be a date YYYY-MM-DD or empty")
def valid_account(raw: object) -> dict:
"""Args:
raw: the account as the page sent it, every key of KEYS.
Returns:
The account; a missing or unknown key, a bad email, weekday, time or
date, or a negative limit raises ToolError.
"""
data = section(raw, "account", KEYS)
if not isinstance(data["provider"], str) or not PROVIDER.fullmatch(data["provider"]):
raise ToolError("provider must be one line of 1 to 40 characters")
if not isinstance(data["email"], str) or not EMAIL.fullmatch(data["email"]):
raise ToolError("email must be an address like name@example.org")
limit = data["limit"]
if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or not 0 <= limit <= LIMIT_CAP):
raise ToolError(f"limit must be empty or a whole number of tokens from 0 to {LIMIT_CAP}")
if not isinstance(data["note"], str) or len(data["note"]) > NOTE_LIMIT:
raise ToolError(f"note must be text of at most {NOTE_LIMIT} characters")
account = {
"provider": data["provider"].strip(),
"email": data["email"],
"renewal": moment(data["renewal"], "renewal"),
"reset": moment(data["reset"], "reset"),
"resubscribe": resubscribe(data["resubscribe"]),
"autorenew": flag(data["autorenew"], "autorenew"),
"limit": limit,
"note": data["note"].strip(),
}
visible({"provider": account["provider"], "note": account["note"]})
return account
def mapping(file: Path) -> dict[str, str]:
"""Returns:
Each session's email, the last line the SessionStart hook wrote for
it winning, in the order the sessions first appear.
"""
found: dict[str, str] = {}
for row in read_jsonl(file):
session, email = row.get("session"), row.get("email")
if isinstance(session, str) and isinstance(email, str) and EMAIL.fullmatch(email):
found[session] = email
return found
def active(file: Path) -> str | None:
"""Returns:
The email of the newest mapping line: the account the host's
Claude Code logged in with at the last session start.
"""
emails = [row.get("email") for row in read_jsonl(file)]
valid = [email for email in emails if isinstance(email, str) and EMAIL.fullmatch(email)]
return valid[-1] if valid else None
def usage(rows: list[dict], now: float) -> dict[str, dict]:
"""Args:
rows: token rows {t, agent, model, input, output, cache_read,
cache_write, account?, width?}.
now: the epoch seconds the recent hours end at.
Returns:
Per account email, "" for rows of no mapped session: {total, hours},
total the tokens of every row, hours [t, tokens] per hourly row of
the last 8 days in time order, for the page to sum from the local
weekly reset and midnight.
"""
found: dict[str, dict] = {}
for row in rows:
account = row.get("account") if isinstance(row.get("account"), str) else ""
tokens = sum(value for value in (row.get(name) for name in COUNTS) if isinstance(value, int) and not isinstance(value, bool) and value > 0)
entry = found.setdefault(account, {"total": 0, "hours": {}})
entry["total"] += tokens
t = row.get("t")
if "width" not in row and isinstance(t, int | float) and now - RECENT <= t <= now:
entry["hours"][int(t)] = entry["hours"].get(int(t), 0) + tokens
return {account: {"total": entry["total"], "hours": sorted(entry["hours"].items())} for account, entry in found.items()}
class Accounts:
def __init__(self, state: Path, kept: Path, council: Path) -> None:
self.ledger = Ledger(state / ACCOUNTS)
self.tokens = kept / RESOURCES / TOKENS
self.sessions = council / SESSION_ACCOUNTS
def view(self, now: float) -> dict:
"""Returns:
{accounts, active, usage}: the stored accounts, the active
account's email or None, and usage() of every token row.
"""
return {"accounts": self.ledger.listed(), "active": active(self.sessions), "usage": usage(rows_between(self.tokens, 0, now, 0), now)}
def save(self, body: bytes) -> dict:
"""Args:
body: {account, id}: id "" adds the account, else it replaces
the account of that id.
"""
data = section(decode(body), "body", ("account", "id"))
account = valid_account(data["account"])
if data["id"] == "":
return self.ledger.add(account)
changed = self.ledger.change(self.known(data), account)
if changed is None:
raise Missing("no such account")
return changed
def drop(self, account_id: str) -> dict:
if not self.ledger.remove(account_id):
raise Missing("no such account")
return {"removed": account_id}
@staticmethod
def known(data: dict) -> str:
pattern, hint = FIELDS["id"]
if not isinstance(data["id"], str) or not pattern.fullmatch(data["id"]):
raise ToolError(f"id must be empty or {hint}")
return data["id"]
+6 -5
View File
@@ -253,22 +253,23 @@ class Firewall:
def settings_files(self) -> tuple[list[dict], dict]:
"""Returns:
The listed settings files the host writer last read, each
{"path", "exists", "sha256", "error", "settings", "own"} with
settings only the part signing.settings_view() keeps, and the
view's written time, error and tools_of().
{"path", "exists", "folder", "sha256", "error", "settings", "own"}
with settings only the part signing.settings_view() keeps and
folder False only when the writer found no directory for the
path, and the view's written time, error and tools_of().
"""
view = read_json(self.firewall_spool.root / VIEW)
files = view.get("files") if isinstance(view, dict) else None
if not isinstance(files, list):
return [], {"written": None, "error": "no settings view yet: the kvb-orchestrator-firewall unit writes it on the host", "tools": None}
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "folder": entry.get("folder") is not False, "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
return shown, {"written": view.get("written"), "error": "", "tools": tools_of(shown, view.get("known"))}
def firewall(self) -> dict:
files, meta = self.settings_files()
now = time.time()
asks = self.recent_subjects("ask", now)
listed = [{key: entry[key] for key in ("path", "exists", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
listed = [{key: entry[key] for key in ("path", "exists", "folder", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
rules = {rule["id"]: stored_hits(rule, asks, now) for rule in self.rules.listed()}
return {**meta, "files": listed, "lists": list(signing.SETTINGS_LISTS), "patterns": deny_patterns(), "groups": self.groups.listed(), "sets": self.rule_sets.listed(), "days": RECENT_DAYS, "rules": rules}
+14 -2
View File
@@ -13,6 +13,7 @@ from .exchange import PLAIN_CSP, Exchange
from .rates import rated
from .resources import RESOURCES, sampled
from .scores import scored
from .skillindex import SKILLS_INDEX, served
BODY_LIMIT = 1 << 20
UPLOAD_LIMIT = 50 << 20
@@ -78,7 +79,9 @@ FIREWALL_STATE = re.compile(r"/api/firewall/settings/([0-9a-f]{16})")
FIREWALL_DROP = re.compile(r"/api/firewall/(groups|sets)/([0-9a-f]{16})/delete")
FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPStatus.ACCEPTED, "add_group": HTTPStatus.CREATED, "add_set": HTTPStatus.CREATED}
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
ACCOUNTS_ROUTE = "/api/accounts"
ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete")
ACTION_POSTS = (ACCOUNTS_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
class Handler(Exchange):
@@ -137,8 +140,12 @@ class Handler(Exchange):
self.answer(lambda: hub.events(self.query()), HTTPStatus.OK)
elif path == "/api/tree":
self.answer(hub.repositories, HTTPStatus.OK)
elif path == "/api/skills":
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 == ACCOUNTS_ROUTE:
self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK)
elif path == "/api/resources":
self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK)
elif path == "/api/scores":
@@ -182,6 +189,11 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.sign_board(body), HTTPStatus.OK)
if board:
return lambda body: self.answer(lambda: hub.board(board.group(1), body), HTTPStatus.OK)
drop = ACCOUNT_DROP.fullmatch(path)
if path == ACCOUNTS_ROUTE:
return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK)
if drop:
return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK)
reveal = REVEAL_ROUTE.fullmatch(path)
if reveal:
method = hub.sign_reveal if reveal.group(3) else hub.reveal
@@ -263,7 +275,7 @@ class Handler(Exchange):
return None
def posted(self, path: str) -> bool:
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE))
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE, ACCOUNT_DROP))
def runner(self, path: str, body: bytes) -> None:
hub = self.server.hub
+3
View File
@@ -10,6 +10,7 @@ from pathlib import Path
import jinja2
from markupsafe import Markup
from .accounts import Accounts
from .approving import Approving
from .artifacts import Touched
from .asking import Asking
@@ -140,6 +141,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
match_snapshots: Ledger
merge_previews: Ledger
live_state: LiveState
accounts: Accounts
def hosts(self) -> tuple[str, str]:
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
@@ -208,6 +210,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
voice_notes=VoiceNotes(state / "voice", host_state / "voice", speech, lambda: {message["voice"] for message in messages.listed() if message.get("voice")}),
replay=state / "replay" / "messages.json",
view_store=ViewStore(state / "view.json"),
accounts=Accounts(state, places.kept, council),
match_snapshots=Ledger(state / "match.json"),
merge_previews=Ledger(state / "previews.json"),
live_state=LiveState(live_ttl),
+4 -3
View File
@@ -8,7 +8,7 @@ from .council import read_claims
from .denying import requester_of
from .errors import ToolError
from .fields import decode, expect
from .jobs import console_of
from .jobs import console_of, row_blocked
from .names import Directory
from .records import digest, iso_epoch
from .register import adder, operator_rows, runnable
@@ -21,7 +21,7 @@ SNOOZE_LIMIT = 8 * 86400
class Inbox:
def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]:
claims = read_claims(self.council)
base = {"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": []}
base = {"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": ""}
items = []
for review in self.reviews.pending():
created = iso_epoch(review["created"]) or now
@@ -38,6 +38,7 @@ class Inbox:
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi"))}
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
held = self.open_jobs()
reasons = self.blocked_rows(now)
consoles = self.consoles()
pattern = task_pattern(self.scripts.skills)
rows = [row for row in operator_rows(tasks) if pattern is not None and pattern.fullmatch(row["task"])]
@@ -45,7 +46,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"])}
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)}
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():
+42
View File
@@ -14,6 +14,7 @@ CONSOLE = ("id", "status", "code", "output", "created_ts", "started", "finished"
TASK_JOB = "task"
GATE_JOB = "gate"
CHANGES = (TASK_JOB, GATE_JOB)
UNRUNNABLE = "The hub runner needs a command and an absolute directory, and this row lacks one; run it with operator.py run in a terminal."
def runner_job(job: dict) -> dict:
@@ -32,10 +33,51 @@ def console_of(job: dict | None) -> dict | None:
return None if job is None else {**{key: job[key] for key in CONSOLE}, "output": job["output"][-OUTPUT_LIMIT:]}
def minutes_since(ts: float | None, now: float) -> int:
return max(0, round((now - (ts or now)) / 60))
def blocked_reasons(jobs: list[dict], now: float) -> dict[str, str]:
"""Args:
jobs: every hub job record.
Returns:
Per task with a queued or running job why its row cannot be run or
denied now: how long the runner runs it, or how long it waits and
which job the runner, which runs one job at a time, started last.
"""
open_jobs = [job for job in jobs if job["status"] in JOB_OPEN]
running = max((job for job in open_jobs if job["status"] == "running"), key=lambda job: job["started"] or 0, default=None)
ahead = "" if running is None else f" behind {running['task']}, which runs for {minutes_since(running['started'], now)} min"
reasons = {}
for job in sorted(open_jobs, key=lambda job: job["created_ts"]):
if job["status"] == "running":
reasons[job["task"]] = f"The hub runner runs it for {minutes_since(job['started'], now)} min; its result comes in Waits on Operator."
else:
reasons[job["task"]] = f"Queued in the hub runner for {minutes_since(job['created_ts'], now)} min{ahead}; the runner runs one job at a time."
return reasons
def row_blocked(row: dict, reasons: dict[str, str]) -> str:
"""Args:
row: an open operator row.
reasons: blocked_reasons() of the hub jobs.
Returns:
Why no area can run or deny the row now, "" when one can: its open
hub job, else for a command row without a command or an absolute
directory UNRUNNABLE; a decision row is answered, never run.
"""
return reasons.get(row["task"]) or ("" if row["check"] == "decision" or runnable(row) else UNRUNNABLE)
class Jobs:
def open_jobs(self) -> set[str]:
return {job["task"] for job in self.jobs.listed() if job["status"] in JOB_OPEN}
def blocked_rows(self, now: float) -> dict[str, str]:
return blocked_reasons(self.jobs.listed(), now)
def consoles(self) -> dict[str, dict]:
latest: dict[str, dict] = {}
for job in sorted(self.jobs.listed(), key=lambda job: job["created_ts"]):
+24 -6
View File
@@ -8,6 +8,7 @@ from .denying import requester_of
from .diffs import stored_diff
from .errors import Conflict, Missing, ToolError
from .fields import decode, expect, field
from .jobs import row_blocked
from .payloads import denied_roots, payload_files, payload_hash
from .previewing import merge_hash
from .records import digest, iso_epoch, read_jsonl
@@ -59,8 +60,8 @@ class Matching:
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"])]
tasks = read_register(self.council / REGISTER)
held = self.open_jobs()
rows = [row for row in operator_rows(tasks) if row["check"] != "decision" and row["task"] not in held]
blocked = self.blocked_rows(now)
rows = [row for row in operator_rows(tasks) if row["check"] != "decision"]
releasing = {f"operator:{row['task']}" for row in rows if self.batches.holds("operator", row["task"])}
roots = denied_roots(self.settings_files()[0])
scan = self.tree.get()
@@ -68,7 +69,7 @@ class Matching:
if f"operator:{row['task']}" in releasing:
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]})
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)})
items = self.inbox(now, tasks, self.directory(claims, read_jsonl(self.council / NEWS), now))
cards += [self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels) for item in items if self.waits(item)]
asked = {row["task"] for row in operator_rows(tasks) if row["check"] == "decision"}
@@ -82,6 +83,17 @@ class Matching:
store.remove(snapshot["id"])
return {"now": now, "cards": cards}
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.
"""
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, {}))
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:
live = review.get("live_tree")
reason = "the staged tree changed since it was added" if live not in (None, review["tree"]) else ""
@@ -89,12 +101,17 @@ class Matching:
files = stored_diff(self.reviews.pages, "review", review["id"])["diff"]
except Missing:
files = None
preview = self.review_preview(review["id"])
if preview is not None:
files = preview.get("diff")
reason = reason or ("HEAD moved since it was added" if preview.get("moved") else "")
place = {"repo": repository_of(review.get("repo", "")), "branch": review["branch"], "worktree": review["worktree"]}
return {
"id": f"review:{review['id']}", "kind": "commit", "ref": review["id"], "agent": review.get("agent", ""), "born": born, "created_ts": iso_epoch(review["created"]),
**place, "title": review["title"], "score": review.get("score", ""), "metrics": metric_chips(review.get("score", ""), labels, True), "gate": review.get("gate", ""),
"hash": review["tree"], "live_hash": live or review["tree"],
"stale": bool(reason), "stale_reason": reason, "files": files, "command": "", "directory": review["worktree"], "reason": "",
"diff_error": None if preview is None else preview.get("error"),
}
def card_payload(self, row: dict, roots: list[str] | None) -> tuple[list[dict], str, dict | None]:
@@ -113,10 +130,11 @@ class Matching:
"""Returns:
Whether an inbox item is a Match card of its own: an ask, a
choice, a rule request, or a decision row not yet answered with
its current question, none held by a release in its undo window;
commits and commands have their own cards.
its current question, none held by a release in its undo window
nor snoozed in Waits on Operator; commits and commands have their
own cards.
"""
if item["held"]:
if item["held"] or item["until"]:
return False
if item["kind"] == "operator":
return item["check"] == "decision" and not item["settled"] and item["job"] is None and not item["answered"]
+60 -7
View File
@@ -4,9 +4,9 @@ import json
import re
import time
from .diffs import valid_diff
from .diffs import stored_diff, valid_diff
from .errors import Conflict, Missing, ToolError
from .fields import bounded, decode, expect
from .fields import bounded, decode, expect, field
from .records import digest
from .register import OPERATOR, REGISTER, operator_rows, read_register
from .signed import signing
@@ -15,12 +15,18 @@ OBJECT_ID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
ERROR_LIMIT = 500
SHOWN = ("task", "command", "head", "base", "target", "diff")
FAILED = ("task", "command", "head", "error")
REVIEW_SHOWN = ("id", "head", "diff")
REVIEW_FAILED = ("id", "head", "error")
def card_id(task: str) -> str:
return f"operator:{task}"
def review_card(review_id: str) -> str:
return f"review:{review_id}"
def object_id(payload: dict, name: str, empty: bool) -> str:
value = payload[name]
if not isinstance(value, str) or not (OBJECT_ID.fullmatch(value) or (empty and value == "")):
@@ -51,22 +57,69 @@ class Previewing:
found = self.merge_previews.get(card_id(row["task"]))
return found if found is not None and found["command"] == row["command"] else None
def shipped(self, review_id: str) -> bool:
try:
return bool(stored_diff(self.reviews.pages, "review", review_id)["diff"])
except Missing:
return False
def review_preview(self, review_id: str) -> dict | None:
"""Returns:
The runner's diff of a review that shipped none, its staged tree
against its worktree's HEAD: {head, diff} or {head, error}, with
moved, the HEAD it saw later, once HEAD moved; None before any.
"""
return None if self.shipped(review_id) else self.merge_previews.get(review_card(review_id))
def preview_rows(self) -> dict:
"""Returns:
{"rows"}: every open operator row in an absolute directory with
the HEAD of the preview the hub holds, None for none, for the
runner to preview the git merges among them.
{"rows", "reviews"}: every open operator row in an absolute
directory with the HEAD of the preview the hub holds, None for
none, for the runner to preview the git merges among them; and
every pending review in an absolute worktree that shipped no
diff, with its tree and the HEAD the hub last saw, for the
runner to diff the tree against HEAD.
"""
rows = [row for row in self.open_rows() if row["directory"].startswith("/")]
return {"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows]}
reviews = [review for review in self.reviews.pending() if review["worktree"].startswith("/") and not self.shipped(review["id"])]
seen = {review["id"]: self.merge_previews.get(review_card(review["id"])) or {} for review in reviews}
return {
"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows],
"reviews": [{"id": review["id"], "worktree": review["worktree"], "tree": review["tree"], "head": seen[review["id"]].get("moved") or seen[review["id"]].get("head")} for review in reviews],
}
def record_review_preview(self, payload: dict) -> dict:
expect(payload, REVIEW_FAILED if "error" in payload else REVIEW_SHOWN)
review_id = field(payload, "id")
review = self.reviews.get(review_id)
if review is None or review["status"] != "pending":
raise Missing(review_id)
head = object_id(payload, "head", "error" in payload)
key = review_card(review_id)
found = self.merge_previews.get(key)
if found is not None and "diff" in found and found["head"] != head:
self.merge_previews.change(key, {"moved": head})
return {"id": key, "head": head}
record = {"head": head, "taken": time.time()}
if "error" in payload:
record["error"] = bounded(payload, "error", ERROR_LIMIT)
else:
record["diff"] = valid_diff(payload["diff"])
self.merge_previews.remove(key)
self.merge_previews.insert(key, record)
return {"id": key, "head": head}
def record_preview(self, body: bytes) -> dict:
"""Args:
body: from the runner, {task, command, head, base, target, diff}
for a git merge row, or {task, command, head, error} when it
could not preview it; head is empty when HEAD is unreadable.
could not preview it; {id, head, diff} or {id, head, error}
for a review that shipped no diff; head is empty when HEAD is
unreadable.
"""
payload = decode(body)
if "id" in payload:
return self.record_review_preview(payload)
expect(payload, FAILED if "error" in payload else SHOWN)
task = payload["task"]
if not isinstance(task, str) or not task.startswith(OPERATOR) or not signing.TASK.fullmatch(task):
+9 -4
View File
@@ -10,7 +10,7 @@ LABELS = "kvb-check-score/labels.json"
FILE_LIMIT = 64 << 20
VARIATION = "️"
VALUE = r"([0-9]+(?:\.[0-9]+)?(?:\s*%|:[0-9]+(?:\.[0-9]+)?)?|–|-|new)(?![0-9.])"
CHIP_EXTRAS = ("value",)
CHIP_EXTRAS = ("legal", "architecture", "value")
def checked(labels: object) -> dict | None:
@@ -71,7 +71,8 @@ def metric_chips(score: str, labels: dict | None, bare: bool) -> list[dict]:
text, where "fix 2 tests" is no score.
Returns:
In label order, then the CHIP_EXTRAS, per metric whose emoji (with or
In label order, each CHIP_EXTRAS entry right before the metric its
"before" names, else after all, per metric whose emoji (with or
without its variation selector) or label or former label stands
right before a value in score (the label alone only when bare), the
first such value: {"id", "emoji", "label", "value"}; none without
@@ -79,8 +80,12 @@ def metric_chips(score: str, labels: dict | None, bare: bool) -> list[dict]:
"""
found = []
extras = (labels or {}).get("extras")
shown = [(key, extras[key]) for key in CHIP_EXTRAS if isinstance(extras, dict) and checked({"metrics": {key: extras.get(key)}})]
for key, metric in [*(labels or {}).get("metrics", {}).items(), *shown]:
ordered = list((labels or {}).get("metrics", {}).items())
for key in CHIP_EXTRAS:
if isinstance(extras, dict) and checked({"metrics": {key: extras.get(key)}}):
keys = [name for name, _ in ordered]
ordered.insert(keys.index(extras[key]["before"]) if extras[key].get("before") in keys else len(ordered), (key, extras[key]))
for key, metric in ordered:
emoji = re.escape(metric["emoji"].removesuffix(VARIATION)) + f"{VARIATION}?"
names = "|".join(re.escape(name) for name in (metric["label"], *metric.get("former", [])))
alone = rf"|\b(?:{names})\s*:?\s*" if bare else ""
@@ -0,0 +1,40 @@
from __future__ import annotations
import re
from pathlib import Path
from .records import read_json
SKILLS_INDEX = "skills-index.json"
NAME = re.compile(r"[A-Za-z0-9:_.-]{1,100}")
TEXT_CHARS = 300
SOURCE_CHARS = 1000
SKILLS_LIMIT = 2000
def entry(raw: object) -> dict | None:
"""Returns:
{name, description, source} of an index row whose name matches NAME
and whose description and source are strings within their limits;
None for any other row.
"""
if not isinstance(raw, dict):
return None
name, description, source = raw.get("name"), raw.get("description"), raw.get("source")
if not isinstance(name, str) or not NAME.fullmatch(name) or not isinstance(description, str) or not isinstance(source, str) or not source or len(source) > SOURCE_CHARS:
return None
return {"name": name, "description": description[:TEXT_CHARS], "source": source}
def served(file: Path) -> dict:
"""Args:
file: the index client/skills_index.py writes next to the branch tree.
Returns:
{"skills"}: its valid rows, at most SKILLS_LIMIT, sorted by name and
source; none while the file is missing or unreadable.
"""
data = read_json(file)
rows = data.get("skills") if isinstance(data, dict) else None
found = [shown for raw in rows[:SKILLS_LIMIT] if (shown := entry(raw)) is not None] if isinstance(rows, list) else []
return {"skills": sorted(found, key=lambda row: (row["name"], row["source"]))}
+4 -3
View File
@@ -9,6 +9,7 @@ from .crons import cron_event
from .errors import Missing, ToolError
from .events import event, event_filters, wanted
from .fields import instant, single, whole
from .jobs import row_blocked
from .names import Directory
from .receipts import read_of
from .records import iso_epoch, read_jsonl
@@ -81,12 +82,12 @@ class Timeline:
source = directory.key(decision["agent"], decision["created_ts"])
who = {"agent": directory.at(source, decision["created_ts"]) or decision["agent"], "now": directory.now(source), "session": source}
rows.append(event({"id": f"decision:{decision['id']}", "ts": decision["created_ts"], "kind": "decision", **who, "title": decision["question"][:300], "text": text, "waiting": status == "pending", "ref": ref}))
held = self.open_jobs()
reasons = self.blocked_rows(now)
for row in operator_rows(tasks):
first = self.watch.first(row["task"], now)
if first <= end:
ref = {key: row[key] for key in ("task", "directory", "check", "status")}
rows.append(event({"id": f"operator:{row['task']}", "ts": first, "kind": "operator", "title": row["command"], "text": row["why"], "waiting": row["task"] not in held, "ref": ref}))
ref = {**{key: row[key] for key in ("task", "directory", "check", "status")}, "blocked": row_blocked(row, reasons)}
rows.append(event({"id": f"operator:{row['task']}", "ts": first, "kind": "operator", "title": row["command"], "text": row["why"], "waiting": True, "ref": ref}))
rows += [change for change in self.watch.listed() if begin <= change["ts"] <= end]
rows += [cron_event(cron, directory) for cron in self.schedules(claims, now) if cron["created"] <= end and (cron["active"] or cron["created"] >= begin)]
rows += [row for row in self.log.listed() if begin <= row["ts"] <= end]
+3 -3
View File
@@ -58,9 +58,9 @@ ENCODER_CSP = (
)
def badges(inbox: list[dict], claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
def badges(cards: int, claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
return {
"tasks": sum(1 for item in inbox if not item["until"] and not item["settled"]),
"tasks": cards,
"agents": len({claim["agent"] for claim in claims if claim["beat"] is not None and claim["beat"] >= now - ACTIVE}),
"artifacts": sum(1 for job in jobs if job["status"] in JOB_OPEN),
}
@@ -146,7 +146,7 @@ class View:
"speech": {**self.speech.describe(), "gate": self.speech_gate.state()},
"people": people,
"inbox": inbox,
"badges": badges(inbox, claims, self.jobs.listed(), now),
"badges": badges(self.match_open(inbox), claims, self.jobs.listed(), now),
"pending": self.batches.listed(),
"rules": [{**{key: value for key, value in rule.items() if key != "proof"}, "signed": rule.get("proof") is not None} for rule in self.rules.listed()],
"approvers": self.keys(),
+44 -8
View File
@@ -15,9 +15,9 @@ from .settings import flag, section
VIEW_LIMIT = 64 << 10
CHANGE_LIMIT = 2 * VIEW_LIMIT + (1 << 10)
VIEW = {
"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []},
"resources": {"hidden": [], "tokens": "interval", "panels": ["hardware", "tokens", "accounts"], "combinedHidden": []},
"burn": {"overlays": []},
"home": {"pins": []},
"home": {"pins": [], "zoom": {}},
"kanban": {"hidden": []},
"legend": {"views": {}, "tiles": {}},
"approval": {"mode": "direct"},
@@ -37,8 +37,10 @@ OVERLAYS = ("fix", "break", "tokens", "velocity", "security", "score")
KANBAN_LAYERS = ("line", "jobs")
PINS_LIMIT = 64
SPAN = (1, 12)
ZOOM = (50, 200, 10)
METRIC = "metric"
CHARTS = ("hardware", "tokens", "combined")
PANELS = (*CHARTS, "accounts")
SHOWN_LIMIT = 100
FNV_PRIME = 0x01000193
FNV_SEEDS = (0x811C9DC5, 0x01000193)
@@ -145,6 +147,30 @@ def pins(value: object) -> list[dict]:
return found
def zooms(value: object) -> dict[str, int]:
"""Returns:
home.zoom: pin keys kind:id to a whole percent from 50 to 200 in
steps of 10; anything else raises ToolError.
"""
low, high, step = ZOOM
if not isinstance(value, dict) or not all(isinstance(key, str) and PIN_KEY.fullmatch(key) for key in value):
raise ToolError("home.zoom must map pin keys kind:id to a percent")
if not all(not isinstance(zoom, bool) and isinstance(zoom, int) and low <= zoom <= high and zoom % step == 0 for zoom in value.values()):
raise ToolError(f"home.zoom must hold whole percents from {low} to {high} in steps of {step}")
return dict(value)
def shown_panels(value: object) -> list[str]:
"""Returns:
resources.panels: the distinct Resources panels shown, at least
one; anything else raises ToolError.
"""
panels = members(value, "resources.panels", "panels", PANELS)
if not panels:
raise ToolError("resources.panels must show at least one panel")
return panels
def legend_flags(value: object, name: str, known: Callable[[str], object], what: str) -> dict[str, bool]:
"""Args:
value: a map of legend owners to whether their legend shows.
@@ -168,7 +194,7 @@ def valid_view(raw: object) -> dict:
Returns:
The document with every key of VIEW and nothing else; any other
key, a missing one or a malformed value raises ToolError. The
legend state of a tile whose pin left Home is dropped.
legend state and zoom of a tile whose pin left Home are dropped.
"""
data = section(raw, "view", tuple(VIEW))
resources = section(data["resources"], "resources", tuple(VIEW["resources"]))
@@ -188,11 +214,11 @@ def valid_view(raw: object) -> dict:
"resources": {
"hidden": series_ids(resources["hidden"], "resources.hidden"),
"tokens": resources["tokens"],
"combined": flag(resources["combined"], "resources.combined"),
"panels": shown_panels(resources["panels"]),
"combinedHidden": series_ids(resources["combinedHidden"], "resources.combinedHidden"),
},
"burn": {"overlays": members(burn["overlays"], "burn.overlays", "metrics", OVERLAYS)},
"home": {"pins": pinned},
"home": {"pins": pinned, "zoom": {key: zoom for key, zoom in zooms(home["zoom"]).items() if key in keys}},
"kanban": {"hidden": members(kanban["hidden"], "kanban.hidden", "layers", KANBAN_LAYERS)},
"legend": {
"views": legend_flags(legend["views"], "legend.views", LEGEND_PANELS.__contains__, f"panels of {', '.join(LEGEND_PANELS)}"),
@@ -204,10 +230,20 @@ def valid_view(raw: object) -> dict:
def upgraded(raw: object) -> object:
"""Returns:
A stored document of an older hub with each VIEW section it lacks
at its default; anything else as it is.
A stored document of an older hub with each VIEW section, and each
key of a section, it lacks at its default, and resources.combined,
which resources.panels replaced, turned into the panels it showed;
anything else as it is.
"""
return {**copy.deepcopy(VIEW), **raw} if isinstance(raw, dict) else raw
if not isinstance(raw, dict):
return raw
resources = raw.get("resources")
if isinstance(resources, dict) and "combined" in resources and "panels" not in resources:
combined = resources["combined"] is True
kept = {key: value for key, value in resources.items() if key != "combined"}
raw = {**raw, "resources": {**kept, "panels": ["combined", "accounts"] if combined else list(VIEW["resources"]["panels"])}}
merged = {**copy.deepcopy(VIEW), **raw}
return {name: {**copy.deepcopy(VIEW[name]), **value} if name in VIEW and isinstance(value, dict) else value for name, value in merged.items()}
def slot(view: dict, path: object) -> tuple[dict, str]: