feat(hub): requirements 023 to 031 and line comments on grant-time code
023 box heads: one head band per box under its top border; in widget mode its controls join the widget title band. 024 Match card content: merge cards show their diff (the runner previews a review's tree against its worktree HEAD), every card carries legal and architecture scores, the null under command cards is gone. 025 Radio speak card: no hint text, a rounder flowing card, a MAYDAY toggle beside push to talk. 026 widget zoom: zoom a widget's content by keyboard and the context menu. 027 slash skill suggestions: every field that messages agents suggests skills after a slash, from a skills index the tree timer writes. 028 Resources accounts: an Accounts panel (provider, renewal, resets, usage and remaining, host-local, emails never in git) and panel checkboxes. 029 Controls layout: Rules and Groups pages laid out. 030 Yes/No answers as buttons, and nothing hides: rows the runner cannot run stay greyed with the reason. 031 mic in fields. Line comments (operator 2026-11-24): wherever code waits for a grant (Waits on Operator, the stream, the review overlay) selected lines or a right-clicked row take a comment that marks its lines and collects on the card; Deny opens with them as the reason and Call preselected, Grant sends them after the signed grant as one post. Requirement 003 decision 4 and its contract follow. Tests are written for every requirement and run once on this head. 🎯 Fix: 80 % 💥 Break: 20 % 💸 Tokens: – ⏱️ Velocity: – 🛡️ Security: ~95 % 🏆 Score: 61 🚦 Gate: ⛔ fix 80 % < 90, break 20 % > 5; security ~95 % < 100: ask the operator before the commit Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7d1926e3de
commit
2722cda1b5
120 files changed
+5372
-486
No files matched your search
@@ -29,9 +29,11 @@
|
||||
tokens: add the input, output, cache-read and cache-write tokens of the
|
||||
usage fields in the Claude Code transcripts under --transcripts since
|
||||
each file's byte offset to <state>/tokens.jsonl as {t, agent, model,
|
||||
input, output, cache_read, cache_write}, t the hour; agent is the
|
||||
name the council claim of the session carries, else the session id's
|
||||
first 8 characters. A message counts once by its message id and
|
||||
input, output, cache_read, cache_write, account?}, t the hour; agent
|
||||
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
|
||||
@@ -97,6 +99,8 @@ HOST_DIGITS = (("cpu", 1), ("ram", 1), ("swap", 1), ("load", 2), ("psi_some", 2)
|
||||
CLAIMS = ("*/claim.json", "*/*/claim.json")
|
||||
SAMPLES = "samples.jsonl"
|
||||
TOKENS = "tokens.jsonl"
|
||||
SESSION_ACCOUNTS = "session-accounts.jsonl"
|
||||
EMAIL_CHARS = 254
|
||||
OFFSETS = "offsets.json"
|
||||
TICKS = "cpu.json"
|
||||
SWAPPED = "swap.json"
|
||||
@@ -115,18 +119,28 @@ def read_text(path: Path) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def read_json(path: Path) -> object:
|
||||
def read_capped(path: Path) -> str:
|
||||
"""Returns:
|
||||
The parsed JSON of path, read without following a symlink and only
|
||||
from a regular file of at most JSON_BYTES; None when that fails.
|
||||
The text of path, read without following a symlink and only from a
|
||||
regular file of at most JSON_BYTES; "" when that fails.
|
||||
"""
|
||||
try:
|
||||
with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as handle:
|
||||
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
||||
return None
|
||||
return ""
|
||||
data = handle.read(JSON_BYTES + 1)
|
||||
return None if len(data) > JSON_BYTES else json.loads(data.decode("utf-8"))
|
||||
except (OSError, ValueError, RecursionError):
|
||||
return "" if len(data) > JSON_BYTES else data.decode("utf-8")
|
||||
except (OSError, ValueError):
|
||||
return ""
|
||||
|
||||
|
||||
def read_json(path: Path) -> object:
|
||||
"""Returns:
|
||||
The parsed JSON of read_capped(path); None when that fails.
|
||||
"""
|
||||
try:
|
||||
return json.loads(read_capped(path))
|
||||
except (ValueError, RecursionError):
|
||||
return None
|
||||
|
||||
|
||||
@@ -526,8 +540,12 @@ def retain(rows: list[dict], now: float) -> list[dict]:
|
||||
|
||||
|
||||
def read_rows(path: Path) -> list[dict]:
|
||||
return json_lines(read_text(path))
|
||||
|
||||
|
||||
def json_lines(text: str) -> list[dict]:
|
||||
rows = []
|
||||
for line in read_text(path).splitlines():
|
||||
for line in text.splitlines():
|
||||
try:
|
||||
row = json.loads(line)
|
||||
except (ValueError, RecursionError):
|
||||
@@ -608,6 +626,20 @@ def claim_names(council: Path) -> dict[str, str]:
|
||||
return names
|
||||
|
||||
|
||||
def session_accounts(council: Path) -> dict[str, str]:
|
||||
"""Returns:
|
||||
Each session's account email from the lines the SessionStart hook
|
||||
appends to <council>/session-accounts.jsonl, the last one winning.
|
||||
Agents may write the file, so it is read through read_capped() and
|
||||
an email longer than EMAIL_CHARS is dropped.
|
||||
"""
|
||||
found = {}
|
||||
for row in json_lines(read_capped(council / SESSION_ACCOUNTS)):
|
||||
if isinstance(row.get("session"), str) and isinstance(row.get("email"), str) and len(row["email"]) <= EMAIL_CHARS:
|
||||
found[row["session"]] = row["email"]
|
||||
return found
|
||||
|
||||
|
||||
def epoch(value: object) -> float | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
@@ -700,24 +732,30 @@ def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tupl
|
||||
|
||||
def token_rows(sums: dict[tuple, list[int]]) -> list[dict]:
|
||||
"""Args:
|
||||
sums: per (t, agent, model, width) the counts in COUNTS order.
|
||||
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.
|
||||
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})} for (t, agent, model, width), counts in sorted(sums.items())]
|
||||
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) of the row a token row merges into: its day
|
||||
(UTC) when the row is daily or the day ended by line, else its hour.
|
||||
(t, agent, model, width, account) of the row a token row merges
|
||||
into: its day (UTC) when the row is daily or the day ended by line,
|
||||
else its hour.
|
||||
"""
|
||||
day = int(row["t"] // DAY * DAY)
|
||||
account = row["account"] if isinstance(row.get("account"), str) else ""
|
||||
if row.get("width") == DAY or day + DAY <= line:
|
||||
return day, row["agent"], row["model"], DAY
|
||||
return row["t"], row["agent"], row["model"], HOUR
|
||||
return day, row["agent"], row["model"], DAY, account
|
||||
return row["t"], row["agent"], row["model"], HOUR, account
|
||||
|
||||
|
||||
def add(sums: dict[tuple, list[int]], key: tuple, counts: tuple[int, ...]) -> None:
|
||||
@@ -775,6 +813,7 @@ def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budg
|
||||
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")):
|
||||
@@ -791,7 +830,7 @@ def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budg
|
||||
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), counts)
|
||||
add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR, accounts.get(session, "")), counts)
|
||||
rows = token_rows(sums)
|
||||
append_rows(state / TOKENS, rows)
|
||||
kept = {"files": files, "seen": kept_seen(seen, touched, now)}
|
||||
|
||||
@@ -220,13 +220,49 @@ def preview(row: dict, rules: Path | None) -> dict | None:
|
||||
return {"task": row["task"], "command": row["command"], "head": head, **shown}
|
||||
|
||||
|
||||
def review_preview(row: dict, rules: Path | None) -> dict | None:
|
||||
"""Args:
|
||||
row: a pending review that shipped no diff, with id, worktree, tree
|
||||
and head, the HEAD the hub last saw, None for none.
|
||||
rules: the MEDUSA rules directory.
|
||||
|
||||
Returns:
|
||||
{id, head, diff}: the review's tree against its worktree's HEAD
|
||||
(staged_diff.tree_diff), or {id, head, error} when it cannot be
|
||||
built; None while HEAD is the one the hub saw.
|
||||
"""
|
||||
try:
|
||||
head = staged_diff.head_of(Path(row["worktree"]))
|
||||
except PREVIEW_FAILURES as error:
|
||||
head, shown = "", {"error": str(error)[:ERROR_LIMIT]}
|
||||
else:
|
||||
shown = None
|
||||
if head == row["head"]:
|
||||
return None
|
||||
if shown is None:
|
||||
try:
|
||||
shown = {"diff": staged_diff.tree_diff(Path(row["worktree"]), row["tree"], rules)[0]}
|
||||
except PREVIEW_FAILURES as error:
|
||||
shown = {"error": str(error)[:ERROR_LIMIT]}
|
||||
return {"id": row["id"], "head": head, **shown}
|
||||
|
||||
|
||||
def oversized(shown: dict, keys: tuple[str, ...]) -> dict:
|
||||
if len(json.dumps(shown).encode()) <= hub_limits.DIFF_BODY_LIMIT:
|
||||
return shown
|
||||
return {**{key: shown[key] for key in keys}, "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"}
|
||||
|
||||
|
||||
def previews(base: str, rules: Path | None) -> None:
|
||||
for row in call(base, PREVIEWS, None)["rows"]:
|
||||
listed = call(base, PREVIEWS, None)
|
||||
for row in listed["rows"]:
|
||||
shown = preview(row, rules)
|
||||
if shown is not None and len(json.dumps(shown).encode()) > hub_limits.DIFF_BODY_LIMIT:
|
||||
shown = {"task": row["task"], "command": row["command"], "head": shown["head"], "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"}
|
||||
if shown is not None:
|
||||
call(base, PREVIEWS, shown)
|
||||
call(base, PREVIEWS, oversized(shown, ("task", "command", "head")))
|
||||
for row in listed["reviews"]:
|
||||
shown = review_preview(row, rules)
|
||||
if shown is not None:
|
||||
call(base, PREVIEWS, oversized(shown, ("id", "head")))
|
||||
|
||||
|
||||
def council_refusal(council: Path) -> str | None:
|
||||
|
||||
@@ -209,12 +209,13 @@ def digest(data: bytes | None) -> str:
|
||||
|
||||
def view_of(path: str) -> dict:
|
||||
"""Returns:
|
||||
{"path", "exists", "sha256", "error", "settings"}: settings only the
|
||||
{"path", "exists", "folder", "sha256", "error", "settings"}: folder
|
||||
False when the path's directory is missing, settings only the
|
||||
permissions and sandbox sections; error why the file was unreadable,
|
||||
for anything unforeseen only the exception's class, so one bad path
|
||||
never keeps the others or the view from being written.
|
||||
"""
|
||||
entry = {"path": path, "exists": False, "sha256": "", "error": "", "settings": {}}
|
||||
entry = {"path": path, "exists": False, "folder": True, "sha256": "", "error": "", "settings": {}}
|
||||
try:
|
||||
return read_view(path, entry)
|
||||
except Exception as error: # noqa: BLE001
|
||||
@@ -225,7 +226,7 @@ def read_view(path: str, entry: dict) -> dict:
|
||||
try:
|
||||
parent = parent_of(path)
|
||||
except FileNotFoundError:
|
||||
return {**entry, "error": MISSING_DIRECTORY}
|
||||
return {**entry, "folder": False, "error": MISSING_DIRECTORY}
|
||||
except OSError as error:
|
||||
return {**entry, "error": f"a link or no directory on the path: {error.strerror}"}
|
||||
try:
|
||||
|
||||
Executable
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Args:
|
||||
--home: the home whose ~/.claude/skills and ~/.agents/skills are read.
|
||||
--tree: the branch-tree.json pkgmgr branch tree writes; each of its
|
||||
repositories' .claude/skills and .agents/skills are read.
|
||||
--output: the index the Agent Orchestrator serves at /api/skills, e.g.
|
||||
~/.local/state/pkgmgr/tree/skills-index.json.
|
||||
|
||||
Returns:
|
||||
Runs on the host, because the hub's container sees no repository:
|
||||
replaces --output with {"written": <epoch>, "skills": [{"name",
|
||||
"description", "source"}]}, one entry per skill folder holding a
|
||||
SKILL.md, sorted by name and source; source is ~/.claude/skills,
|
||||
~/.agents/skills or the repository's path. The exit code is 0.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
HOME_SOURCES = (".claude/skills", ".agents/skills")
|
||||
SKILL_FILE = "SKILL.md"
|
||||
HEAD_BYTES = 16384
|
||||
TREE_BYTES = 8 << 20
|
||||
NAME = re.compile(r"[A-Za-z0-9:_.-]{1,100}")
|
||||
DESCRIPTION_CHARS = 300
|
||||
FIELD = re.compile(r"^(name|description):[ \t]*(.*)$")
|
||||
BLOCKS = (">", "|", ">-", "|-", ">+", "|+")
|
||||
|
||||
|
||||
def read_head(path: Path, limit: int) -> str:
|
||||
"""Returns:
|
||||
The first limit bytes of path as text, read without following a
|
||||
symlink and only from a regular file.
|
||||
|
||||
Raises:
|
||||
OSError: path is missing, a symlink or no regular file.
|
||||
"""
|
||||
handle = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
||||
with os.fdopen(handle, "rb") as stream:
|
||||
if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
|
||||
raise OSError(f"{path}: no regular file")
|
||||
return stream.read(limit).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def front_matter(text: str) -> dict[str, str]:
|
||||
"""Returns:
|
||||
name and description from the YAML front matter that opens text,
|
||||
each one line with its quotes stripped, a folded or literal block
|
||||
joined into it; none without a closed front matter.
|
||||
"""
|
||||
lines = text.splitlines()
|
||||
if not lines or lines[0].strip() != "---":
|
||||
return {}
|
||||
found, folding = {}, None
|
||||
for line in lines[1:]:
|
||||
if line.strip() == "---":
|
||||
return {key: " ".join(value.split()) for key, value in found.items()}
|
||||
match = FIELD.match(line)
|
||||
if match:
|
||||
value = match.group(2).strip()
|
||||
folding = match.group(1) if value in BLOCKS else None
|
||||
found[match.group(1)] = "" if folding else value.strip("\"'")
|
||||
elif folding and line[:1] in (" ", "\t"):
|
||||
found[folding] += f" {line.strip()}"
|
||||
else:
|
||||
folding = None
|
||||
return {}
|
||||
|
||||
|
||||
def skill_of(folder: Path, source: str) -> dict | None:
|
||||
"""Returns:
|
||||
{name, description, source} of a skill folder: the front matter's
|
||||
name, else the folder's; None without a readable SKILL.md or with a
|
||||
name outside NAME.
|
||||
"""
|
||||
try:
|
||||
fields = front_matter(read_head(folder / SKILL_FILE, HEAD_BYTES))
|
||||
except OSError:
|
||||
return None
|
||||
name = fields.get("name") or folder.name
|
||||
if not NAME.fullmatch(name):
|
||||
return None
|
||||
return {"name": name, "description": fields.get("description", "")[:DESCRIPTION_CHARS], "source": source}
|
||||
|
||||
|
||||
def skills_in(root: Path, source: str) -> list[dict]:
|
||||
try:
|
||||
folders = sorted(path for path in root.iterdir() if path.is_dir())
|
||||
except OSError:
|
||||
return []
|
||||
return [found for folder in folders if (found := skill_of(folder, source)) is not None]
|
||||
|
||||
|
||||
def repositories(tree: Path) -> list[str]:
|
||||
"""Returns:
|
||||
The absolute repository paths of the branch tree; none when it is
|
||||
unreadable.
|
||||
"""
|
||||
try:
|
||||
scan = json.loads(read_head(tree, TREE_BYTES))
|
||||
except (OSError, ValueError, RecursionError):
|
||||
return []
|
||||
repos = scan.get("repos") if isinstance(scan, dict) else None
|
||||
return sorted({repo["path"] for repo in repos if isinstance(repo, dict) and isinstance(repo.get("path"), str) and repo["path"].startswith("/")}) if isinstance(repos, list) else []
|
||||
|
||||
|
||||
def index(home: Path, tree: Path) -> list[dict]:
|
||||
found = [skill for part in HOME_SOURCES for skill in skills_in(home / part, f"~/{part}")]
|
||||
found += [skill for repo in repositories(tree) for part in HOME_SOURCES for skill in skills_in(Path(repo) / part, repo)]
|
||||
unique = {(skill["name"], skill["source"]): skill for skill in found}
|
||||
return [unique[key] for key in sorted(unique)]
|
||||
|
||||
|
||||
def write(output: Path, data: dict) -> None:
|
||||
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=output.parent, prefix=f".{output.name}.", delete=False) as handle:
|
||||
try:
|
||||
json.dump(data, handle)
|
||||
except BaseException:
|
||||
os.unlink(handle.name)
|
||||
raise
|
||||
os.replace(handle.name, output)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Index the skills an agent message may name for the Agent Orchestrator.")
|
||||
parser.add_argument("--home", type=Path, required=True)
|
||||
parser.add_argument("--tree", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
write(args.output, {"written": time.time(), "skills": index(args.home, args.tree)})
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user