feat: hub and skills requirements 032 to 063

Hub: send in the field (032), coherent speak box (033), stream head band (034), Match at full width with its pile (035, 036), Home without the outer box (037), badge to Match (038), rejects that survive a changed or withdrawn card (039), the release card (040), code marks in the review diff (041), why Deny is off (042), the undo window clock (043), widgets without inner boxes (044), the Artifacts head on one line (045), accepting a red gate's risk (046), one code box (047), done rows greyed and folded (048), one control height (049), menus that stay open (050), radio settings in the Device card (051), bubbles beside the modes (052), agent settings on every face and name (053), pin only by menu (054), WASD in Match (055), the flowing card edge (056), Schedules in Controls (057) and the hub poll cost (059).

Skills: the coach leaves for its own repository kevinveenbirkenbach/coach (058; test_install pins its four skills in skills-lock.json and stays red until that repository is published and pinned), hooks and timers start fewer processes (060), council files on hot paths stay bounded and mirror by marker instead of mtime (061), scripts and hooks hand agents less output (062), and block.py builds the commit table and message block in one run (063). Requirement documents 032 to 063 with their implementation amendments.

MEDUSA false positives accepted after kvb-think-criticize (36 lines): MM-SCAN-058 (pla inside replace or plan), JB-SCAN-616/641 (the local clip helper), CODEGEN-SCAN-001 (drop-in paths), CGS-SCAN-029 (systemctl argv from constants), CGS-SCAN-040 (runner poll loop), FLA-SCAN-055 (feedback), WM-SCAN-354, AI-BACKDOOR-006, GENAI-SCAN-1270, B604 (runner shell path for passkey-verified commands), TC004, EXA002, EXA006, EXA010 and WEB-SSRF.

🎯 Fix: 92 %
💥 Break: 8 %
💸 Tokens: 89 %
⏱️ Velocity: –
🛡️ Security: ~100 %
🏆 Score: 95
🚦 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:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-26 08:44:15 +00:00
1 parent e5fd70e183
commit 0fad1bfae3
265 files changed
+10434 -2242

No files matched your search

+10 -4
View File
@@ -7,11 +7,16 @@ from collections.abc import Callable
from .errors import Conflict, Missing
UNDO = 3.0
UNDO = 3
class Pending:
def __init__(self) -> None:
def __init__(self, window: Callable[[], float]) -> None:
"""Args:
window: returns the undo window in seconds the operator set, read
anew for every batch; a running batch keeps its due time.
"""
self.window = window
self.lock = threading.Lock()
self.batches: dict[str, dict] = {}
self.applied: set[str] = set()
@@ -28,9 +33,10 @@ class Pending:
The batch without its proof and timer.
"""
batch_id = secrets.token_hex(8)
timer = threading.Timer(UNDO, self.fire, args=(batch_id, apply))
window = self.window()
timer = threading.Timer(window, self.fire, args=(batch_id, apply))
timer.daemon = True
batch = {"id": batch_id, "items": items, "source": source, "due": time.time() + UNDO}
batch = {"id": batch_id, "items": items, "source": source, "due": time.time() + window}
with self.lock:
self.batches[batch_id] = {**batch, "proof": proof, "timer": timer}
timer.start()
+1 -1
View File
@@ -153,7 +153,7 @@ class Watch:
self.seen.setdefault(task, now)
if self.last is not None and self.last != tasks:
self.changes.extend(register_changes(self.last, tasks, now))
self.last = json.loads(json.dumps(tasks))
self.last = tasks
def first(self, task: str, now: float) -> float:
with self.lock:
+21 -1
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import hashlib
import json
import re
from collections.abc import Callable
@@ -15,6 +16,7 @@ GUARD = "X-Kvb-Orchestrator"
PLAIN_CSP = "default-src 'none'; frame-ancestors 'none'"
LENGTH = re.compile(r"[0-9]{1,9}")
QUERY_FIELDS = 32
TAG_LENGTH = 32
class HubServer(ThreadingHTTPServer):
@@ -46,7 +48,25 @@ class Exchange(BaseHTTPRequestHandler):
self.send(status, "text/plain; charset=utf-8", f"{message}\n".encode(), {"Content-Security-Policy": PLAIN_CSP})
def send_json(self, status: HTTPStatus, payload: dict) -> None:
self.send(status, "application/json", json.dumps(payload).encode(), {"Content-Security-Policy": PLAIN_CSP})
self.send_body(status, json.dumps(payload).encode())
def send_body(self, status: HTTPStatus, body: bytes) -> None:
self.send(status, "application/json", body, {"Content-Security-Policy": PLAIN_CSP})
def send_tagged(self, payload: dict) -> None:
"""Args:
payload: the answer; its digest is the ETag, and a request whose
If-None-Match names it gets 304 without a body.
"""
body = json.dumps(payload).encode()
tag = f'"{hashlib.sha256(body).hexdigest()[:TAG_LENGTH]}"'
if self.headers.get_all("If-None-Match") == [tag]:
self.send_response(HTTPStatus.NOT_MODIFIED)
self.send_header("ETag", tag)
self.send_header("Cache-Control", "no-store")
self.end_headers()
return
self.send(HTTPStatus.OK, "application/json", body, {"Content-Security-Policy": PLAIN_CSP, "ETag": tag})
def not_allowed(self) -> None:
self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
+6 -3
View File
@@ -81,7 +81,8 @@ FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPSta
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
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)
SCHEDULES_ROUTE = "/api/schedules"
ACTION_POSTS = (ACCOUNTS_ROUTE, SCHEDULES_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):
@@ -133,11 +134,11 @@ class Handler(Exchange):
elif proof:
self.answer(lambda: hub.review_proof(proof.group(1)), HTTPStatus.OK)
elif path == "/api/state":
self.answer(lambda: hub.window(self.query()), HTTPStatus.OK)
self.attempt(lambda: hub.window(self.query()), lambda body: self.send_body(HTTPStatus.OK, body))
elif path == "/api/stream":
self.answer(lambda: hub.stream(self.query()), HTTPStatus.OK)
elif path == "/api/events":
self.answer(lambda: hub.events(self.query()), HTTPStatus.OK)
self.attempt(lambda: hub.events(self.query()), self.send_tagged)
elif path == "/api/tree":
self.answer(hub.repositories, HTTPStatus.OK)
elif path == "/api/skills":
@@ -194,6 +195,8 @@ class Handler(Exchange):
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)
if path == SCHEDULES_ROUTE:
return lambda body: self.answer(lambda: hub.schedule_settings.save(body), HTTPStatus.OK)
reveal = REVEAL_ROUTE.fullmatch(path)
if reveal:
method = hub.sign_reveal if reveal.group(3) else hub.reveal
+4 -1
View File
@@ -53,6 +53,7 @@ from .resources import RESOURCES, SAMPLES
from .revealing import Revealing
from .reviewing import Reviewing
from .rules import Offers, Rules
from .schedules import Schedules
from .settings import Settings
from .signed import signing
from .skill_scripts import Runner
@@ -142,6 +143,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
merge_previews: Ledger
live_state: LiveState
accounts: Accounts
schedule_settings: Schedules
def hosts(self) -> tuple[str, str]:
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
@@ -211,6 +213,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
replay=state / "replay" / "messages.json",
view_store=ViewStore(state / "view.json"),
accounts=Accounts(state, places.kept, council),
schedule_settings=Schedules(council),
match_snapshots=Ledger(state / "match.json"),
merge_previews=Ledger(state / "previews.json"),
live_state=LiveState(live_ttl),
@@ -219,7 +222,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
jobs=Ledger(state / "jobs.json"),
marks=Marks(state / "marks.json"),
log=Log(state / "log.jsonl"),
batches=Pending(),
batches=Pending(lambda: settings.undo()),
names=Names(state / "names.json"),
receipt_names=ReceiptNames(state / NAMES),
receipt_reads=ReceiptReads(state / READS),
+5 -2
View File
@@ -94,7 +94,10 @@ class Jobs:
raise Missing(job_id)
if record["status"] in JOB_OPEN:
raise Conflict({"id": job_id, "status": record["status"]})
self.jobs.change(job_id, {"dismissed": True})
if record.get("kind") in CHANGES:
self.jobs.change(job_id, {"dismissed": True})
else:
self.jobs.keep(lambda job: job.get("kind") in CHANGES or job["status"] in JOB_OPEN or (job["task"] != record["task"] and job.get("dismissed") is not True))
return {"id": job_id, "dismissed": True}
def queue_job(self, item: dict, proof: dict | None) -> str:
@@ -139,7 +142,7 @@ class Jobs:
if record["status"] != "running":
raise Conflict({"id": job_id, "status": record["status"]})
if code is None and not refused:
self.jobs.change(job_id, {"output": output})
self.jobs.note(job_id, {"output": output})
return {"id": job_id, "status": "running", "code": None}
status = "refused" if refused else "done" if code == 0 else "failed"
job, changed = self.jobs.transition(job_id, "running", {"status": status, "code": code, "output": output, "finished": time.time()})
+18
View File
@@ -87,6 +87,24 @@ class Ledger:
self.write({**self.items, item_id: updated})
return dict(updated)
def note(self, item_id: str, changes: dict) -> dict | None:
"""Returns:
The record with changes applied in memory only; the next write of
any record stores them, a restart before it loses them.
"""
with self.changed:
record = self.items.get(item_id)
if record is None:
return None
self.items = {**self.items, item_id: {**record, **changes}}
return dict(self.items[item_id])
def keep(self, wanted: Callable[[dict], bool]) -> None:
with self.changed:
kept = {key: record for key, record in self.items.items() if wanted(record)}
if len(kept) != len(self.items):
self.write(kept)
def remove(self, item_id: str) -> bool:
with self.changed:
if item_id not in self.items:
+25 -4
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
import threading
import time
from collections.abc import Callable
@@ -16,19 +17,35 @@ class LiveState:
self.ttl = ttl
self.guard = threading.Lock()
self.locks: dict[object, threading.Lock] = {}
self.built: dict[object, tuple[int, float, dict]] = {}
self.built: dict[object, tuple[int, float, dict, bytes]] = {}
self.generation = 0
def invalidate(self) -> None:
with self.guard:
self.generation += 1
def slot(self, moment: float) -> float:
"""Returns:
moment rounded down to a multiple of ttl, so polls whose window
starts within one ttl share a key; moment itself for a zero ttl.
"""
return moment - moment % self.ttl if self.ttl > 0 else moment
def shared(self, key: object, build: Callable[[], dict]) -> dict:
"""Returns:
build()'s result; callers arriving while it runs wait for it and
share it, and so do callers within ttl after it, until
invalidate() is called.
"""
return self.entry(key, build)[0]
def encoded(self, key: object, build: Callable[[], dict]) -> bytes:
"""Returns:
The JSON bytes of shared(key, build), encoded once per build.
"""
return self.entry(key, build)[1]
def entry(self, key: object, build: Callable[[], dict]) -> tuple[dict, bytes]:
with self.guard:
lock = self.locks.setdefault(key, threading.Lock())
with lock:
@@ -36,8 +53,12 @@ class LiveState:
generation = self.generation
hit = self.built.get(key)
if hit is not None and hit[0] == generation and time.monotonic() - hit[1] < self.ttl:
return hit[2]
return hit[2], hit[3]
value = build()
body = json.dumps(value).encode()
with self.guard:
self.built[key] = (generation, time.monotonic(), value)
return value
at = time.monotonic()
self.built = {old: found for old, found in self.built.items() if at - found[1] < self.ttl}
self.built[key] = (generation, at, value, body)
self.locks = {old: held for old, held in self.locks.items() if old in self.built}
return value, body
+26 -7
View File
@@ -1,5 +1,7 @@
from __future__ import annotations
import os
import threading
from pathlib import Path
from .council import HUMAN, agent, ordered
@@ -12,13 +14,34 @@ REGISTER = "rasci.json"
AGENT_ORDER = "agent-order.json"
OPERATOR = "operator/"
ENDED = ("done", "stopped")
PARSED_KEPT = 8
parsed: dict[Path, tuple[tuple[int, int, int], dict[str, dict]]] = {}
parsed_lock = threading.Lock()
def read_register(path: Path) -> dict[str, dict]:
data = read_json(path)
if not isinstance(data, dict):
"""Returns:
The task rows of the register, parsed again only when its inode, size
or mtime changed; a fresh top-level dict per call whose rows are
shared between callers and read only.
"""
try:
info = os.lstat(path)
except OSError:
return {}
return {task: row for task, row in data.items() if isinstance(row, dict)}
stamp = (info.st_ino, info.st_size, info.st_mtime_ns)
with parsed_lock:
found = parsed.get(path)
if found is not None and found[0] == stamp:
return dict(found[1])
data = read_json(path)
rows = {task: row for task, row in data.items() if isinstance(row, dict)} if isinstance(data, dict) else {}
with parsed_lock:
parsed.pop(path, None)
parsed[path] = (stamp, rows)
while len(parsed) > PARSED_KEPT:
parsed.pop(next(iter(parsed)))
return dict(rows)
def status_of(row: dict) -> str:
@@ -128,10 +151,6 @@ def register_row(task: str, row: dict) -> dict:
}
def register_rows(tasks: dict[str, dict]) -> list[dict]:
return [register_row(task, row) for task, row in sorted(tasks.items(), key=pinned) if is_open(task, row, False)]
def stored_order(path: Path) -> list[str]:
data = read_json(path)
names = data.get("agents") if isinstance(data, dict) else None
+112
View File
@@ -0,0 +1,112 @@
from __future__ import annotations
import json
from pathlib import Path
from .errors import ToolError
from .fields import decode
from .records import read_json, write_atomic
from .settings import CLOCK, flag, section
SCHEDULES = "schedules.json"
SCHEDULES_VIEW = "schedules-view.json"
ROWS = {
"coach": {"on": False, "every": 1},
"dream": {"on": False, "every": 12},
"dream-popup": {"on": False, "at": ["17:00"]},
"queue-cleanup": {"on": True, "at": ["00:00", "12:00"]},
"code-graph": {"on": True},
}
HOURS = (1, 24)
TIMES_LIMIT = 6
VIEW_LIMIT = 200
VIEW_TEXT = 2000
VIEW_KEYS = ("name", "kind", "owner", "unit", "file", "schedule", "next", "last", "event", "command", "off")
def valid_row(name: object, value: object) -> dict:
"""Args:
name: one of ROWS.
value: the row: on, plus every (hours from 1 to 24) for a reminder
hook or at (1 to TIMES_LIMIT distinct HH:MM) for a timer.
Returns:
The row, times sorted.
"""
if not isinstance(name, str) or name not in ROWS:
raise ToolError(f"no such schedule: {name}")
row = section(value, str(name), tuple(ROWS[name]))
found = {"on": flag(row["on"], f"{name}.on")}
if "every" in row:
every = row["every"]
if isinstance(every, bool) or not isinstance(every, int) or not HOURS[0] <= every <= HOURS[1]:
raise ToolError(f"{name}.every must be a whole number of hours from {HOURS[0]} to {HOURS[1]}")
found["every"] = every
if "at" in row:
times = row["at"]
if not isinstance(times, list) or not 1 <= len(times) <= TIMES_LIMIT or not all(isinstance(time, str) and CLOCK.fullmatch(time) for time in times):
raise ToolError(f"{name}.at must hold 1 to {TIMES_LIMIT} times like 17:00")
if len(set(times)) != len(times):
raise ToolError(f"{name}.at names a time twice")
found["at"] = sorted(times)
return found
def stored_rows(council: Path) -> dict:
"""Returns:
Every row of ROWS from schedules.json; a missing, linked or malformed
file, or a malformed row, gives that row's default.
"""
data = read_json(council / SCHEDULES)
rows = {}
for name, default in ROWS.items():
try:
rows[name] = valid_row(name, data[name])
except (ToolError, KeyError, TypeError):
rows[name] = default
return rows
def view_rows(council: Path) -> dict:
"""Returns:
{at, rows}: what the host reconciler last saw, each row with the
VIEW_KEYS as strings or numbers; {at: None, rows: []} before its first
run or for a malformed file.
"""
data = read_json(council / SCHEDULES_VIEW)
rows = data.get("rows") if isinstance(data, dict) else None
at = data.get("at") if isinstance(data, dict) else None
if not isinstance(rows, list) or isinstance(at, bool) or not isinstance(at, int | float):
return {"at": None, "rows": []}
kept = []
for row in rows[:VIEW_LIMIT]:
if isinstance(row, dict) and isinstance(row.get("name"), str):
kept.append({key: shown(row.get(key)) for key in VIEW_KEYS})
return {"at": at, "rows": kept}
def shown(value: object) -> str | float | None:
if isinstance(value, str):
return value[:VIEW_TEXT]
if isinstance(value, int | float) and not isinstance(value, bool):
return value
return None
class Schedules:
def __init__(self, council: Path) -> None:
self.council = council
def view(self) -> dict:
return {"rows": stored_rows(self.council), "host": view_rows(self.council)}
def save(self, body: bytes) -> dict:
"""Args:
body: {row, value}: one row of ROWS and its new value; every
other row keeps its stored value.
"""
data = section(decode(body), "body", ("row", "value"))
rows = {**stored_rows(self.council), data["row"]: valid_row(data["row"], data["value"])}
self.council.mkdir(parents=True, exist_ok=True)
write_atomic(self.council / SCHEDULES, json.dumps(rows, sort_keys=True).encode())
return self.view()
+55 -1
View File
@@ -7,6 +7,7 @@ import threading
from pathlib import Path
from urllib.parse import urlsplit
from .batches import UNDO
from .errors import ToolError
from .fields import FIELDS, NAME_LIMIT, expect
from .rates import METRICS, PERIOD_NAMES
@@ -19,7 +20,13 @@ TRENDS = ("off", "regression", "velocity")
TREND_DAYS = (1, 365)
THRESHOLDS = tuple(range(0, ALWAYS + 1, 10))
WPM = (5, 40)
LATE = ("rates", "morse")
LATE = ("rates", "morse", "undo", "popups", "agents")
AGENT_SWITCHES = ("sound", "aloud", "bubbles")
AGENTS_LIMIT = 200
UNDO_RANGE = (0, 60)
POPUP_SOURCES = ("resources", "mayday", "dream")
POPUP_UNTIL = 4102444800
NOTIFY = "notify.json"
RADIO_MOVED = ("sounds", "squelch")
SPEECH_MOVED = ("on", "classes", "muted")
COLOR = re.compile(r"#[0-9a-f]{6}")
@@ -49,6 +56,9 @@ SETTINGS = {
"trend": {"mode": "off", "days": 7},
"bubbles": False,
"rates": {"period": "hour", "metrics": ["tasks", "tokens", "cpu"]},
"undo": UNDO,
"popups": {source: {"on": True, "until": 0} for source in POPUP_SOURCES},
"agents": {},
}
RATE_CHIP = (2, 9)
SPACE_AXES = ("none", "time", "spawn")
@@ -188,6 +198,43 @@ def trend_setting(raw: object) -> dict:
return {"mode": entry["mode"], "days": entry["days"]}
def undo_setting(raw: object) -> int:
low, high = UNDO_RANGE
if isinstance(raw, bool) or not isinstance(raw, int) or not low <= raw <= high:
raise ToolError(f"undo must be whole seconds from {low} to {high}")
return raw
def popups_setting(raw: object) -> dict:
data = section(raw, "popups", POPUP_SOURCES)
popups = {}
for source in POPUP_SOURCES:
entry = section(data[source], f"popups.{source}", ("on", "until"))
until = entry["until"]
if isinstance(until, bool) or not isinstance(until, int) or not 0 <= until <= POPUP_UNTIL:
raise ToolError(f"popups.{source}.until must be whole epoch seconds from 0 to {POPUP_UNTIL}")
popups[source] = {"on": flag(entry["on"], f"popups.{source}.on"), "until": until}
return popups
def agents_setting(raw: object) -> dict:
"""Returns:
Each agent key with its sound, aloud and bubbles switches; an entry
with all three on is dropped, since on is what an absent agent gets.
"""
if not isinstance(raw, dict) or len(raw) > AGENTS_LIMIT:
raise ToolError(f"agents must be an object of at most {AGENTS_LIMIT} agents")
agents = {}
for key, entry in raw.items():
if not 0 < len(key) <= NAME_LIMIT:
raise ToolError(f"agents keys must be 1 to {NAME_LIMIT} characters")
switches = section(entry, f"agents.{key}", AGENT_SWITCHES)
kept = {name: flag(switches[name], f"agents.{key}.{name}") for name in AGENT_SWITCHES}
if not all(kept.values()):
agents[key] = kept
return agents
def rates_setting(raw: object) -> dict:
entry = section(raw, "rates", tuple(SETTINGS["rates"]))
low, high = RATE_CHIP
@@ -224,6 +271,9 @@ def valid_settings(raw: object) -> dict:
"trend": trend_setting(data["trend"]),
"bubbles": flag(data["bubbles"], "bubbles"),
"rates": rates_setting(data["rates"]),
"undo": undo_setting(data["undo"]),
"popups": popups_setting(data["popups"]),
"agents": agents_setting(data["agents"]),
}
@@ -306,6 +356,10 @@ class Settings:
with self.lock:
return copy.deepcopy(self.current)
def undo(self) -> float:
with self.lock:
return float(self.current["undo"])
def put(self, raw: object, expected: dict) -> dict:
"""Args:
raw: the settings to save.
+27 -15
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import json
import time
from .asking import ask_row, decision_row
@@ -25,22 +26,21 @@ from .graph import graph
from .jobs import JOB_OPEN
from .messaging import message_row
from .orbits import TRACK_STEPS, track
from .phrasing import joined, phrase_parts
from .phrasing import phrase_parts
from .presence import presence, read_snapshot
from .queue_order import grant_order, live_ids
from .receipts import inline, read_of
from .records import epoch, iso_epoch, read_jsonl
from .records import epoch, iso_epoch, read_jsonl, write_atomic
from .register import (
AGENT_ORDER,
REGISTER,
agent_order,
operator_rows,
read_register,
register_rows,
stored_order,
)
from .reviewing import review_row
from .settings import completed, media_origins, station_origins, valid_settings
from .settings import NOTIFY, completed, media_origins, station_origins, valid_settings
from .signed import signing
from .skill_scripts import OUTPUT_LIMIT
from .tasks import queue_chain, queue_line, task_edges, task_rows
@@ -76,14 +76,21 @@ class View:
raise ToolError("from must not lie after to")
return begin, end
def window(self, query: dict[str, list[str]]) -> dict:
def window(self, query: dict[str, list[str]]) -> bytes:
"""Returns:
The encoded state of the window; a live window, one without
`to`, is shared with every poll whose `from` falls into the same
live_state slot.
"""
sampled = single(query, "track")
if sampled not in (None, "1"):
raise ToolError("track must be 1 or left out")
self.tree.beat()
if "from" in query or "to" in query:
return self.built(query, sampled)
return self.live_state.shared(sampled, lambda: self.built(query, sampled))
if "to" in query:
return json.dumps(self.built(query, sampled)).encode()
begin, _ = self.span(query, time.time())
key = (sampled, None if "from" not in query else self.live_state.slot(begin))
return self.live_state.encoded(key, lambda: self.built(query, sampled))
def built(self, query: dict[str, list[str]], sampled: str | None) -> dict:
now = time.time()
@@ -122,7 +129,7 @@ class View:
called = [directory.at(key, row["ts"]) or name for key, name in zip(targets, row["to"], strict=True)]
speaker = directory.at(source, row["ts"]) or row["from"]
word, rest = phrase_parts(row["class"], speaker, called, row["text"])
spoken = {"speech": joined((word, rest)), "word": word, "rest": rest, "voice": self.speech.voice_of(source), "pitch": pitch_of(source), **sound_of(source), "speaker": speaker, "called": called}
spoken = {"word": word, "rest": rest, "voice": self.speech.voice_of(source), "pitch": pitch_of(source), **sound_of(source), "speaker": speaker, "called": called}
read = read_of(inlined, row["ts"])
radio.append({**row, "source": source, "targets": targets, "now": directory.now(source), **spoken, **read})
grant_rows = [{**grant, "target": directory.key(grant["to"], grant["ts"])} for grant in grants(history, (begin, end), claims, tasks)]
@@ -142,6 +149,7 @@ class View:
stored = self.messages.listed()
return {
"settings": settings,
"schedules": self.schedule_settings.view(),
"media": media_origins(settings),
"speech": {**self.speech.describe(), "gate": self.speech_gate.state()},
"people": people,
@@ -165,7 +173,6 @@ class View:
"messages": [{**message_row(message), **read_of(inlined, epoch(message.get("relay_ts")))} for message in stored if begin <= message["created_ts"] <= end],
"reasons": recent_reasons(stored),
"operator": operator_rows(tasks),
"register": register_rows(tasks),
"tasks": rows,
"task_edges": task_edges(rows, chain),
"queue_line": queue_line(chain, queue),
@@ -190,14 +197,16 @@ class View:
The items the operator's passkey signs for this save: the station
origins and the new urls when the settings name a stream url the
saved ones do not, and the speech threshold when it differs from
the saved one, since the hub's speech gate enforces it. The hub
dials no url before it is signed, and resolves its redirect
targets only after the signature.
the saved one, since the hub's speech gate enforces it, and the
desktop popups when they differ, since muting one silences an
alarm outside the page. The hub dials no url before it is signed,
and resolves its redirect targets only after the signature.
"""
urls = sorted({stream["url"] for stream in settings["streams"]} - {stream["url"] for stream in saved["streams"]})
threshold = settings["speech"]["threshold"]
streams = [signing.stream_item(station_origins(settings), urls)] if urls else []
return streams + ([signing.threshold_item(threshold)] if threshold != saved["speech"]["threshold"] else [])
speech = [signing.threshold_item(threshold)] if threshold != saved["speech"]["threshold"] else []
return streams + speech + ([signing.popups_item(settings["popups"])] if settings["popups"] != saved["popups"] else [])
def resolved(self, settings: dict, saved: dict) -> tuple[dict, list[str]]:
"""Args:
@@ -258,7 +267,10 @@ class View:
for change in self.signed_changes(settings, saved):
self.operator_proven(proof, change)
resolved, problems = self.resolved(settings, saved)
return {"settings": self.settings.put(resolved, saved), "problems": problems}
stored = self.settings.put(resolved, saved)
self.council.mkdir(parents=True, exist_ok=True)
write_atomic(self.council / NOTIFY, json.dumps(stored["popups"], sort_keys=True).encode())
return {"settings": stored, "problems": problems}
def render(self, nonce: str) -> tuple[str, str]:
now = time.time()