perf(skills): cut the tokens and start-up time every agent pays

Requirement 071, from the skeptic audit picks.

Output: radio.py show groups older rows per peer and class into one
line each (7 days 143,520 -> 3,229 bytes); rasci.py show is narrower
(7,081 -> 2,915 bytes) and archives tasks ended over 7 days ago into
rasci-archive.json, still listed by get, --all, artifacts and tools
and revived by any command that names them; make test runs quiet.

Hooks: hooks register as python3 -I -S (site import skipped), the
hook paths of watch, queue, radio, graph and log skip argparse, and
traceback, tempfile, configparser, tomllib, statistics and urllib load
lazily; councilroot.guard() serves watch and radio; the dream
reminder exits before Python when no row can be on. pre-bash 68 ms,
post-bash 50 ms.

Hub: names.json keeps only the entries every lookup needs (11.6 MB ->
11 KB, lookups identical) and phrasing is cached; a state build takes
55 instead of 104 ms.

Context: the commit-chain skills shrink from 3,330 to 1,192 words with
their names kept, details moved to chain.md and reference.md files read
on demand; descriptions capped at 25 words; .ignore and .rgignore keep
state and worktrees out of searches. overhead.py of
kvb-check-efficiency measures hook and script cost per call.

🎯 Fix: 93 %
💥 Break: 5 %
💸 Tokens: 107 %
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 83
🚦 Gate: ⚠️ tokens 107 % > 100 (on-demand reference files; resident text and daily cost fall): operator approved the commit

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-27 10:49:30 +00:00
1 parent 5c969be21c
commit 9403e17e97
53 files changed
+1219 -522

No files matched your search

+24
View File
@@ -118,6 +118,22 @@ class TestDreamHook(unittest.TestCase):
self.assertEqual(self._run(self._session("a1")), "")
self.assertFalse(self.stamps.exists())
def test_a_row_that_cannot_be_on_starts_no_python(self):
hook = Path(self.tmp.name) / "skills" / "kvb-dream" / "hooks" / "reminder.sh"
hook.parent.mkdir(parents=True)
shutil.copy(HOOK, hook)
marker = Path(self.tmp.name) / "checked"
fake = Path(self.tmp.name) / "skills" / "kvb-org-organize" / "scripts" / "schedules.py"
fake.parent.mkdir(parents=True)
fake.write_text(f"open({str(marker)!r}, 'a').close()\nprint(12)\n", encoding="utf-8")
env = {"PATH": "/usr/bin:/bin", "HOME": self.tmp.name, "DREAM_STAMP_DIR": str(self.stamps)}
for row, started in (({"on": False, "every": 12}, False), (None, False), ({"every": 12, "on": True}, True)):
with self.subTest(row=row):
marker.unlink(missing_ok=True)
self.schedule(row)
subprocess.run(["bash", str(hook)], input=self._session("a1"), capture_output=True, text=True, check=True, env={**env, **self.env})
self.assertEqual(marker.exists(), started)
def test_corrupt_stamp_does_not_crash(self):
self.stamps.mkdir()
(self.stamps / "a1").write_text("not-a-timestamp\n", encoding="utf-8")
@@ -265,6 +281,14 @@ class TestSettingsRegistration(unittest.TestCase):
self.assertEqual([(run.returncode, run.stdout) for run in runs], [(3, "__main__ ['pre-bash'] True\n")] * 2)
self.assertEqual([path.name.split(".")[0] for path in (script.parent / "__pycache__").iterdir()], ["hooks"])
def test_a_hook_registered_with_the_site_import_moves_to_the_start_without_it(self):
data = self._patch()
(gate,) = self._hooks(data, "PreToolUse", "kvb-org-organize/scripts/hooks.py")
gate["command"] = gate["command"].replace("/usr/bin/python3 -I -S ", "/usr/bin/python3 -I ")
self.settings.write_text(json.dumps(data), encoding="utf-8")
(moved,) = self._hooks(self._patch(), "PreToolUse", "kvb-org-organize/scripts/hooks.py")
self.assertIn("/usr/bin/python3 -I -S -c ", moved["command"])
def bash_entries(self, data: dict, event: str) -> list[dict]:
return [entry for entry in data["hooks"].get(event, []) if not entry.get("matcher") or entry["matcher"] == "*" or re.fullmatch(entry["matcher"], "Bash")]
+23
View File
@@ -504,5 +504,28 @@ class TestMeasure(GitRepo):
self.assertCleanedUp()
class TestOverhead(unittest.TestCase):
def run_overhead(self, skills: Path, *args: str) -> subprocess.CompletedProcess:
return subprocess.run([sys.executable, str(SCRIPTS / "overhead.py"), "--skills", str(skills), *args], capture_output=True, text=True, check=False, timeout=120)
def test_each_case_prints_one_line_with_its_timings_output_and_exit_code(self):
with tempfile.TemporaryDirectory() as folder:
script = Path(folder) / "kvb-org-radio" / "scripts" / "radio.py"
script.parent.mkdir(parents=True)
script.write_text("import sys\nsys.stdin.read()\nprint('row')\nsys.exit(4)\n", encoding="utf-8")
done = self.run_overhead(Path(folder), "--runs", "2", "--case", "python-empty", "--case", "radio-tool", "--flags=-I -S")
self.assertEqual(done.returncode, 0, done.stderr)
lines = done.stdout.splitlines()
self.assertEqual([line.split("\t")[0] for line in lines], ["python-empty", "radio-tool"])
for line in lines:
self.assertRegex(line, r"^[a-z-]+\t\d+ms\t\d+\t\d+\tcpu=\d+ms\t\d+B\trc=\d+$")
self.assertTrue(lines[1].endswith("\t4B\trc=4"))
def test_an_unknown_case_is_refused(self):
done = self.run_overhead(REPO_ROOT / "skills", "--runs", "1", "--case", "nope")
self.assertEqual(done.returncode, 2)
self.assertIn("unknown case nope", done.stderr)
if __name__ == "__main__":
unittest.main()
+35
View File
@@ -1,11 +1,14 @@
from __future__ import annotations
import json
import random
import tempfile
import unittest
from pathlib import Path
import hub_support # noqa: F401
from kvb_orchestrator import names
from kvb_orchestrator.matching import born_of
class TestRenameOnce(unittest.TestCase):
@@ -59,5 +62,37 @@ class TestDirectoryLookups(unittest.TestCase):
self.assertEqual(book.directory().now("s1"), "B")
def lookups(entries: list[dict]) -> dict:
directory = names.Directory(entries)
known = sorted(directory.by_name)
return {
"renames": [(row["id"], row["title"]) for row in directory.renames(-1.0, 1e9)],
"born": [born_of(name, entries, []) for name in known],
"aliases": [sorted(directory.aliases(name)) for name in known],
"holders": [directory.by_name[name] for name in known],
"now": {session: directory.now(session) for session in directory.by_session},
"names": {session: directory.names(session) for session in directory.by_session},
"find": [directory.find(name, 1e9) for name in known],
}
class TestCompaction(unittest.TestCase):
def test_thirty_thousand_flip_flops_shrink_and_every_lookup_stays(self):
pick = random.Random(7)
cycle = [{"session": "s1", "name": pick.choice(("Stage", "i18n 2.0", "Stage:x")), "first_seen": float(index), "source": "claim"} for index in range(30000)]
entries = [{"session": "s0", "name": "Main", "first_seen": 0.0, "source": "claim"}, *cycle,
{"session": "s1", "name": "Skills", "first_seen": 30000.0, "source": "title"},
{"session": "s2", "name": "Stage", "first_seen": 30001.0, "source": "claim"}]
with tempfile.TemporaryDirectory() as folder:
store = Path(folder) / "names.json"
store.write_text(json.dumps({"entries": entries, "observed": {}}), encoding="utf-8")
before = store.stat().st_size
kept = names.Names(store).listed()
self.assertLess(len(kept), 60)
self.assertLess(store.stat().st_size * 100, before)
self.assertEqual(lookups(kept), lookups(entries))
self.assertEqual(names.Names(store).listed(), kept)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -23,8 +23,8 @@ QUEUE = SCRIPTS / "queue.py"
HISTORY = SCRIPTS / "history.py"
STANDSTILL = SCRIPTS / "standstill.py"
NOW = 1_800_000_000.0
POLL = 0.1
HUNG = 2.0
POLL = 0.05
HUNG = 0.2
GRACE = 0.5
OUTLAST = HUNG + 0.5
SAMPLE = {"free_gb": 50.0, "mem": 20.0, "cpu": 10.0}
+33 -16
View File
@@ -209,7 +209,7 @@ class TestRadio(unittest.TestCase):
]
(self.root / "news.jsonl").write_text("".join(json.dumps(r) + "\n" for r in old), encoding="utf-8")
self.assertEqual(
[strip(line) for line in self._send("s2", "show", "--all")],
[strip(line) for line in self._send("s2", "show", "--all", "--full")],
[
"NEWSLETTER Three: old board",
"POST Three to Two: old direct",
@@ -303,16 +303,23 @@ class TestRadio(unittest.TestCase):
self.assertEqual(len(caller), 2)
self.assertRegex(caller[1], RECEIPT)
def test_prompt_hook_shows_ten_and_counts_the_rest(self):
def test_prompt_hook_keeps_alarms_and_shows_five_broadcasts_and_counts_the_rest(self):
self._send("s1", "send", "security", "early warning")
for n in range(12):
self._send("s1", "send", "broadcast", f"item {n}")
lines = self._prompt("s2")
self.assertEqual(lines[0], "SECURITY One: early warning")
self.assertEqual(lines[1:-1], [f"BROADCAST One: item {n}" for n in range(3, 12)])
self.assertEqual(lines[-1], "RADIO 3 more items: radio.py show --all --since 1d --summary")
self.assertEqual(lines[1:-1], [f"BROADCAST One: item {n}" for n in range(7, 12)])
self.assertEqual(lines[-1], "RADIO 7 more items: radio.py show --all --since 1d")
self.assertEqual(self._prompt("s2"), [])
def test_calls_to_this_session_are_never_held_back_or_cut(self):
long = "z" * 900
for n in range(7):
self._send("s1", "send", "call", f"{long} {n}", "--to", "Two")
lines = self._tool("s2")
self.assertEqual(lines, [f"CALL One to Two: {long} {n}" for n in range(7)])
def test_the_mailbox_delivers_post_and_newsletters_once_when_the_turn_ends(self):
self._send("s1", "post", "board")
self._send("s1", "post", "for two", "--to", "Two")
@@ -323,13 +330,16 @@ class TestRadio(unittest.TestCase):
self.assertEqual(self._mailbox("s1"), (0, []))
self.assertEqual(self._prompt("s2"), ["SECURITY One: sec"])
def test_the_mailbox_shows_ten_and_counts_the_rest(self):
for n in range(12):
def test_the_mailbox_shows_five_newsletters_cut_short_and_counts_the_rest(self):
for n in range(11):
self._send("s1", "post", f"item {n}")
self._send("s1", "post", "w" * 400)
code, lines = self._mailbox("s2")
self.assertEqual(code, 2)
self.assertEqual(lines[:-1], [f"NEWSLETTER One: item {n}" for n in range(2, 12)])
self.assertEqual(lines[-1], "MAIL 2 more items: radio.py show --all --since 1d --summary")
self.assertEqual(lines[:-2], [f"NEWSLETTER One: item {n}" for n in range(7, 11)])
self.assertTrue(lines[-2].endswith("…"))
self.assertLess(len(lines[-2]), 200)
self.assertEqual(lines[-1], "MAIL 7 more items: radio.py show --all --since 1d")
self.assertEqual(self._mailbox("s2"), (0, []))
def test_a_read_call_puts_one_receipt_in_the_callers_mailbox_without_waking_it(self):
@@ -368,10 +378,17 @@ class TestRadio(unittest.TestCase):
old = {"ts": time.time() - 7200, "class": "security", "from": "Old", "to": [], "text": "stale", "v": 2}
with (self.root / "news.jsonl").open("a", encoding="utf-8") as news:
news.write(json.dumps(old) + "\n")
shown = self._cli("s3", "show", "--all", "--since", "1h", "--summary")
self.assertEqual(shown.returncode, 0, shown.stderr)
lines = [re.sub(r"\d\d:\d\d", "HH:MM", line) for line in shown.stdout.splitlines()]
self.assertEqual(lines, ["BROADCAST One: 2, last HH:MM: second", "NEWSLETTER Two: 1, last HH:MM: board"])
receipt = {"ts": time.time(), "class": "receipt", "from": "Two", "to": ["One"], "text": "ring", "v": 2, "call": time.time()}
with (self.root / "news.jsonl").open("a", encoding="utf-8") as news:
news.write(json.dumps(receipt) + "\n")
expected = ["BROADCAST One: 2, last HH:MM: second", "NEWSLETTER Two: 1, last HH:MM: board"]
for extra in ((), ("--summary",)):
shown = self._cli("s3", "show", "--all", "--since", "1h", *extra)
self.assertEqual(shown.returncode, 0, shown.stderr)
self.assertEqual([re.sub(r"\d\d:\d\d", "HH:MM", line) for line in shown.stdout.splitlines()], expected)
full = self._cli("s3", "show", "--all", "--since", "1h", "--full").stdout.splitlines()
self.assertEqual(len(full), 4)
self.assertTrue(any("read by Two" in line for line in full))
self.assertEqual(self._cli("s3", "show", "--since", "soon").returncode, 2)
def test_tool_hook_delivers_radio_rows_once_and_leaves_the_mail_for_the_stop(self):
@@ -585,11 +602,11 @@ class TestRadio(unittest.TestCase):
def test_the_tool_hook_caps_radio_items_like_the_prompt_hook(self):
self.root.mkdir()
now = time.time()
rows = [{"ts": now - 60 + i, "class": "security", "from": "Three", "to": [], "text": f"s{i}"} for i in range(12)]
rows = [{"ts": now - 60 + i, "class": "broadcast", "from": "Three", "to": [], "text": f"s{i}", "v": 2} for i in range(12)]
(self.root / "news.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
shown = self._tool("s2")
self.assertEqual(len(shown), 11)
self.assertEqual(shown[-1], "RADIO 2 more items: radio.py show --all --since 1d --summary")
self.assertEqual(len(shown), 6)
self.assertEqual(shown[-1], "RADIO 7 more items: radio.py show --all --since 1d")
def test_long_fields_are_clipped_and_a_planted_silence_stays_on_one_line(self):
self.root.mkdir()
@@ -767,7 +784,7 @@ class TestRadio(unittest.TestCase):
sessions = self.home / ".claude" / "sessions"
for sid, name in (("s2", "Deux"), ("s3", "Two"), ("s4", "Deux")):
(sessions / f"{sid}.json").write_text(json.dumps({"sessionId": sid, "name": name}), encoding="utf-8")
self.assertEqual(self._send(None, "show", "--all")[0].split(" ", 3)[3], "Operator to Two: ran x")
self.assertEqual(self._send(None, "show", "--all", "--full")[0].split(" ", 3)[3], "Operator to Two: ran x")
self.assertEqual(self._prompt("s2"), ["CALL Operator to Two: ran x"])
self.assertEqual(self._prompt("s3"), ["CALL Operator to Two: ran x"])
self.assertEqual(self._mailbox("s3"), (2, ["POST Operator to Three: ran x"]))
+22 -3
View File
@@ -95,8 +95,10 @@ class TestRasci(unittest.TestCase):
f"| 2 | - | work/a: Alpha | Ship A | running | Skills | - | {local(start)} | - "
"| Skills | Skills | | Operator, Pkgmgr | Operator |",
)
self.assertEqual(lines[4], "gaps: 3 (show --gaps)")
self.assertEqual(
lines[4], "gaps: work/b has 0 A; work/b has no key result; work/a has no key result"
self._out("show", "--gaps")[-3:],
["gap: work/b has 0 A", "gap: work/b has no key result", "gap: work/a has no key result"],
)
def test_show_prints_the_compact_table_by_default(self):
@@ -108,7 +110,7 @@ class TestRasci(unittest.TestCase):
"|---|---|---|---|---|---|",
"| 1 | - | work/b: Beta | queued | subagent Explore (haiku) | |",
"| 2 | - | work/a: Alpha | running | Skills | Skills |",
"gaps: work/b has 0 A; work/b has no key result; work/a has no key result",
"gaps: 3 (show --gaps)",
],
)
@@ -261,6 +263,22 @@ class TestRasci(unittest.TestCase):
f"| done | - | - | - | {local('2026-11-01T12:00:00+00:00')} |", self._out("show", "--all", "--wide")[2]
)
def test_tasks_ended_over_a_week_ago_move_to_the_archive_and_stay_reachable(self):
now = datetime.datetime.now(datetime.UTC)
self._run("set", "work/old", "--status", "done", "--end", (now - datetime.timedelta(days=8)).isoformat())
self._run("set", "work/new", "--status", "done", "--end", (now - datetime.timedelta(days=1)).isoformat())
live = json.loads((self.root / "rasci.json").read_text(encoding="utf-8"))
archived = json.loads((self.root / "rasci-archive.json").read_text(encoding="utf-8"))
self.assertEqual((sorted(live), sorted(archived)), (["work/new"], ["work/old"]))
self.assertIn("status: done", self._out("get", "work/old"))
self.assertEqual(sorted(line.split(" | ")[2] for line in self._out("show", "--all")[2:] if line.startswith("| ")), ["work/new", "work/old"])
self._run("kr", "work/old", "add", "late note")
self.assertIn("key result 1 [ ]: late note", self._out("get", "work/old"))
self.assertNotIn("work/old", json.loads((self.root / "rasci.json").read_text(encoding="utf-8")))
self._run("rm", "work/old")
self.assertEqual(self._run("get", "work/old").returncode, 2)
self.assertNotIn("work/old", json.loads((self.root / "rasci-archive.json").read_text(encoding="utf-8")))
def test_artifacts_and_tools(self):
self._run("set", "work/a", "--workdir", "/w/a", "--branch", "feat/a", "--status", "done",
"--artifact", "image:core:dev", "--artifact", "volume:db",
@@ -415,7 +433,8 @@ class TestRasci(unittest.TestCase):
self._out("wsjf")[2:], ["| 1 | work/a | - (0/1 KR) | - | - | - | - | queued |", "unestimated: work/a"]
)
self._run("set", "work/b", "--title", "Beta")
self.assertEqual(self._out("show")[-1], "gaps: work/b has 0 A; work/b has no R; work/b has no key result")
self.assertEqual(self._out("show")[-1], "gaps: 3 (show --gaps)")
self.assertEqual(self._out("show", "--gaps")[-1], "gap: work/b has no key result")
self._run("set", "hotfix/db", "--status", "done", "--branch", "fix/db", "--workdir", "/w/db")
self._run("set", "operator/push", "--branch", "main", "--artifact", "dir:/tmp/push")
self._run("set", "work/a", "--branch", "feat/a")