feat(orchestrator): hub requirements 066 to 082 and 084

Radio footer, rules page, schedules editor (System timers and Claude
tasks through signed runner jobs), account usage bar, usage explorer
with a streamed usage.jsonl, queue Controls tab and override, running
tasks on the board, stale task prune with the generic dial, greyed card
stamps, commit-tree diffs from the runner preview, VS Code path links,
expired asks and decisions that stay as EXPIRED cards (asks keyed by a
call digest; an async PostToolUse hook closes those answered in the
terminal), the Match refresh hourglass, attachments by paste, drop and
paperclip in every text field (page CSP gains img-src blob: for the
thumbnails) and the limits board with profiles and a passkey to loosen.
Fixes: one red accept on a red-gate commit and no release while a risk
is open, the send bar footer segments share one height, the mic button
survives a redraw, new Match cards queue before the release card.

E2E specs were still running at commit time (operator order); their
failures follow as separate fixes.

🎯 Fix: 88 %
💥 Break: 8 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 81
🚦 Gate: ⛔ fix 88 % < 90, break 8 % > 5 (committed on the operator's word)

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-27 19:05:38 +00:00
1 parent dc0d578eca
commit f356083a24
149 files changed
+10646 -963

No files matched your search

+42 -5
View File
@@ -7,7 +7,9 @@
--approvers: the pinned passkeys, e.g. ~/.config/kvb-orchestrator/approvers.json.
--replay: this hook's replay store, outside the hub's reach, e.g.
~/.local/state/kvb-orchestrator-approvals/hook.json.
stdin: the Claude Code PermissionRequest hook input.
stdin: the Claude Code PermissionRequest hook input, or the PostToolUse
input of a call that ran, which report_ran() tells the hub and which
prints nothing.
Returns:
stdout: the PermissionRequest decision JSON: allow only when a pinned
@@ -70,6 +72,8 @@ QUESTION_TOOL = "AskUserQuestion"
SHELL = "Bash"
SHELL_KEYS = frozenset({"command", "description", "timeout", "run_in_background"})
OPTION_KEYS = ("label", "description", "preview")
RAN_EVENT = "PostToolUse"
RAN_TIMEOUT = 2.0
def summary(tool: str, tool_input: object) -> str:
@@ -196,11 +200,41 @@ def encoded(payload: dict) -> bytes:
return json.dumps(payload).encode()
def create(base: str, ask: dict, timeout: float, shown: dict) -> str:
data = encoded({**ask, "timeout": timeout, **shown})
def call_key_of(hook: dict) -> str:
"""Returns:
signing.call_key() of the hook input's tool_name and tool_input, the
same for the PermissionRequest and the PostToolUse input of one call;
empty when they cannot be encoded, so the ask goes without it and
never becomes an expired Match card.
"""
try:
return signing.call_key(hook.get("tool_name"), hook.get("tool_input"))
except (TypeError, ValueError):
return ""
def report_ran(base: str, hook: dict) -> None:
"""Args:
hook: the PostToolUse input of a call that ran; the hub closes the
oldest still pending ask of that session and call_key_of() as
answered in the terminal. The report approves and denies nothing.
"""
key, session = call_key_of(hook), str(hook.get("session_id") or "")
if not key or not session or len(session) > NAME_LIMIT:
return
request = urllib.request.Request(f"{base}/api/asks/ran", data=encoded({"call_key": key, "session": session}), headers={"Content-Type": "application/json", **hub_api.GUARD}, method="POST")
hub_api.call(request, RAN_TIMEOUT)
def create(base: str, ask: dict, timeout: float, shown: dict, key: str) -> str:
"""Args:
key: the call's call_key_of(), sent only when not empty.
"""
called = {"call_key": key} if key else {}
data = encoded({**ask, "timeout": timeout, **called, **shown})
if len(data) > hub_limits.DIFF_BODY_LIMIT:
print(f"kvb-orchestrator: the ask goes without its diff, its {len(data)} bytes pass the hub's {hub_limits.DIFF_BODY_LIMIT}", file=sys.stderr)
data = encoded({**ask, "timeout": timeout})
data = encoded({**ask, "timeout": timeout, **called})
headers = {"Content-Type": "application/json", **hub_api.GUARD}
request = urllib.request.Request(f"{base}/api/asks", data=data, headers=headers, method="POST")
ask_id = hub_api.call(request, hub_api.SLACK)["id"]
@@ -350,6 +384,9 @@ def main() -> int:
deadline = time.monotonic() + args.timeout
try:
hook = json.load(sys.stdin)
if hook.get("hook_event_name") == RAN_EVENT:
report_ran(base, hook)
return 0
questions = asked_questions(hook)
if questions is not None:
chosen = answers_of(base, hook, questions, args.timeout, trust, deadline)
@@ -365,7 +402,7 @@ def main() -> int:
print(f"kvb-orchestrator: {WORKTREE}", file=sys.stderr)
return 0
pinned, shown = commit_diff(ask, staged_diff.rules_root())
ask_id = create(base, ask, args.timeout, shown)
ask_id = create(base, ask, args.timeout, shown, call_key_of(hook))
answer = {"status": "pending"}
while answer["status"] == "pending" and (left := deadline - time.monotonic()) > 0:
answer = status(base, ask_id, min(left, POLL))
+120
View File
@@ -0,0 +1,120 @@
from __future__ import annotations
import datetime
import re
import signing
ANNOUNCE = "announce"
APPLY = "prune"
TASKS_LIMIT = 50
WINDOW_MIN = 60
SKEW = 300
SENDER = "Operator"
RECORDS = ("operator/", "hotfix/")
DAYS = re.compile(r"[1-9][0-9]{0,2}")
EPOCH = re.compile(r"[1-9][0-9]{9}")
def whole(value: object) -> bool:
return isinstance(value, int) and not isinstance(value, bool)
def checked_tasks(tasks: list[str]) -> list[str]:
"""Returns:
tasks: 1 to TASKS_LIMIT distinct register slugs signing.TASK matches,
none an operator/ or hotfix/ record.
Raises:
signing.Refused for any other list.
"""
if not 1 <= len(tasks) <= TASKS_LIMIT or len(set(tasks)) != len(tasks):
raise signing.Refused(f"a prune names 1 to {TASKS_LIMIT} distinct tasks")
if not all(signing.TASK.fullmatch(task) and not task.startswith(RECORDS) for task in tasks):
raise signing.Refused("a pruned task is no register task slug outside operator/ and hotfix/")
return tasks
def announced(argv: list[str]) -> bool:
return len(argv) >= 6 and argv[0] == ANNOUNCE and argv[1] == "--days" and argv[3] == "--deadline" and bool(DAYS.fullmatch(argv[2]) and EPOCH.fullmatch(argv[4]))
def applied(argv: list[str], not_before: object) -> bool:
if len(argv) < 4 or argv[:2] != [APPLY, "--since"] or not EPOCH.fullmatch(argv[2]) or not whole(not_before):
return False
return WINDOW_MIN <= not_before - int(argv[2]) <= signing.PRUNE_WINDOW
def prune_argv(argv: object, not_before: object) -> list[str]:
"""Args:
argv: the announce job's `announce --days <N> --deadline <epoch>
<task>...` (N 1 to 999 DAYS, an EPOCH) with not_before None, or
the apply job's rasci.py arguments `prune --since <epoch>
<task>...` with not_before the deadline, WINDOW_MIN to
signing.PRUNE_WINDOW seconds after since; the tasks as
checked_tasks() takes them.
not_before: the epoch the runner holds the job back until, signed
with it.
Returns:
argv, the hub and the runner check it the same way.
Raises:
signing.Refused for every other argv or not_before.
"""
if not isinstance(argv, list) or not all(isinstance(part, str) for part in argv):
raise signing.Refused("the argv is no list of texts")
if not_before is None and announced(argv):
checked_tasks(argv[5:])
return argv
if applied(argv, not_before):
checked_tasks(argv[3:])
return argv
raise signing.Refused(f"the argv is no prune announce with --days and --deadline, nor rasci.py prune --since with a deadline {WINDOW_MIN} to {signing.PRUNE_WINDOW} s later")
def prune_item(argv: list[str], not_before: int | None) -> dict:
item = {"kind": signing.PRUNE_KIND, "argv": argv}
return item if not_before is None else {**item, "not_before": not_before}
def tasks_of(argv: list[str]) -> list[str]:
return argv[5:] if argv[0] == ANNOUNCE else argv[3:]
def deadline_of(argv: list[str]) -> int:
return int(argv[4])
def timely(argv: list[str], not_before: int | None, now: float) -> None:
"""Raises:
signing.Refused for an announce whose deadline passed or lies over
signing.PRUNE_WINDOW + SKEW seconds ahead, and for an apply job
before its not_before.
"""
if not_before is not None and not_before > now:
raise signing.Refused(f"the prune is not due before {stamp(not_before)}")
if not_before is None and not now < deadline_of(argv) <= now + signing.PRUNE_WINDOW + SKEW:
raise signing.Refused(f"the prune deadline {stamp(deadline_of(argv))} passed or lies over {signing.PRUNE_WINDOW} s ahead")
def stamp(epoch: int) -> str:
return datetime.datetime.fromtimestamp(epoch).astimezone().isoformat(timespec="seconds")
def announcement(argv: list[str]) -> str:
"""Returns:
The Securite text of an announce argv: every task, the deadline in
local HH:MM and ISO 8601, and how an agent keeps a task.
"""
deadline = datetime.datetime.fromtimestamp(deadline_of(argv)).astimezone()
names = ", ".join(tasks_of(argv))
return (
f"Stale task prune at {deadline:%H:%M} ({deadline.isoformat(timespec='seconds')}): {names}. "
f"Each had no register change for {argv[2]} days; at the deadline the hub runner sets every one still unchanged to stopped. "
"Keep a task with rasci.py keep <task>; any register change of it keeps it too."
)
def radio_argv(argv: list[str]) -> list[str]:
return ["send", "security", announcement(argv), "--session", SENDER]
+157 -91
View File
@@ -33,14 +33,32 @@
is the name the council claim of the session carries, else the
session id's first 8 characters; account is the email the
SessionStart hook mapped the session to in the council's
session-accounts.jsonl, left out for an unmapped session. A message counts once by its message id and
request id, also when written over several lines or copied into a
fork's transcript. <state>/offsets.json holds {files: {path: offset},
seen: {hour: [key digest]}}, seen keeping the hours this run read and
the last two, and is replaced only when it changes. In the first
minute of an hour, rows of the same hour, agent and model merge and
the rows of a day that ended more than 90 days ago fold into one row
per day, agent and model with width: 86400, kept forever.
session-accounts.jsonl, left out for an unmapped session. The same
tokens go to <state>/usage.jsonl as those rows plus skill?, tool?,
subagent? and repo?: skill the last Skill call of the session (main
thread and sidechains) before the message; tool the sorted,
comma-joined tool names of the message; subagent the agentType of a
sidechain transcript's agent-<id>.meta.json; repo the base name of
the git top-level of the message's cwd; a tag is left out while ""
(none, the main thread, text only). Per usage row t and width each of
agent, model, account and the tags keeps its 50 values of the most
tokens and folds the rest into "(other)". A message counts once by
its message id and request id, also when written over several lines
(its tools joined over the lines one run reads) or copied into a
fork's transcript. Only names and counts are stored, never prompt
text, tool inputs or outputs. <state>/context.jsonl gets per day and
agent {t, agent, turns: {kilo: count}, compactions}: the main thread's
context per turn (input plus cache read) in thousands of tokens,
rounded down, and its compact boundaries. <state>/offsets.json holds
{files: {path: offset}, seen: {hour: [key digest]}, skills?: {session:
[[t, skill]]}}, seen keeping the hours this run read and the last two,
skills the calls from the last two hours and the one before, and is
replaced only when it changes. In the first minute of an hour, token
rows of the same hour, agent and model merge and the rows of a day
that ended more than 90 days ago fold into one row per day, agent and
model with width: 86400, kept forever; usage.jsonl is rewritten line
by line the same way by usage_tags.trimmed(); context rows merge per
day and agent.
--state: the directory of these files, the unit passes
~/.local/state/agents-council/resources.
--council: the council directory with queue.json and the claims.
@@ -74,15 +92,15 @@ import stat
import subprocess
import sys
import time
from collections.abc import Callable
from collections.abc import Callable, Iterator
from pathlib import Path
import queue_live
import usage_tags as tags
from usage_tags import COUNTS, DAY, HOUR, NAMES, add, token_rows
INTERVAL = 60
BUCKET = 900
HOUR = 3600
DAY = 86400
FINE = 7 * DAY
COARSE = 90 * DAY
COMMAND_SECONDS = 10
@@ -95,12 +113,13 @@ NVIDIA = "0x10de"
DISPLAY = "0x03"
NVIDIA_QUERY = "pci.bus_id,utilization.gpu,memory.used,memory.total"
UNREAD = {"util": None, "vram_used": None, "vram_total": None}
COUNTS = (("input", "input_tokens"), ("output", "output_tokens"), ("cache_read", "cache_read_input_tokens"), ("cache_write", "cache_creation_input_tokens"))
NAMES = tuple(name for name, _ in COUNTS)
HOST_DIGITS = (("cpu", 1), ("ram", 1), ("swap", 1), ("load", 2), ("psi_some", 2), ("psi_full", 2), ("swap_out_mb_min", 1))
CLAIMS = ("*/claim.json", "*/*/claim.json")
SAMPLES = "samples.jsonl"
TOKENS = "tokens.jsonl"
CONTEXT = "context.jsonl"
USAGE = "usage.jsonl"
COMPACTION = "compact"
SESSION_ACCOUNTS = "session-accounts.jsonl"
EMAIL_CHARS = 254
OFFSETS = "offsets.json"
@@ -609,6 +628,34 @@ def replace(path: Path, text: str) -> None:
os.close(parent)
def stream_rewrite(path: Path, produce: Callable[[Iterator[bytes]], Iterator[str]]) -> None:
"""Args:
path: the file, read line by line without following a link and
replaced through a fresh temp file beside it, so its size meets
no read limit; a missing file stays missing, a link at its
directory or a file that is not regular raises OSError.
produce: the new file's lines from the old file's lines.
"""
parent = folder(path)
temp = f".{path.name}.{os.urandom(8).hex()}"
try:
try:
source = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=parent)
except FileNotFoundError:
return
with open(source, "rb") as old, open(os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, 0o600, dir_fd=parent), "w", encoding="utf-8") as new:
if not stat.S_ISREG(os.fstat(old.fileno()).st_mode):
raise OSError(errno.EINVAL, "not a regular file", str(path))
new.writelines(produce(old))
os.replace(temp, path.name, src_dir_fd=parent, dst_dir_fd=parent)
except BaseException:
with contextlib.suppress(OSError):
os.unlink(temp, dir_fd=parent)
raise
finally:
os.close(parent)
def rewrite(path: Path, keep: Callable[[list[dict], float], list[dict]], now: float) -> None:
rows = read_rows(path)
kept = keep(rows, now)
@@ -661,18 +708,27 @@ def count(value: object) -> int:
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
def assistant(raw: bytes) -> tuple[dict, dict, dict] | None:
"""Returns:
(row, message, usage) of an assistant transcript line whose message
carries a usage map and whose row a session id, else None.
"""
def parsed(raw: bytes) -> dict | None:
try:
row = json.loads(raw)
except (ValueError, RecursionError):
return None
message = row.get("message") if isinstance(row, dict) and row.get("type") == "assistant" else None
return row if isinstance(row, dict) and isinstance(row.get("sessionId"), str) else None
def turn_of(row: dict) -> tags.Turn | None:
"""Returns:
The turn of an assistant transcript line whose message carries a
usage map and a model and whose row a time, else None; of the
message only its id, model, usage and tool names are kept.
"""
message = row.get("message") if row.get("type") == "assistant" else None
fields = message.get("usage") if isinstance(message, dict) else None
return (row, message, fields) if isinstance(fields, dict) and isinstance(row.get("sessionId"), str) else None
ts = epoch(row.get("timestamp"))
if not isinstance(fields, dict) or ts is None or not isinstance(message.get("model"), str):
return None
counts = tuple(count(fields.get(field)) for _, field in COUNTS)
return tags.Turn(message_key(message.get("id"), row.get("requestId")), ts, row["sessionId"], message["model"], counts, tags.tool_names(message), row.get("isSidechain") is True, string_of(row.get("cwd")))
def message_key(ident: object, request: object) -> str:
@@ -685,22 +741,6 @@ def message_key(ident: object, request: object) -> str:
return base64.urlsafe_b64encode(hashlib.blake2b(text.encode("utf-8"), digest_size=KEY_BYTES).digest()).decode("ascii")
def usage(raw: bytes) -> tuple[str, float, str, str, tuple[int, ...]] | None:
"""Returns:
(message key, time, session, model, counts in COUNTS order) of an
assistant transcript line with a usage field, a time and a model,
else None.
"""
found = assistant(raw)
if found is None:
return None
row, message, fields = found
ts, model = epoch(row.get("timestamp")), message.get("model")
if ts is None or not isinstance(model, str):
return None
return message_key(message.get("id"), row.get("requestId")), ts, row["sessionId"], model, tuple(count(fields.get(field)) for _, field in COUNTS)
def first_sight(key: str, ts: float, seen: dict[int, set[str]], keys: dict[int, set[str]]) -> bool:
"""Returns:
Whether the message key at ts is in neither seen nor keys at its hour
@@ -716,13 +756,39 @@ def first_sight(key: str, ts: float, seen: dict[int, set[str]], keys: dict[int,
return not known
def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tuple[int, list[tuple[float, str, str, tuple[int, ...]]], dict[int, set[str]]]:
def take(row: dict, found: tags.Read, turns: dict[str, tags.Turn], seen: dict[int, set[str]], keys: dict[int, set[str]]) -> None:
"""Args:
row: one parsed transcript line.
found: gets its first-seen turn, its skill calls and its compaction.
turns: this scan's turns by message key; a later line of the same
message adds its tool names to the turn.
seen: the keys of earlier runs and files per hour.
keys: the keys this scan read per hour.
"""
if tags.is_compaction(row):
ts = epoch(row.get("timestamp"))
if ts is not None and first_sight(message_key(row.get("uuid"), COMPACTION), ts, seen, keys):
found.compactions.append((row["sessionId"], ts))
return
turn = turn_of(row)
if turn is None:
return
found.skills += [(turn.session, turn.ts, name) for name in tags.skill_calls(row["message"])]
if turn.key and turn.key in turns:
turns[turn.key].tools |= turn.tools
elif first_sight(turn.key, turn.ts, seen, keys) and any(turn.counts):
found.turns.append(turn)
turns[turn.key] = turn
def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tuple[int, tags.Read, dict[int, set[str]]]:
"""Returns:
The offset after the last complete line read from start, at most
about budget bytes on, the usage of every message seen holds no key
of, and per hour the keys of every message read.
about budget bytes on, what take() found in the lines, and per hour
the keys of every message read.
"""
found = []
found = tags.Read()
turns: dict[str, tags.Turn] = {}
keys: dict[int, set[str]] = {}
position = start
with path.open("rb") as handle:
@@ -731,27 +797,12 @@ def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tupl
if not raw.endswith(b"\n") or position - start >= budget:
break
position += len(raw)
read = usage(raw) if b'"usage"' in raw else None
if read is not None and first_sight(read[0], read[1], seen, keys) and any(read[4]):
found.append(read[1:])
row = parsed(raw) if b'"usage"' in raw or tags.COMPACT in raw else None
if row is not None:
take(row, found, turns, seen, keys)
return position, found, keys
def token_rows(sums: dict[tuple, list[int]]) -> list[dict]:
"""Args:
sums: per (t, agent, model, width, account) the counts in COUNTS
order, account "" for a session the hook mapped to none.
Returns:
One token row per key in key order; a row other than hourly names
its width, a row of a mapped session its account.
"""
return [
{"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width}), **({"account": account} if account else {})}
for (t, agent, model, width, account), counts in sorted(sums.items())
]
def token_key(row: dict, line: float) -> tuple:
"""Returns:
(t, agent, model, width, account) of the row a token row merges
@@ -765,12 +816,6 @@ def token_key(row: dict, line: float) -> tuple:
return row["t"], row["agent"], row["model"], HOUR, account
def add(sums: dict[tuple, list[int]], key: tuple, counts: tuple[int, ...]) -> None:
total = sums.setdefault(key, [0] * len(COUNTS))
for index, value in enumerate(counts):
total[index] += value
def compact(rows: list[dict], now: float) -> list[dict]:
"""Returns:
The token rows merged per token_key(), every day that ended more than
@@ -789,15 +834,15 @@ def start_of(entry: object, info: os.stat_result, now: float) -> int:
return info.st_size if info.st_mtime < now - COARSE else 0
def read_transcript(path: Path, entry: object, budget: int, now: float, seen: dict[int, set[str]]) -> tuple[int, int, list, dict[int, set[str]]]:
def read_transcript(path: Path, entry: object, budget: int, now: float, seen: dict[int, set[str]]) -> tuple[int, int, tags.Read, dict[int, set[str]]]:
"""Returns:
(start, end, usages, keys per hour) of path read from the offset
(start, end, read, keys per hour) of path read from the offset
entry records, without reading once budget is spent.
"""
info = path.stat()
start = start_of(entry, info, now)
if budget <= 0 or start >= info.st_size:
return start, start, [], {}
return start, start, tags.Read(), {}
return start, *scan(path, start, budget, seen)
@@ -807,44 +852,65 @@ def seen_of(value: object) -> dict[int, set[str]]:
return {int(hour): {key for key in keys if isinstance(key, str)} for hour, keys in value.items() if hour.isdigit() and isinstance(keys, list)}
def seen_floor(now: float) -> float:
return now // HOUR * HOUR - HOUR
def kept_seen(seen: dict[int, set[str]], touched: set[int], now: float) -> dict[str, list[str]]:
floor = now // HOUR * HOUR - HOUR
floor = seen_floor(now)
return {str(hour): sorted(keys) for hour, keys in sorted(seen.items()) if hour in touched or hour >= floor}
def read_all(transcripts: Path, offsets: dict, seen: dict[int, set[str]], budget: int, now: float) -> tuple[dict, set[int], tags.Read]:
"""Returns:
(files, touched, read): the offset per transcript after this run,
the hours whose keys it read, and what the transcripts held, each
sidechain turn tagged with its transcript's agent type.
"""
found = tags.Read()
files, touched = {}, set()
for path in sorted(transcripts.rglob("*.jsonl")):
key = path.relative_to(transcripts).as_posix()
try:
start, end, read, keys = read_transcript(path, offsets.get(key), budget, now, seen)
except OSError:
if key in offsets:
files[key] = offsets[key]
continue
files[key] = end
budget -= end - start
for hour, ids in keys.items():
seen.setdefault(hour, set()).update(ids)
touched.add(hour)
found.extend(read, tags.agent_type(path, read_json) if any(turn.sidechain for turn in read.turns) else "")
return files, touched, found
def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budget: int) -> list[dict]:
"""Returns:
The rows appended to <state>/tokens.jsonl by this run.
"""
stored = read_json(state / OFFSETS)
offsets = stored.get("files") if isinstance(stored, dict) and isinstance(stored.get("files"), dict) else {}
seen = seen_of(stored.get("seen") if isinstance(stored, dict) else None)
names = claim_names(council)
accounts = session_accounts(council)
sums: dict[tuple, list[int]] = {}
files, touched = {}, set()
for path in sorted(transcripts.rglob("*.jsonl")):
key = path.relative_to(transcripts).as_posix()
try:
start, end, found, keys = read_transcript(path, offsets.get(key), budget, now, seen)
except OSError:
if key in offsets:
files[key] = offsets[key]
continue
files[key] = end
budget -= end - start
for hour, read in keys.items():
seen.setdefault(hour, set()).update(read)
touched.add(hour)
for ts, session, model, counts in found:
add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR, accounts.get(session, "")), counts)
rows = token_rows(sums)
kept_before = stored if isinstance(stored, dict) else {}
offsets = kept_before.get("files") if isinstance(kept_before.get("files"), dict) else {}
seen = seen_of(kept_before.get("seen"))
files, touched, found = read_all(transcripts, offsets, seen, budget, now)
history = tags.history_of(kept_before.get("skills"))
tags.add_calls(history, found.skills)
names, accounts = claim_names(council), session_accounts(council)
sums, context = tags.tally(found, history, lambda session: names.get(session) or session[:8], lambda session: accounts.get(session, ""))
rows = token_rows(tags.untagged(sums))
append_rows(state / TOKENS, rows)
kept = {"files": files, "seen": kept_seen(seen, touched, now)}
append_rows(state / USAGE, token_rows(tags.fold(sums)))
append_rows(state / CONTEXT, tags.context_rows(context))
skills = tags.kept_history(history, seen_floor(now), now - COARSE)
kept = {"files": files, "seen": kept_seen(seen, touched, now), **({"skills": skills} if skills else {})}
if kept != stored:
replace(state / OFFSETS, json.dumps(kept, sort_keys=True, separators=(",", ":")))
if now % HOUR < INTERVAL:
rewrite(state / TOKENS, compact, now)
stream_rewrite(state / USAGE, functools.partial(tags.trimmed, now=now, line=now - COARSE))
rewrite(state / CONTEXT, tags.compact_context, now)
return rows
+264 -19
View File
@@ -15,6 +15,15 @@
--gates: the installed gates script, e.g.
~/.claude/skills/kvb-check-gate/scripts/gates.py; optional, gate
changes need it.
--queue: the installed queue script, e.g.
~/.agents/skills/kvb-org-queue/scripts/queue.py; optional, queue
changes need it and --council.
--schedules: the installed schedules script, e.g.
~/.claude/skills/kvb-org-organize/scripts/schedules.py; optional,
schedule changes need it and --council.
--radio: the installed radio script, e.g.
~/.claude/skills/kvb-org-radio/scripts/radio.py; optional, stale
task prunes need it, --rasci and --council.
--operator: the installed operator script, e.g.
~/.claude/skills/kvb-org-operator/scripts/operator.py; optional,
without it no row closes done after exit 0.
@@ -38,15 +47,38 @@ Returns:
refuses a cycle or a done with an open key result, and its reason is the
job's output. Runs every signed gate change (rule set|drop, parents
add|drop) the same way as `python3 -I -B <gates> <argv>` with the
operator's HOME, so gates.py writes its default gates.db. Refuses task
operator's HOME, so gates.py writes its default gates.db. Runs every
signed queue change (`override <id>` or `config set <key> <value>`,
signing.queue_argv()) the same way as `python3 -I -B <queue> <argv>`
with the operator's HOME and the council, so queue.py marks the entry
in its queue and writes the operator's queue config. Runs every
signed schedule change of a System timer or a Claude task
(`timer <unit> ...` or `cron <file> <id> ...`,
signing.schedule_argv()) the same way as
`python3 -I -B <schedules> <argv>` with the operator's HOME and the
council, so schedules.py writes the timer's drop-in or the task's cron
and refreshes schedules-view.json. Runs a signed stale task prune
(pruning.prune_argv()) as two jobs of one signature: the announce job
as `python3 -I -B <radio> send security <text> --session Operator`,
naming every task and the deadline, and the apply job as
`python3 -I -B <rasci> prune --since <epoch> <task>...`; every job
whose not_before lies ahead stays queued, unclaimed, until a later
cycle. Refuses task
changes without --rasci and --council or into a council that is a
symlink or another uid's, gate changes without --gates, and every other
job. Posts the last 200 output lines
symlink or another uid's, gate changes without --gates, queue changes
without --queue and --council or into such a council, schedule changes
without --schedules and --council or into such a council, prunes
without --radio, --rasci and --council or into such a council, and every
other job. Posts the last 200 output lines
back while it runs and the exit code at its end. Before a poll, at most
every PREVIEW_SECONDS, it posts, for each open operator row that is a git merge of a full commit
id (staged_diff.merge_of) whose HEAD differs from the preview the hub
holds, staged_diff.merge_preview, which its Match card shows; such a
merge whose job names the previewed HEAD is refused once HEAD moved.
For each open operator row and each pending Bash ask that shipped no
diff that is a git commit-tree with a parent (staged_diff.commit_tree_of)
and has no preview of that parent at the hub, it posts
staged_diff.commit_tree_preview, or the git error line that kept it.
At start, before its first cycle, it removes a leftover runner-job.json
and posts /api/runner/restart once, so the hub fails every job an
earlier runner left running; a failed post is printed to stderr. While
@@ -80,6 +112,7 @@ from typing import NamedTuple
import hub_api
import hub_limits
import pruning
import signing
import staged_diff
import verifier
@@ -92,14 +125,21 @@ ERROR_LIMIT = 500
PREVIEW_FAILURES = (OSError, ValueError, staged_diff.DiffError)
BEAT = 2.0
PREVIEW_SECONDS = 10.0
TREE_KIND = "commit-tree"
SAFE_PATH = "/usr/bin:/bin"
TASK_JOB = "task"
TASK_LIMIT = 30.0
GATE_JOB = "gate"
QUEUE_JOB = "queue"
SCHEDULE_JOB = "schedule"
PRUNE_JOB = signing.PRUNE_KIND
OPERATOR = "operator/"
REFUSED = "refused: no valid operator signature for this command"
UNREGISTERED = "refused: this runner was started without --rasci and --council; reinstall its unit with make orchestrator-runner"
UNGATED = "refused: this runner was started without --gates; reinstall its unit with make orchestrator-runner"
UNQUEUED = "refused: this runner was started without --queue and --council; reinstall its unit with make orchestrator-runner"
UNSCHEDULED = "refused: this runner was started without --schedules and --council; reinstall its unit with make orchestrator-runner"
UNPRUNED = "refused: this runner was started without --radio, --rasci and --council; reinstall its unit with make orchestrator-runner"
class Register(NamedTuple):
@@ -107,6 +147,14 @@ class Register(NamedTuple):
council: Path
class Scripts(NamedTuple):
register: Register | None
gates: Path | None
queue: Path | None
schedules: Path | None
radio: Path | None
class Host(NamedTuple):
shell: str
operator: Path | None
@@ -176,14 +224,86 @@ def gate_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None:
Why the change must not run, or None when signing.gate_argv()
accepts its argv and a pinned key signed it.
"""
return argv_refusal(job, trust, now, signing.gate_argv, signing.gate_item)
def argv_refusal(job: dict, trust: verifier.Trust, now: float, shape: Callable[[object], list[str]],
item: Callable[[list[str]], dict]) -> str | None:
"""Args:
job: the claimed change with argv and proof.
trust: the pinned keys, the runner's replay store and the origin.
now: the current time in epoch seconds.
shape: the signing check of its argv, raising signing.Refused.
item: the signed item of that argv.
Returns:
Why the change must not run, or None when shape accepts its argv
and a pinned key signed its item.
"""
try:
argv = signing.gate_argv(job["argv"])
verifier.check(job.get("proof"), signing.gate_item(argv), "", trust, now)
argv = shape(job["argv"])
verifier.check(job.get("proof"), item(argv), "", trust, now)
except (signing.Refused, OSError) as error:
return f"{REFUSED}: {error}"
return None
def queue_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None:
"""Args:
job: the claimed queue change with argv and proof.
trust: the pinned keys, the runner's replay store and the origin.
now: the current time in epoch seconds.
Returns:
Why the change must not run, or None when signing.queue_argv()
accepts its argv and a pinned key signed it.
"""
return argv_refusal(job, trust, now, signing.queue_argv, signing.queue_item)
def schedule_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None:
"""Args:
job: the claimed schedule change with argv and proof.
trust: the pinned keys, the runner's replay store and the origin.
now: the current time in epoch seconds.
Returns:
Why the change must not run, or None when signing.schedule_argv()
accepts its argv and a pinned key signed it.
"""
return argv_refusal(job, trust, now, signing.schedule_argv, signing.schedule_item)
def prune_refusal(job: dict, trust: verifier.Trust, now: float) -> str | None:
"""Args:
job: the claimed prune job with argv, not_before and proof.
trust: the pinned keys, the runner's replay store and the origin.
now: the current time in epoch seconds.
Returns:
Why the job must not run, or None when pruning.prune_argv() accepts
its argv with its not_before, it is due (pruning.timely()) and a
pinned key signed its item, not_before included.
"""
try:
not_before = job.get("not_before")
argv = pruning.prune_argv(job["argv"], not_before)
pruning.timely(argv, not_before, now)
verifier.check(job.get("proof"), pruning.prune_item(argv, not_before), "", trust, now)
except (signing.Refused, OSError) as error:
return f"{REFUSED}: {error}"
return None
def not_due(job: dict, now: float) -> bool:
"""Returns:
Whether a listed job carries a not_before after now; the cycle
leaves it queued and unclaimed until then instead of waiting on it.
"""
not_before = job.get("not_before")
return pruning.whole(not_before) and not_before > now
def moved(job: dict) -> str | None:
"""Args:
job: a claimed operator command; head, when set, is the HEAD its
@@ -212,11 +332,14 @@ def preview(row: dict, rules: Path | None) -> dict | None:
Returns:
The preview to post for a git merge row whose HEAD differs from the
hub's: staged_diff.merge_preview, or {head, error} when it cannot be
built; None for every other row.
built; for a git commit-tree row, with kind TREE_KIND,
tree_preview() once head is not its parent; None for every other
row.
"""
found = staged_diff.merge_of(row["command"], row["directory"])
if found is None:
return None
tree = staged_diff.commit_tree_of(row["command"], row["directory"])
return None if tree is None or tree[2] == row["head"] else {"task": row["task"], "command": row["command"], "kind": TREE_KIND, **tree_preview(tree, rules)}
try:
head = staged_diff.head_of(found[0])
except PREVIEW_FAILURES as error:
@@ -233,6 +356,36 @@ def preview(row: dict, rules: Path | None) -> dict | None:
return {"task": row["task"], "command": row["command"], "head": head, **shown}
def tree_preview(found: tuple[Path, str, str], rules: Path | None) -> dict:
"""Args:
found: the directory, tree and parent staged_diff.commit_tree_of
read from a git commit-tree.
rules: the MEDUSA rules directory.
Returns:
staged_diff.commit_tree_preview, or {head, error} with the parent
as head and the git error line that kept it.
"""
try:
return staged_diff.commit_tree_preview(*found, rules)
except PREVIEW_FAILURES as error:
return {"head": found[2], "error": str(error)[:ERROR_LIMIT]}
def ask_preview(ask: dict, rules: Path | None) -> dict | None:
"""Args:
ask: a pending Bash ask that shipped no diff, with id, command, cwd
and head, the parent of the preview the hub holds, None for none.
rules: the MEDUSA rules directory.
Returns:
{ask, ...tree_preview()} for a git commit-tree with a parent whose
preview the hub lacks; None for every other ask.
"""
found = staged_diff.commit_tree_of(ask["command"], ask["cwd"])
return None if found is None or found[2] == ask["head"] else {"ask": ask["id"], **tree_preview(found, rules)}
def review_preview(row: dict, rules: Path | None) -> dict | None:
"""Args:
row: a pending review that shipped no diff, with id, worktree, tree
@@ -271,11 +424,15 @@ def previews(base: str, rules: Path | None) -> None:
for row in listed["rows"]:
shown = preview(row, rules)
if shown is not None:
call(base, PREVIEWS, oversized(shown, ("task", "command", "head")))
call(base, PREVIEWS, oversized(shown, tuple(key for key in ("task", "command", "kind", "head") if key in shown)))
for row in listed["reviews"]:
shown = review_preview(row, rules)
if shown is not None:
call(base, PREVIEWS, oversized(shown, ("id", "head")))
for ask in listed["asks"]:
shown = ask_preview(ask, rules)
if shown is not None:
call(base, PREVIEWS, oversized(shown, ("ask", "head")))
def council_refusal(council: Path) -> str | None:
@@ -371,6 +528,77 @@ def gate(job: dict, gates: Path, report: Callable[[dict], None]) -> int:
return spawn([sys.executable, "-I", "-B", str(gates), *argv], "/", env, report, TASK_LIMIT)
def queue(job: dict, scripts: Scripts, report: Callable[[dict], None]) -> int:
"""Args:
job: the claimed and verified queue change with argv.
scripts: the runner's scripts; queue and the register's council set.
report: called with {"output", "code", "refused"}.
Returns:
The exit code of queue.py, run from / on the argv queue_argv()
checked, with the operator's HOME and the council as its
AGENTS_COUNCIL_ROOT.
Raises:
signing.Refused for an argv of any other shape.
"""
return council_script(scripts.queue, signing.queue_argv(job["argv"]), scripts, report)
def schedule(job: dict, scripts: Scripts, report: Callable[[dict], None]) -> int:
"""Args:
job: the claimed and verified schedule change with argv.
scripts: the runner's scripts; schedules and the register's council
set.
report: called with {"output", "code", "refused"}.
Returns:
The exit code of schedules.py, run from / on the argv
schedule_argv() checked, with the operator's HOME and the council as
its AGENTS_COUNCIL_ROOT.
Raises:
signing.Refused for an argv of any other shape.
"""
return council_script(scripts.schedules, signing.schedule_argv(job["argv"]), scripts, report)
def prune(job: dict, scripts: Scripts, report: Callable[[dict], None]) -> int:
"""Args:
job: the claimed and verified prune job with argv and not_before.
scripts: the runner's scripts; radio and the register set.
report: called with {"output", "code", "refused"}.
Returns:
The exit code of radio.py sending the announcement for the announce
job, else of rasci.py prune on the apply job's argv.
Raises:
signing.Refused for an argv of any other shape.
"""
not_before = job.get("not_before")
argv = pruning.prune_argv(job["argv"], not_before)
if not_before is None:
return council_script(scripts.radio, pruning.radio_argv(argv), scripts, report)
return council_script(scripts.register.rasci, argv, scripts, report)
def council_script(script: Path, argv: list[str], scripts: Scripts, report: Callable[[dict], None]) -> int:
"""Args:
script: the skill script to run.
argv: its arguments, already checked against their signing shape.
scripts: the runner's scripts; the register's council set.
report: called with {"output", "code", "refused"}.
Returns:
The exit code of `python3 -I -B <script> <argv>`, run from / without
a shell with the operator's HOME and the council as its
AGENTS_COUNCIL_ROOT, killed after TASK_LIMIT seconds.
"""
env = {"PATH": SAFE_PATH, "HOME": str(Path.home()), "AGENTS_COUNCIL_ROOT": str(scripts.register.council)}
return spawn([sys.executable, "-I", "-B", str(script), *argv], "/", env, report, TASK_LIMIT)
def spawn(argv: list[str], cwd: str, env: dict[str, str] | None, report: Callable[[dict], None], limit: float | None = None) -> int:
"""Args:
argv: the program and its arguments, run without a shell.
@@ -451,38 +679,52 @@ def mark(marker: Path, job: dict) -> str | None:
return None
def refused(claimed: dict, trust: verifier.Trust, register: Register | None, gates: Path | None) -> str | None:
kind = claimed.get("kind")
def refused(claimed: dict, trust: verifier.Trust, scripts: Scripts) -> str | None:
kind, register = claimed.get("kind"), scripts.register
if kind == TASK_JOB:
return UNREGISTERED if register is None else council_refusal(register.council) or task_refusal(claimed, trust, time.time())
if kind == GATE_JOB:
return UNGATED if gates is None else gate_refusal(claimed, trust, time.time())
return UNGATED if scripts.gates is None else gate_refusal(claimed, trust, time.time())
if kind == QUEUE_JOB:
return UNQUEUED if scripts.queue is None or register is None else council_refusal(register.council) or queue_refusal(claimed, trust, time.time())
if kind == SCHEDULE_JOB:
return UNSCHEDULED if scripts.schedules is None or register is None else council_refusal(register.council) or schedule_refusal(claimed, trust, time.time())
if kind == PRUNE_JOB:
return UNPRUNED if scripts.radio is None or register is None else council_refusal(register.council) or prune_refusal(claimed, trust, time.time())
return refusal(claimed, trust, time.time()) or moved(claimed)
def run(claimed: dict, register: Register | None, gates: Path | None, host: Host, send: Callable[[dict], None]) -> None:
def run(claimed: dict, scripts: Scripts, host: Host, send: Callable[[dict], None]) -> None:
kind = claimed.get("kind")
if kind == TASK_JOB:
change(claimed, register, send)
change(claimed, scripts.register, send)
elif kind == GATE_JOB:
gate(claimed, gates, send)
gate(claimed, scripts.gates, send)
elif kind == QUEUE_JOB:
queue(claimed, scripts, send)
elif kind == SCHEDULE_JOB:
schedule(claimed, scripts, send)
elif kind == PRUNE_JOB:
prune(claimed, scripts, send)
else:
execute(claimed, host, send)
def cycle(base: str, trust: verifier.Trust, register: Register | None, gates: Path | None, host: Host) -> None:
def cycle(base: str, trust: verifier.Trust, scripts: Scripts, host: Host) -> None:
for job in call(base, "/api/runner/jobs", None)["jobs"]:
if not_due(job, time.time()):
continue
try:
claimed = call(base, f"/api/runner/{job['id']}/claim", {})
except urllib.error.HTTPError:
continue
send = sender(base, claimed["id"])
reason = refused(claimed, trust, register, gates) or mark(host.marker, claimed)
reason = refused(claimed, trust, scripts) or mark(host.marker, claimed)
if reason is not None:
send({"output": reason, "code": None, "refused": True})
continue
try:
run(claimed, register, gates, host, send)
run(claimed, scripts, host, send)
finally:
host.marker.unlink(missing_ok=True)
@@ -519,12 +761,15 @@ def main() -> int:
parser.add_argument("--rasci", type=Path)
parser.add_argument("--council", type=Path)
parser.add_argument("--gates", type=Path)
parser.add_argument("--queue", type=Path)
parser.add_argument("--schedules", type=Path)
parser.add_argument("--radio", type=Path)
parser.add_argument("--operator", type=Path)
parser.add_argument("--once", action="store_true")
args = parser.parse_args()
base = hub_api.base_url(args.port)
trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port))
register = Register(rasci=args.rasci, council=args.council) if args.rasci and args.council else None
scripts = Scripts(register=Register(rasci=args.rasci, council=args.council) if args.rasci and args.council else None, gates=args.gates, queue=args.queue, schedules=args.schedules, radio=args.radio)
host = Host(shell=os.environ.get("SHELL") or pwd.getpwuid(os.geteuid()).pw_shell, operator=args.operator, council=args.council, marker=args.state / MARKER)
rules, told, previewed = staged_diff.rules_root(), "", None
restart(base, host.marker)
@@ -533,7 +778,7 @@ def main() -> int:
previewed = time.monotonic()
told = post_previews(base, rules, told)
try:
cycle(base, trust, register, args.gates, host)
cycle(base, trust, scripts, host)
except (OSError, ValueError, KeyError, TypeError):
pass
if args.once:
+114 -2
View File
@@ -14,6 +14,9 @@ VERSION = 1
LIFETIME = 900
REVIEW_LIFETIME = 7200
RULE_LIFETIME = 366 * 86400
PRUNE_KIND = "prune"
PRUNE_WINDOW = 3600
PRUNE_LIFETIME = LIFETIME + PRUNE_WINDOW
ALGORITHMS = {-7: "ES256", -8: "EdDSA", -257: "RS256"}
HASH = re.compile(r"[0-9a-f]{64}")
NONCE = re.compile(r"[0-9a-f]{32}")
@@ -39,6 +42,18 @@ GATE_LEVELS = ("none", "quick", "test", "quality-high", "e2e")
GATE_ACTIONS = ("commit", "merge", "push", "pr")
GATE_REPO = re.compile(r"/[^\x00-\x1f\x7f]{0,4095}")
GATE_BRANCH = re.compile(r"(?![-/])(?!.*\.\.)(?!.*@\{)(?!.*//)[^\x00-\x20\x7f~^:?*\[\\]{1,255}(?<![/.])")
QUEUE_KIND = re.compile(r"[a-z0-9][a-z0-9_-]{0,63}")
QUEUE_ID = re.compile(r"[a-z0-9][a-z0-9_-]{0,63}-[0-9]{1,12}")
QUEUE_VALUE = re.compile(r"(0|[1-9][0-9]{0,5})(\.[0-9]{1,3})?")
QUEUE_SETTINGS = {"budget_percent": ("ram", "cpu"), "load_limits": ("cpu_percent", "mem_percent", "sample_seconds", "band_low", "band_high"), "slot_limits": None, "ram_cap_percent": None}
SCHEDULE_UNIT = re.compile(r"(?!kvb-orchestrator-)[A-Za-z0-9][A-Za-z0-9_.@:\\-]{0,200}\.timer")
SCHEDULE_CLOCK = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]")
SCHEDULE_CALENDAR = re.compile(r"(?![ -])[A-Za-z0-9*:,./~_+ -]{1,128}(?<! )")
SCHEDULE_TIMES = 6
SCHEDULE_SWITCHES = (["--on"], ["--off"], ["--reset"])
TASK_FILE = re.compile(r"/[^\x00-\x1f\x7f]{1,4000}/\.claude/scheduled_tasks\.json")
TASK_ID = re.compile(r"[A-Za-z0-9_-]{1,64}")
CRON = re.compile(r"[0-9*,/-]{1,64}(?: [0-9*,/-]{1,64}){4}")
TOKEN_FREE_MERGE = "ancestor"
LOCAL_DELETE = ["local-branch"]
APPROVAL_KEYS = {"v", "kind", "items", "nonce", "expires"}
@@ -96,6 +111,19 @@ def canonical(value: object) -> bytes:
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False).encode("ascii")
def call_key(tool_name: object, tool_input: object) -> str:
"""Args:
tool_name: the hook input's tool_name.
tool_input: the hook input's tool_input.
Returns:
The sha256 hex digest of the canonical JSON of both: the key the
PermissionRequest hook gives an ask and the PostToolUse hook gives the
call that ran, as neither input carries a shared call id.
"""
return hashlib.sha256(canonical({"tool_name": tool_name, "tool_input": tool_input})).hexdigest()
def challenge(payload: dict) -> str:
return b64encode(hashlib.sha256(canonical(payload)).digest())
@@ -234,6 +262,10 @@ def popups_item(popups: dict) -> dict:
return {"kind": "popups", "popups": popups}
def limits_item(limits: dict) -> dict:
return {"kind": "limits", "limits": limits}
def task_item(task: str, argv: list[str]) -> dict:
return {"kind": "task", "id": task, "argv": argv}
@@ -317,6 +349,82 @@ def gate_argv(argv: object) -> list[str]:
return argv
def queue_item(argv: list[str]) -> dict:
return {"kind": "queue", "argv": argv}
def queue_argv(argv: object) -> list[str]:
"""Args:
argv: the queue.py arguments, `override <id>` with an id QUEUE_ID
matches, or `config set <key> <value>` with a key of
QUEUE_SETTINGS (`<section>.<name>`, a kind QUEUE_KIND matches
for a section mapped to None) and a value QUEUE_VALUE matches.
Returns:
argv, the hub and the runner check it the same way; queue.py checks
the value against the config itself.
Raises:
Refused for every other argv.
"""
if not isinstance(argv, list) or not all(isinstance(part, str) for part in argv):
raise Refused("the argv is no list of texts")
if len(argv) == 2 and argv[0] == "override" and QUEUE_ID.fullmatch(argv[1]):
return argv
if len(argv) != 4 or argv[:2] != ["config", "set"] or not QUEUE_VALUE.fullmatch(argv[3]):
raise Refused("the argv is no queue.py override <id> or config set <key> <value> with a plain number")
section, _, name = argv[2].partition(".")
names = QUEUE_SETTINGS.get(section, ())
if not (QUEUE_KIND.fullmatch(name) if names is None else name in names):
raise Refused(f"{argv[2]} is no queue setting the hub may change")
return argv
def schedule_item(argv: list[str]) -> dict:
return {"kind": "schedule", "argv": argv}
def timer_change(rest: list[str]) -> bool:
if rest in SCHEDULE_SWITCHES:
return True
if len(rest) == 2 and rest[0] == "--calendar":
return bool(SCHEDULE_CALENDAR.fullmatch(rest[1]))
times = rest[1:]
return rest[:1] == ["--at"] and 1 <= len(times) <= SCHEDULE_TIMES and len(set(times)) == len(times) and all(SCHEDULE_CLOCK.fullmatch(item) for item in times)
def task_file(path: str) -> bool:
return bool(TASK_FILE.fullmatch(path)) and "/../" not in path and "/./" not in path and "//" not in path
def schedule_argv(argv: object) -> list[str]:
"""Args:
argv: the schedules.py arguments of one foreign row: `timer <unit>`
(a user timer SCHEDULE_UNIT matches, never a kvb-orchestrator-
one) with exactly one of `--on`, `--off`, `--reset`,
`--calendar <expr>` (SCHEDULE_CALENDAR) or `--at <HH:MM> ...`
(1 to SCHEDULE_TIMES distinct times), or `cron <file> <id>`
(an absolute .claude/scheduled_tasks.json, a TASK_ID) with
`--cron <5 fields>` (CRON) or `--remove`.
Returns:
argv, the hub and the runner check it the same way; schedules.py
validates the calendar with systemd-analyze and accepts only the
task files it lists itself.
Raises:
Refused for every other argv.
"""
if not isinstance(argv, list) or not all(isinstance(part, str) for part in argv):
raise Refused("the argv is no list of texts")
if len(argv) >= 3 and argv[0] == "timer" and SCHEDULE_UNIT.fullmatch(argv[1]) and timer_change(argv[2:]):
return argv
rest = argv[3:]
if len(argv) >= 4 and argv[0] == "cron" and task_file(argv[1]) and TASK_ID.fullmatch(argv[2]) and (rest == ["--remove"] or (len(rest) == 2 and rest[0] == "--cron" and CRON.fullmatch(rest[1]))):
return argv
raise Refused("the argv is no schedules.py timer <unit> change or cron <file> <id> change of a foreign row")
def names_default(ref: object, default: object) -> bool:
"""Args:
ref: a ref as pkgmgr names it, bare such as main or behind one
@@ -775,9 +883,13 @@ def lifetime(items: list[dict]) -> int:
How long an approval of items may live: REVIEW_LIFETIME when every
item is a review, whose approval names one exact tree and is used
once at the commit, so a commit row may run well after the clicks;
LIFETIME for any other mix.
PRUNE_LIFETIME when every item is a stale task prune, whose apply
job waits for its deadline up to PRUNE_WINDOW seconds; LIFETIME for
any other mix.
"""
return REVIEW_LIFETIME if items and all(item.get("kind") == "review" for item in items) else LIFETIME
if items and all(item.get("kind") == "review" for item in items):
return REVIEW_LIFETIME
return PRUNE_LIFETIME if items and all(item.get("kind") == PRUNE_KIND for item in items) else LIFETIME
def checked_approval(payload: object, now: float, cap: int) -> dict:
+24 -2
View File
@@ -43,6 +43,9 @@ Returns:
tree_of: (directory, tree, parents) of a single git commit-tree whose
tree and parents are full object ids, which no later write can
change; None for any other command.
commit_tree_of: (directory, tree, parent) of a tree_of command with at
least one parent, the first one; None without -p.
commit_tree_preview: what git diff <parent> <tree> shows for it.
merge_of: (directory, target) of a single git merge of one full object
id; merge_preview: what that merge brings in; head_of: the commit
HEAD names.
@@ -51,8 +54,8 @@ Returns:
Every git call runs GIT with core.fsmonitor, core.hooksPath, lazy fetching,
the system and the global config off, and an environment of only PASSED_ENV
and FIXED_ENV (PATH set to TRUSTED_PATH). The permission hook and runner path
(binding, bound_diff, commit_tree_diff, merge_preview, head_of, commit_of,
tree_of, merge_of) runs only plumbing that writes nothing (rev-parse,
(binding, bound_diff, commit_tree_diff, merge_preview, commit_tree_preview,
head_of, commit_of, tree_of, commit_tree_of, merge_of) runs only plumbing that writes nothing (rev-parse,
merge-base, symbolic-ref, ls-tree, ls-files, cat-file); only approval.py, run
inside the sandbox, adds git write-tree. The diff itself is computed here:
the permission hook and the runner call this outside the sandbox in a directory the agent
@@ -551,6 +554,20 @@ def merge_preview(cwd: Path, target: str, rules: Path | None) -> dict:
return {"head": head, "base": base, "target": target, "diff": commit_tree_diff(top, tree, [base], rules)[0]}
def commit_tree_preview(cwd: Path, tree: str, parent: str, rules: Path | None) -> dict:
"""Returns:
{head, base, target, diff}: what git diff <parent> <tree> shows, the
tree against the parent's tree, secrets masked; head and base are
the parent, target the tree. A parent or tree the repository lacks
fails with git's own error line; neither git diff nor commit-tree
runs, so no repository config can start a diff driver.
"""
top = toplevel(cwd)
for oid in (parent, tree):
git(top, ["cat-file", "-t", oid], None)
return {"head": parent, "base": parent, "target": tree, "diff": commit_tree_diff(top, tree, [parent], rules)[0]}
def fetched(cwd: Path, old: dict, new: dict, changed: list[str], contents: dict[str, bytes | None]) -> None:
needed = {side[path][1] for side in (old, new) for path in changed if path in side and side[path][0] != GITLINK and side[path][1] not in contents}
sizes = blob_sizes(cwd, needed)
@@ -627,6 +644,11 @@ def tree_of(command: str, cwd: str) -> tuple[Path, str, list[str]] | None:
return None if named is None else (found[0], *named)
def commit_tree_of(command: str, cwd: str) -> tuple[Path, str, str] | None:
found = tree_of(command, cwd)
return None if found is None or not found[2] else (found[0], found[1], found[2][0])
def merge_of(command: str, cwd: str) -> tuple[Path, str] | None:
"""Returns:
The directory and target of one git merge, behind what commit_of
+376
View File
@@ -0,0 +1,376 @@
"""Returns:
The helpers resources.py tokens tags each assistant message's usage with
(skill, tool, subagent, repo) and counts the context per turn and the
compactions of <state>/context.jsonl with; only names and counts leave a
transcript, never prompt text, tool inputs or outputs. Nothing here
writes a file or calls a language model.
"""
from __future__ import annotations
import bisect
import dataclasses
import json
import os
import re
from collections.abc import Callable, Iterable, Iterator
from pathlib import Path
HOUR = 3600
DAY = 86400
TAGS = ("skill", "tool", "subagent", "repo")
COUNTS = (("input", "input_tokens"), ("output", "output_tokens"), ("cache_read", "cache_read_input_tokens"), ("cache_write", "cache_creation_input_tokens"))
NAMES = tuple(name for name, _ in COUNTS)
USAGE_OPEN = 2 * DAY
OTHER = "(other)"
UNTYPED = "(untyped)"
FOLD_LIMIT = 50
FOLDED = (1, 2, 4, 5, 6, 7, 8)
KILO = 1000
CONTEXT_PARTS = (0, 2)
COMPACT = b"compact_boundary"
TOOL_BLOCKS = ("tool_use", "server_tool_use")
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:+-]{0,63}")
AGENT_FILE = "agent-"
META = ".meta.json"
@dataclasses.dataclass
class Turn:
key: str
ts: float
session: str
model: str
counts: tuple[int, ...]
tools: set[str]
sidechain: bool
cwd: str
subagent: str = ""
@dataclasses.dataclass
class Read:
turns: list[Turn] = dataclasses.field(default_factory=list)
skills: list[tuple[str, float, str]] = dataclasses.field(default_factory=list)
compactions: list[tuple[str, float]] = dataclasses.field(default_factory=list)
def extend(self, other: Read, subagent: str) -> None:
"""Args:
other: one transcript's read.
subagent: the agent type of that transcript, given to its
sidechain turns only.
"""
for turn in other.turns:
turn.subagent = subagent if turn.sidechain else ""
self.turns += other.turns
self.skills += other.skills
self.compactions += other.compactions
def named(value: object) -> str:
"""Returns:
value when it is a name of at most 64 letters, digits and _.:+-
starting with a letter or digit, else "".
"""
return value if isinstance(value, str) and NAME.fullmatch(value) else ""
def blocks(message: dict) -> list[dict]:
content = message.get("content")
return [block for block in content if isinstance(block, dict)] if isinstance(content, list) else []
def tool_names(message: dict) -> set[str]:
return {name for block in blocks(message) if block.get("type") in TOOL_BLOCKS and (name := named(block.get("name")))}
def skill_calls(message: dict) -> list[str]:
"""Returns:
The skill name of every Skill tool_use block in message; only the
input's skill field is read, never its args.
"""
found = []
for block in blocks(message):
given = block.get("input") if block.get("type") == "tool_use" and block.get("name") == "Skill" else None
name = named(given.get("skill")) if isinstance(given, dict) else ""
if name:
found.append(name)
return found
def is_compaction(row: dict) -> bool:
# Claude Code writes one {"type": "system", "subtype": "compact_boundary"} line per compaction, followed by a user line with isCompactSummary; only the boundary counts, so a compaction is not counted twice.
return row.get("type") == "system" and row.get("subtype") == "compact_boundary" and row.get("isSidechain") is not True
def agent_type(path: Path, read_json: Callable[[Path], object]) -> str:
"""Args:
path: a transcript; a sidechain one is <session>/subagents/agent-<id>.jsonl.
read_json: the sampler's capped JSON reader, called with the
transcript's agent-<id>.meta.json.
Returns:
The agentType that meta file names, UNTYPED without one; only that
field is read.
"""
if not path.name.startswith(AGENT_FILE):
return UNTYPED
data = read_json(path.with_name(path.name.removesuffix(".jsonl") + META))
return (named(data.get("agentType")) if isinstance(data, dict) else "") or UNTYPED
def top_level(cwd: str) -> str:
"""Returns:
The base name of the nearest directory at or above cwd that holds a
.git entry, "" for none or a relative cwd.
"""
if not cwd.startswith("/"):
return ""
# A removed worktree's cwd no longer exists, so the walk reaches the enclosing checkout, if any, and names that.
path = Path(cwd)
for folder in (path, *path.parents):
if os.path.lexists(folder / ".git"):
return named(folder.name)
return ""
def repo_of(cwd: str, cache: dict[str, str]) -> str:
if cwd not in cache:
cache[cwd] = top_level(cwd)
return cache[cwd]
def add(sums: dict[tuple, list[int]], key: tuple, counts: tuple[int, ...] | list[int]) -> None:
total = sums.setdefault(key, [0] * len(counts))
for index, value in enumerate(counts):
total[index] += value
def kept_values(values: dict[str, int]) -> set[str]:
ranked = sorted((value for value in values if value != OTHER), key=lambda value: (-values[value], value))
return {OTHER, *ranked[:FOLD_LIMIT]}
def fold_position(sums: dict[tuple, list[int]], position: int) -> dict[tuple, list[int]]:
totals: dict[tuple, dict[str, int]] = {}
for key, counts in sums.items():
bucket = totals.setdefault((key[0], key[3]), {})
bucket[key[position]] = bucket.get(key[position], 0) + sum(counts)
kept = {bucket: kept_values(values) for bucket, values in totals.items()}
found: dict[tuple, list[int]] = {}
for key, counts in sums.items():
value = key[position] if key[position] in kept[(key[0], key[3])] else OTHER
add(found, (*key[:position], value, *key[position + 1:]), counts)
return found
def fold(sums: dict[tuple, list[int]]) -> dict[tuple, list[int]]:
"""Args:
sums: per (t, agent, model, width, account, skill, tool, subagent,
repo) the counts.
Returns:
sums with every dimension of FOLDED bounded per row (t, width): its
FOLD_LIMIT values of the most tokens kept, ties by name, the others
merged into OTHER.
"""
for position in FOLDED:
sums = fold_position(sums, position)
return sums
def untagged(sums: dict[tuple, list[int]]) -> dict[tuple, list[int]]:
"""Returns:
sums merged per (t, agent, model, width, account), the key of a
tokens.jsonl row, unfolded.
"""
found: dict[tuple, list[int]] = {}
for key, counts in sums.items():
add(found, key[:5], counts)
return found
def token_rows(sums: dict[tuple, list[int]]) -> list[dict]:
"""Args:
sums: per (t, agent, model, width, account, *tags) the counts in
COUNTS order, account "" for a session the hook mapped to none,
tags in TAGS order or left out.
Returns:
One row per key in key order; a row other than hourly names its
width, a row of a mapped session its account, a row its tags but
those that are "".
"""
return [
{
"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width}), **({"account": account} if account else {}),
**{name: value for name, value in zip(TAGS, tagged, strict=False) if value},
}
for (t, agent, model, width, account, *tagged), counts in sorted(sums.items())
]
def usage_row(raw: bytes) -> dict | None:
try:
row = json.loads(raw)
except (ValueError, RecursionError):
return None
if not isinstance(row, dict) or not isinstance(row.get("agent"), str) or not isinstance(row.get("model"), str):
return None
return row if isinstance(row.get("t"), int | float) and not isinstance(row["t"], bool) else None
def usage_key(row: dict, line: float) -> tuple:
"""Returns:
(t, agent, model, width, account, *tags) of the usage row a row
merges into: its day (UTC) when that day ended by line, else its
hour.
"""
day = int(row["t"] // DAY * DAY)
account = row["account"] if isinstance(row.get("account"), str) else ""
start, width = (day, DAY) if day + DAY <= line else (int(row["t"]), HOUR)
return start, row["agent"], row["model"], width, account, *row_tags(row)
def trimmed(lines: Iterable[bytes], now: float, line: float) -> Iterator[str]:
"""Args:
lines: the lines of usage.jsonl, read one at a time.
now: epoch seconds of this run.
line: a day that ended by it folds into one row per day and
dimensions, kept forever.
Returns:
The lines of the trimmed file: a daily row, and an hourly row older
than USAGE_OPEN whose day ended after line, unchanged and in order,
as an earlier run already merged it; the rows of the last USAGE_OPEN
and those of a day that ended by line merged per usage_key(),
folded, after them. Only those rows stay in memory; a malformed line
is dropped.
"""
sums: dict[tuple, list[int]] = {}
for raw in lines:
row = usage_row(raw)
if row is None:
continue
settled = row["t"] < now - USAGE_OPEN and int(row["t"] // DAY * DAY) + DAY > line
if row.get("width") == DAY or settled:
yield raw.decode("utf-8", "replace").rstrip("\n") + "\n"
else:
add(sums, usage_key(row, line), tuple(whole(row.get(name)) for name in NAMES))
for row in token_rows(fold(sums)):
yield json.dumps(row, separators=(",", ":")) + "\n"
def row_tags(row: dict) -> tuple[str, ...]:
"""Returns:
The TAGS of a token row, "" for each one an older row lacks.
"""
return tuple(row[name] if isinstance(row.get(name), str) else "" for name in TAGS)
def history_of(value: object) -> dict[str, list[tuple[float, str]]]:
"""Returns:
Per session its skill calls [(time, name)] in time order from the
skills map offsets.json keeps; a malformed entry is dropped.
"""
if not isinstance(value, dict):
return {}
found = {}
for session, calls in value.items():
kept = sorted((float(call[0]), call[1]) for call in calls if isinstance(call, list) and len(call) == 2 and isinstance(call[0], int | float) and not isinstance(call[0], bool) and named(call[1])) if isinstance(calls, list) else []
if isinstance(session, str) and kept:
found[session] = kept
return found
def add_calls(history: dict[str, list[tuple[float, str]]], calls: list[tuple[str, float, str]]) -> None:
for session, ts, name in calls:
history.setdefault(session, []).append((ts, name))
for session in {session for session, _, _ in calls}:
history[session] = sorted(set(history[session]))
def skill_at(history: dict[str, list[tuple[float, str]]], session: str, ts: float) -> str:
"""Returns:
The name of the last skill call of session strictly before ts, ""
before any.
"""
calls = history.get(session, [])
index = bisect.bisect_left(calls, (ts, "")) - 1
return calls[index][1] if index >= 0 else ""
def kept_history(history: dict[str, list[tuple[float, str]]], floor: float, oldest: float) -> dict[str, list[list]]:
"""Returns:
The skills map offsets.json keeps: per session its calls from floor
on and the last one before it; a session whose last call lies before
oldest is dropped.
"""
kept = {}
for session, calls in sorted(history.items()):
if calls[-1][0] < oldest:
continue
start = max(bisect.bisect_left(calls, (floor, "")) - 1, 0)
kept[session] = [[ts, name] for ts, name in calls[start:]]
return kept
def tally(read: Read, history: dict[str, list[tuple[float, str]]], agent_of: Callable[[str], str], account_of: Callable[[str], str]) -> tuple[dict[tuple, list[int]], dict[tuple, list]]:
"""Args:
read: the turns, skill calls and compactions of this run.
history: per session its skill calls, those of read included.
agent_of: a session's agent name.
account_of: a session's account email, "" for none.
Returns:
(sums, context): per (hour, agent, model, HOUR, account, skill,
tool, subagent, repo) the counts in the sampler's COUNTS order, tool
the sorted, comma-joined tool names of the turn; per (day, agent) a
histogram of the main thread's context per turn (input plus cache
read, at CONTEXT_PARTS of the counts) in KILO tokens and its
compactions.
"""
sums: dict[tuple, list[int]] = {}
context: dict[tuple, list] = {}
repos: dict[str, str] = {}
for turn in read.turns:
agent = agent_of(turn.session)
tags = (skill_at(history, turn.session, turn.ts), ",".join(sorted(turn.tools)), turn.subagent, repo_of(turn.cwd, repos))
add(sums, (int(turn.ts // HOUR * HOUR), agent, turn.model, HOUR, account_of(turn.session), *tags), turn.counts)
if not turn.sidechain:
sizes = context.setdefault((int(turn.ts // DAY * DAY), agent), [{}, 0])[0]
size = sum(turn.counts[index] for index in CONTEXT_PARTS) // KILO
sizes[size] = sizes.get(size, 0) + 1
for session, ts in read.compactions:
context.setdefault((int(ts // DAY * DAY), agent_of(session)), [{}, 0])[1] += 1
return sums, context
def context_rows(context: dict[tuple, list]) -> list[dict]:
"""Returns:
One context row {t, agent, turns: {kilo: count}, compactions} per
(day, agent) in key order.
"""
return [{"t": t, "agent": agent, "turns": {str(kilo): turns[kilo] for kilo in sorted(turns)}, "compactions": compactions} for (t, agent), (turns, compactions) in sorted(context.items())]
def whole(value: object) -> int:
return value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
def compact_context(rows: list[dict], _now: float) -> list[dict]:
"""Returns:
The context rows merged per day and agent, kept forever like the
daily token rows; a malformed row is dropped.
"""
context: dict[tuple, list] = {}
for row in rows:
t, agent, turns = row.get("t"), row.get("agent"), row.get("turns")
if not whole(t) or not isinstance(agent, str) or not isinstance(turns, dict):
continue
entry = context.setdefault((t, agent), [{}, 0])
for kilo, number in turns.items():
if isinstance(kilo, str) and kilo.isdigit() and whole(number):
entry[0][int(kilo)] = entry[0].get(int(kilo), 0) + number
entry[1] += whole(row.get("compactions"))
return context_rows(context)
+20 -2
View File
@@ -262,6 +262,11 @@ def consume(store: Path, key: str, expires: int, credential: str, count: int, no
count: its signature counter; 0 when the authenticator keeps none.
nonce: the payload nonce; one bulk signature carries one counter.
now: the current time in epoch seconds.
An assertion the store accepted once (its nonce, credential and count
under "seen" until expires) passes the counter check for its other
items later too: a prune's apply job uses its approval at the deadline,
after other signatures moved the counter on.
"""
store.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
descriptor = os.open(store.with_name(f"{store.name}.lock"), os.O_RDWR | os.O_CREAT, 0o600)
@@ -271,14 +276,27 @@ def consume(store: Path, key: str, expires: int, credential: str, count: int, no
used = {name: until for name, until in state["used"].items() if isinstance(until, int | float) and until > now}
if key in used:
raise Refused("this signature was already used for this item")
seen, mark = live_seen(state.get("seen"), now), {"credential": credential, "count": count, "until": expires}
last = state["counts"].get(credential)
if last is not None and not (count > last["count"] or (count == last["count"] and (count == 0 or nonce == last["nonce"]))):
fresh = last is None or count > last["count"] or (count == last["count"] and (count == 0 or nonce == last["nonce"]))
if not fresh and seen.get(nonce) != mark:
raise Refused("the signature counter did not grow: a cloned authenticator or a replay")
write_private(store, {"used": {**used, key: expires}, "counts": {**state["counts"], credential: {"count": count, "nonce": nonce}}})
counts = {**state["counts"], credential: {"count": count, "nonce": nonce}} if fresh else state["counts"]
write_private(store, {"used": {**used, key: expires}, "counts": counts, "seen": {**seen, nonce: mark}})
finally:
os.close(descriptor)
def live_seen(raw: object, now: float) -> dict[str, dict]:
"""Returns:
The "seen" entries of the replay store whose until lies after now;
none for a store written before them.
"""
if not isinstance(raw, dict):
return {}
return {nonce: entry for nonce, entry in raw.items() if isinstance(entry, dict) and isinstance(entry.get("until"), int | float) and entry["until"] > now}
def check(proof: object, item: dict, gate: str, trust: Trust, now: float) -> None:
"""Args:
proof: {"payload", "assertion"} the Agent Orchestrator relayed for the item.