Hub: send in the field (032), coherent speak box (033), stream head band (034), Match at full width with its pile (035, 036), Home without the outer box (037), badge to Match (038), rejects that survive a changed or withdrawn card (039), the release card (040), code marks in the review diff (041), why Deny is off (042), the undo window clock (043), widgets without inner boxes (044), the Artifacts head on one line (045), accepting a red gate's risk (046), one code box (047), done rows greyed and folded (048), one control height (049), menus that stay open (050), radio settings in the Device card (051), bubbles beside the modes (052), agent settings on every face and name (053), pin only by menu (054), WASD in Match (055), the flowing card edge (056), Schedules in Controls (057) and the hub poll cost (059). Skills: the coach leaves for its own repository kevinveenbirkenbach/coach (058; test_install pins its four skills in skills-lock.json and stays red until that repository is published and pinned), hooks and timers start fewer processes (060), council files on hot paths stay bounded and mirror by marker instead of mtime (061), scripts and hooks hand agents less output (062), and block.py builds the commit table and message block in one run (063). Requirement documents 032 to 063 with their implementation amendments. MEDUSA false positives accepted after kvb-think-criticize (36 lines): MM-SCAN-058 (pla inside replace or plan), JB-SCAN-616/641 (the local clip helper), CODEGEN-SCAN-001 (drop-in paths), CGS-SCAN-029 (systemctl argv from constants), CGS-SCAN-040 (runner poll loop), FLA-SCAN-055 (feedback), WM-SCAN-354, AI-BACKDOOR-006, GENAI-SCAN-1270, B604 (runner shell path for passkey-verified commands), TC004, EXA002, EXA006, EXA010 and WEB-SSRF. 🎯 Fix: 92 % 💥 Break: 8 % 💸 Tokens: 89 % ⏱️ Velocity: – 🛡️ Security: ~100 % 🏆 Score: 95 🚦 Gate: ⛔ break 8 % > 5 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
499 lines
25 KiB
Python
499 lines
25 KiB
Python
"""Validate the kvb-dream reminder, its GNOME notification, timer and settings registration."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[1]
|
|
DREAM = REPO_ROOT / "skills" / "kvb-dream"
|
|
SKILL = DREAM / "SKILL.md"
|
|
HOOK = DREAM / "hooks" / "reminder.sh"
|
|
NOTIFY = DREAM / "hooks" / "notify.sh"
|
|
TIMER = DREAM / "systemd" / "kvb-dream-notify.timer"
|
|
SERVICE = DREAM / "systemd" / "kvb-dream-notify.service"
|
|
PATCHER = REPO_ROOT / "scripts" / "enable-plugins.js"
|
|
COUNCIL_DENY = REPO_ROOT / "scripts" / "council-deny.js"
|
|
DENIED = ["Edit(~/.claude/agents-council/**)", "Edit(~/.local/state/agents-council/**)"]
|
|
|
|
|
|
class TestDreamSkill(unittest.TestCase):
|
|
def test_skill_runs_optimize_and_the_cleanups(self):
|
|
text = SKILL.read_text(encoding="utf-8")
|
|
self.assertIn("name: kvb-dream", text)
|
|
self.assertIn("multiSelect: false", text)
|
|
for skill in ("`kvb-optimize`", "`kvb-cleanup`", "`kvb-git-gc`"):
|
|
self.assertIn(skill, text)
|
|
|
|
def test_optimize_covers_every_optimization_skill(self):
|
|
text = (REPO_ROOT / "skills" / "kvb-optimize" / "SKILL.md").read_text(encoding="utf-8")
|
|
for skill in (
|
|
"kvb-skill-cleanup",
|
|
"kvb-transcend",
|
|
"kvb-skill-auto",
|
|
"kvb-skill-tune",
|
|
"kvb-skill-compile",
|
|
"kvb-skill-essence",
|
|
"kvb-skill-silence",
|
|
"kvb-code-refactor",
|
|
"kvb-code-tune",
|
|
"kvb-agent-optimize",
|
|
"kvb-think-gaps",
|
|
):
|
|
self.assertIn(f"`{skill}`", text)
|
|
|
|
|
|
def council_with(root: Path, rows: dict | None) -> dict:
|
|
"""Args:
|
|
root: the council directory to create.
|
|
rows: the schedules.json content, None for no file.
|
|
|
|
Returns:
|
|
The environment entry that points the hooks at root.
|
|
"""
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
if rows is not None:
|
|
(root / "schedules.json").write_text(json.dumps(rows), encoding="utf-8")
|
|
return {"AGENTS_COUNCIL_ROOT": str(root)}
|
|
|
|
|
|
class TestDreamHook(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.stamps = Path(self.tmp.name) / "stamps"
|
|
self.council = Path(self.tmp.name) / "council"
|
|
self.schedule({"on": True, "every": 12})
|
|
|
|
def schedule(self, row: dict | None) -> None:
|
|
self.env = council_with(self.council, None if row is None else {"dream": row})
|
|
if row is None:
|
|
(self.council / "schedules.json").unlink(missing_ok=True)
|
|
|
|
def _run(self, payload: str, path: str = "/usr/bin:/bin") -> str:
|
|
return subprocess.run(
|
|
["bash", str(HOOK)],
|
|
input=payload,
|
|
capture_output=True,
|
|
text=True,
|
|
check=True,
|
|
env={"PATH": path, "HOME": self.tmp.name, "DREAM_STAMP_DIR": str(self.stamps), **self.env},
|
|
).stdout
|
|
|
|
@staticmethod
|
|
def _session(sid: str) -> str:
|
|
return json.dumps({"session_id": sid, "prompt": "hi"})
|
|
|
|
def test_first_run_hints_and_stamps_the_session(self):
|
|
self.assertIn("/kvb-dream", self._run(self._session("a1")))
|
|
self.assertTrue((self.stamps / "a1").is_file())
|
|
|
|
def test_second_run_of_the_same_agent_is_silent(self):
|
|
self._run(self._session("a1"))
|
|
self.assertEqual(self._run(self._session("a1")), "")
|
|
|
|
def test_every_agent_gets_its_own_hint(self):
|
|
self._run(self._session("a1"))
|
|
self.assertIn("/kvb-dream", self._run(self._session("b2")))
|
|
|
|
def test_hint_returns_after_the_rows_hours(self):
|
|
self.schedule({"on": True, "every": 2})
|
|
self.stamps.mkdir()
|
|
stamp = self.stamps / "a1"
|
|
now = int(subprocess.run(["date", "+%s"], capture_output=True, text=True, check=True).stdout)
|
|
stamp.write_text(f"{now - 3600}\n", encoding="utf-8")
|
|
self.assertEqual(self._run(self._session("a1")), "")
|
|
stamp.write_text(f"{now - 7300}\n", encoding="utf-8")
|
|
self.assertIn("/kvb-dream", self._run(self._session("a1")))
|
|
|
|
def test_the_row_off_or_no_schedules_file_keeps_it_silent_and_stamps_nothing(self):
|
|
for row in ({"on": False, "every": 12}, None):
|
|
with self.subTest(row=row):
|
|
self.schedule(row)
|
|
self.assertEqual(self._run(self._session("a1")), "")
|
|
self.assertFalse(self.stamps.exists())
|
|
|
|
def test_corrupt_stamp_does_not_crash(self):
|
|
self.stamps.mkdir()
|
|
(self.stamps / "a1").write_text("not-a-timestamp\n", encoding="utf-8")
|
|
self.assertIn("/kvb-dream", self._run(self._session("a1")))
|
|
|
|
def test_without_a_valid_session_it_stays_silent(self):
|
|
for payload in ("", "not json", self._session(""), self._session("../escape")):
|
|
with self.subTest(payload=payload):
|
|
self.assertEqual(self._run(payload), "")
|
|
self.assertFalse(self.stamps.exists())
|
|
|
|
def test_a_binary_planted_on_the_inherited_path_never_runs(self):
|
|
planted = Path(self.tmp.name) / "planted"
|
|
planted.mkdir()
|
|
marker = Path(self.tmp.name) / "ran"
|
|
for name in ("python3", "date", "mkdir", "cat"):
|
|
fake = planted / name
|
|
fake.write_text(f"#!/bin/sh\n/usr/bin/touch '{marker}'\n", encoding="utf-8")
|
|
fake.chmod(0o755)
|
|
self._run(self._session("a1"), path=f"{planted}:/usr/bin:/bin")
|
|
self.assertFalse(marker.exists())
|
|
|
|
|
|
class TestDreamNotification(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.bin = Path(self.tmp.name) / "bin"
|
|
self.bin.mkdir()
|
|
self.calls = Path(self.tmp.name) / "calls"
|
|
fake = self.bin / "notify-send"
|
|
fake.write_text(f'#!/bin/sh\nprintf "%s\\n" "$@" >> "{self.calls}"\n', encoding="utf-8")
|
|
fake.chmod(0o755)
|
|
self.council = Path(self.tmp.name) / "council"
|
|
|
|
def _run(self, desktop: str, row: dict | None = None) -> None:
|
|
rows = {"dream-popup": row or {"on": True, "at": ["17:00"]}}
|
|
subprocess.run(
|
|
["bash", str(NOTIFY)],
|
|
capture_output=True,
|
|
check=True,
|
|
env={"PATH": f"{self.bin}:/usr/bin:/bin", "XDG_CURRENT_DESKTOP": desktop, "HOME": self.tmp.name, **council_with(self.council, rows)},
|
|
)
|
|
|
|
def test_gnome_session_gets_the_popup(self):
|
|
self._run("ubuntu:GNOME")
|
|
self.assertIn("/kvb-dream", self.calls.read_text(encoding="utf-8"))
|
|
|
|
def test_other_desktops_stay_silent(self):
|
|
self._run("KDE")
|
|
self.assertFalse(self.calls.exists())
|
|
|
|
def test_the_popup_row_off_or_a_missing_schedules_file_sends_nothing(self):
|
|
self._run("ubuntu:GNOME", {"on": False, "at": ["17:00"]})
|
|
self.assertFalse(self.calls.exists())
|
|
(self.council / "schedules.json").unlink()
|
|
subprocess.run(
|
|
["bash", str(NOTIFY)],
|
|
capture_output=True,
|
|
check=True,
|
|
env={"PATH": f"{self.bin}:/usr/bin:/bin", "XDG_CURRENT_DESKTOP": "ubuntu:GNOME", "HOME": self.tmp.name, "AGENTS_COUNCIL_ROOT": str(self.council)},
|
|
)
|
|
self.assertFalse(self.calls.exists())
|
|
|
|
def test_timer_fires_daily_at_five_pm_and_catches_up(self):
|
|
timer = TIMER.read_text(encoding="utf-8")
|
|
self.assertIn("OnCalendar=*-*-* 17:00:00", timer)
|
|
self.assertIn("Persistent=true", timer)
|
|
self.assertIn("kvb-dream/hooks/notify.sh", SERVICE.read_text(encoding="utf-8"))
|
|
|
|
|
|
@unittest.skipUnless(shutil.which("node"), "node not installed")
|
|
class TestSettingsRegistration(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.settings = Path(self.tmp.name) / "settings.json"
|
|
|
|
def _patch(self) -> dict:
|
|
subprocess.run(
|
|
["node", str(PATCHER), str(self.settings)], check=True, capture_output=True
|
|
)
|
|
return json.loads(self.settings.read_text(encoding="utf-8"))
|
|
|
|
@staticmethod
|
|
def _hooks(data: dict, event: str, script: str) -> list[dict]:
|
|
return [
|
|
hook
|
|
for entry in data["hooks"].get(event, [])
|
|
for hook in entry.get("hooks", [])
|
|
if script in hook.get("command", "")
|
|
]
|
|
|
|
def test_hook_registered_once(self):
|
|
self._patch()
|
|
data = self._patch()
|
|
expected = {
|
|
("UserPromptSubmit", "kvb-dream/hooks/reminder.sh"): 1,
|
|
("UserPromptSubmit", "kvb-coach/hooks/reminder.sh"): 1,
|
|
("UserPromptSubmit", "tune/hooks/reminder.sh"): 0,
|
|
("UserPromptSubmit", "kvb-org-organize/scripts/watch.py"): 1,
|
|
("UserPromptSubmit", "kvb-org-radio/scripts/radio.py"): 1,
|
|
("UserPromptSubmit", "kvb-org-organize/scripts/news.py"): 0,
|
|
("PostToolBatch", "kvb-org-radio/scripts/radio.py"): 1,
|
|
("Stop", "kvb-org-radio/scripts/radio.py"): 2,
|
|
("PreToolUse", "kvb-org-radio/scripts/radio.py"): 1,
|
|
("PreToolUse", "kvb-org-organize/scripts/council.py"): 1,
|
|
("PreToolUse", "kvb-org-organize/scripts/watch.py"): 0,
|
|
("PreToolUse", "kvb-org-queue/scripts/queue.py"): 0,
|
|
("PreToolUse", "kvb-org-perform/scripts/log.py"): 1,
|
|
("PreToolUse", "kvb-agent-optimize/scripts/graph.py"): 1,
|
|
("PreToolUse", "kvb-org-organize/scripts/hooks.py"): 1,
|
|
("PostToolUse", "kvb-org-organize/scripts/watch.py"): 0,
|
|
("PostToolUse", "kvb-org-perform/scripts/log.py"): 0,
|
|
("PostToolUse", "kvb-org-organize/scripts/hooks.py"): 1,
|
|
}
|
|
for (event, script), count in expected.items():
|
|
with self.subTest(event=event, script=script):
|
|
self.assertEqual(len(self._hooks(data, event, script)), count)
|
|
|
|
def test_radio_listener_wakes_asynchronously_and_hooks_survive_a_missing_script(self):
|
|
data = self._patch()
|
|
listen, mailbox = self._hooks(data, "Stop", "kvb-org-radio/scripts/radio.py")
|
|
self.assertIs(listen["asyncRewake"], True)
|
|
self.assertGreater(listen["timeout"], 3600)
|
|
self.assertTrue(listen["command"].endswith(" listen"))
|
|
self.assertTrue(mailbox["command"].endswith(" mailbox"))
|
|
self.assertNotIn("asyncRewake", mailbox)
|
|
(block,) = [
|
|
entry
|
|
for entry in data["hooks"]["PreToolUse"]
|
|
if any(hook["command"].endswith("radio.py\" block") for hook in entry["hooks"])
|
|
]
|
|
self.assertEqual(block["matcher"], "Edit|Write|MultiEdit|NotebookEdit")
|
|
(gate,) = self._hooks(data, "PreToolUse", "kvb-org-organize/scripts/hooks.py")
|
|
result = subprocess.run(["sh", "-c", gate["command"]], capture_output=True, check=False)
|
|
self.assertEqual(result.returncode, 1)
|
|
|
|
def test_a_hook_runs_its_script_as_main_from_cached_bytecode_and_keeps_its_exit_code(self):
|
|
(gate,) = self._hooks(self._patch(), "PreToolUse", "kvb-org-organize/scripts/hooks.py")
|
|
script = Path(self.tmp.name) / "skills" / "kvb-org-organize" / "scripts" / "hooks.py"
|
|
script.parent.mkdir(parents=True)
|
|
script.write_text("import sys\nprint(__name__, sys.argv[1:], sys.argv[0] == __file__)\nsys.exit(3)\n", encoding="utf-8")
|
|
runs = [subprocess.run(["sh", "-c", gate["command"]], capture_output=True, text=True, check=False) for _ in range(2)]
|
|
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 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")]
|
|
|
|
def answer(self, command: str, home: Path, event: str) -> tuple:
|
|
home.mkdir()
|
|
env = {"PATH": "/usr/bin:/bin", "HOME": str(home), "AGENTS_COUNCIL_ROOT": str(home / "council"), "XDG_STATE_HOME": str(home / "state")}
|
|
payload = json.dumps({"session_id": "s", "hook_event_name": event, "tool_name": "Bash", "tool_input": {"command": "ls"}, "tool_response": {"stdout": ""}, "cwd": "/"})
|
|
done = subprocess.run(["sh", "-c", command], input=payload, cwd="/", env=env, capture_output=True, text=True, timeout=60, check=False)
|
|
return done.returncode, done.stdout.replace(str(home), "~"), done.stderr.replace(str(home), "~")
|
|
|
|
def test_the_bash_dispatcher_answers_as_its_handlers_started_directly(self):
|
|
data = self._patch()
|
|
skills = Path(self.tmp.name) / "skills"
|
|
skills.symlink_to(REPO_ROOT / "skills")
|
|
handlers = {
|
|
("PreToolUse", "pre-bash"): [("kvb-org-radio/scripts/radio.py", "block"), ("kvb-org-organize/scripts/watch.py", "block"), ("kvb-org-queue/scripts/queue.py", "block"), ("kvb-agent-optimize/scripts/graph.py", "hook")],
|
|
("PostToolUse", "post-bash"): [("kvb-org-organize/scripts/watch.py", "watch"), ("kvb-org-perform/scripts/log.py", "persist")],
|
|
}
|
|
for (event, sub), scripts in handlers.items():
|
|
with self.subTest(event=event):
|
|
(gate,) = [hook for entry in self.bash_entries(data, event) for hook in entry["hooks"] if "importlib" in hook["command"]]
|
|
self.assertTrue(gate["command"].endswith(f'hooks.py" {sub}'))
|
|
direct = [self.answer(f'/usr/bin/python3 -I "{skills / script}" {name}', Path(self.tmp.name) / f"direct-{sub}-{n}", event) for n, (script, name) in enumerate(scripts)]
|
|
self.assertEqual([code for code, _, _ in direct], [0] * len(scripts), direct)
|
|
self.assertEqual(self.answer(gate["command"], Path(self.tmp.name) / f"dispatched-{sub}", event), (0, "".join(out for _, out, _ in direct), "".join(err for _, _, err in direct)))
|
|
|
|
def test_one_bash_call_starts_one_python_per_hook_event(self):
|
|
data = self._patch()
|
|
(Path(self.tmp.name) / "skills").symlink_to(REPO_ROOT / "skills")
|
|
counter = Path(self.tmp.name) / "started"
|
|
fake = Path(self.tmp.name) / "python3"
|
|
fake.write_text(f'#!/bin/sh\necho started >> "{counter}"\nexec /usr/bin/python3 "$@"\n', encoding="utf-8")
|
|
fake.chmod(0o755)
|
|
for event in ("PreToolUse", "PostToolUse"):
|
|
with self.subTest(event=event):
|
|
counter.unlink(missing_ok=True)
|
|
commands = [hook["command"] for entry in self.bash_entries(data, event) for hook in entry["hooks"]]
|
|
for n, command in enumerate(commands):
|
|
self.answer(command.replace("/usr/bin/python3", str(fake)), Path(self.tmp.name) / f"count-{event}-{n}", event)
|
|
self.assertEqual(counter.read_text(encoding="utf-8").count("started"), 1)
|
|
|
|
def test_the_six_separate_bash_entries_are_rewritten_to_two(self):
|
|
base = Path(self.tmp.name) / "skills"
|
|
|
|
def entry(matcher: str | None, script: str, sub: str) -> dict:
|
|
hook = {"type": "command", "command": f'[ -f "{base}/{script}" ] && /usr/bin/python3 -I "{base}/{script}" {sub}'}
|
|
return {"matcher": matcher, "hooks": [hook]} if matcher else {"hooks": [hook]}
|
|
|
|
self.settings.write_text(json.dumps({"hooks": {
|
|
"PreToolUse": [
|
|
entry("Edit|Write|MultiEdit|NotebookEdit|Bash", "kvb-org-radio/scripts/radio.py", "block"),
|
|
entry("Bash", "kvb-org-organize/scripts/watch.py", "block"),
|
|
entry("Bash", "kvb-org-queue/scripts/queue.py", "block"),
|
|
entry(None, "kvb-agent-optimize/scripts/graph.py", "hook"),
|
|
],
|
|
"PostToolUse": [entry("Bash", "kvb-org-organize/scripts/watch.py", "watch"), entry("Bash", "kvb-org-perform/scripts/log.py", "persist")],
|
|
}}), encoding="utf-8")
|
|
data = self._patch()
|
|
for event, sub in (("PreToolUse", "pre-bash"), ("PostToolUse", "post-bash")):
|
|
with self.subTest(event=event):
|
|
commands = [hook["command"] for entry in self.bash_entries(data, event) for hook in entry["hooks"]]
|
|
self.assertEqual(len(commands), 1, commands)
|
|
self.assertTrue(commands[0].endswith(f'kvb-org-organize/scripts/hooks.py" {sub}'))
|
|
(graph,) = [entry for entry in data["hooks"]["PreToolUse"] if any("graph.py" in hook["command"] for hook in entry["hooks"])]
|
|
self.assertEqual(graph["matcher"], "Read|Edit|Write|MultiEdit|NotebookEdit|Grep|Glob")
|
|
self.assertEqual(len(self._hooks(data, "PreToolUse", "kvb-org-radio/scripts/radio.py")), 1)
|
|
|
|
def test_news_hook_moves_to_radio(self):
|
|
base = Path(self.tmp.name) / "skills"
|
|
self.settings.write_text(
|
|
json.dumps({"hooks": {"UserPromptSubmit": [
|
|
{"hooks": [{"type": "command", "command": f'python3 "{base}/kvb-org-organize/scripts/news.py" hook'}]}
|
|
]}}),
|
|
encoding="utf-8",
|
|
)
|
|
data = self._patch()
|
|
self.assertEqual(self._hooks(data, "UserPromptSubmit", "kvb-org-organize/scripts/news.py"), [])
|
|
self.assertEqual(len(self._hooks(data, "UserPromptSubmit", "kvb-org-radio/scripts/radio.py")), 1)
|
|
|
|
def test_code_graph_plugin_is_retired_for_the_agent_agnostic_installer(self):
|
|
self.settings.write_text(
|
|
json.dumps({
|
|
"enabledPlugins": {"codebase-memory@codebase-memory": True},
|
|
"extraKnownMarketplaces": {"codebase-memory": {"source": {"source": "github", "repo": "x/y"}}},
|
|
}),
|
|
encoding="utf-8",
|
|
)
|
|
data = self._patch()
|
|
self.assertIs(data["enabledPlugins"]["codebase-memory@codebase-memory"], False)
|
|
self.assertNotIn("codebase-memory", data["extraKnownMarketplaces"])
|
|
self.assertTrue(data["enabledPlugins"]["caveman@caveman"])
|
|
self.settings.write_text("{}", encoding="utf-8")
|
|
self.assertIs(self._patch()["enabledPlugins"]["codebase-memory@codebase-memory"], False)
|
|
|
|
def test_compact_window_is_set_once_and_never_overwritten(self):
|
|
self.assertEqual(self._patch()["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "300000")
|
|
self.settings.write_text(json.dumps({"env": {"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "500000"}}), encoding="utf-8")
|
|
self.assertEqual(self._patch()["env"]["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "500000")
|
|
|
|
def test_hooks_run_the_system_python_isolated_and_old_entries_move_to_it(self):
|
|
old = f'[ -f "{self.tmp.name}/skills/kvb-org-queue/scripts/queue.py" ] && python3 "{self.tmp.name}/skills/kvb-org-queue/scripts/queue.py" block'
|
|
self.settings.write_text(
|
|
json.dumps({"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": old}]}]}}),
|
|
encoding="utf-8",
|
|
)
|
|
data = self._patch()
|
|
commands = [h["command"] for entries in data["hooks"].values() for e in entries for h in e.get("hooks", [])]
|
|
python = [c for c in commands if ".py" in c]
|
|
self.assertTrue(python)
|
|
for command in python:
|
|
with self.subTest(command=command):
|
|
self.assertIn("/usr/bin/python3 -I ", command)
|
|
self.assertNotRegex(command, r"(^|&& )python3 ")
|
|
self.assertEqual(self._hooks(data, "PreToolUse", "kvb-org-queue/scripts/queue.py"), [])
|
|
(gate,) = self._hooks(data, "PreToolUse", "kvb-org-organize/scripts/hooks.py")
|
|
self.assertIn("spec_from_file_location", gate["command"])
|
|
|
|
def test_reminders_run_the_system_bash_and_old_entries_move_to_it(self):
|
|
old = f'bash "{self.tmp.name}/skills/kvb-dream/hooks/reminder.sh"'
|
|
self.settings.write_text(
|
|
json.dumps({"hooks": {"UserPromptSubmit": [{"hooks": [{"type": "command", "command": old}]}]}}),
|
|
encoding="utf-8",
|
|
)
|
|
data = self._patch()
|
|
reminders = [hook["command"] for hook in self._hooks(data, "UserPromptSubmit", "/hooks/reminder.sh")]
|
|
self.assertEqual(len(reminders), 2)
|
|
for command in reminders:
|
|
with self.subTest(command=command):
|
|
self.assertTrue(command.startswith("/usr/bin/bash "))
|
|
|
|
def test_council_config_and_state_denies_are_added_once_next_to_existing_rules(self):
|
|
self.settings.write_text(json.dumps({"permissions": {"deny": ["Bash(rm -rf:*)"]}}), encoding="utf-8")
|
|
self._patch()
|
|
self.assertEqual(self._patch()["permissions"]["deny"], ["Bash(rm -rf:*)", *DENIED])
|
|
|
|
def _deny(self, path: Path) -> subprocess.CompletedProcess:
|
|
return subprocess.run(["node", str(COUNCIL_DENY), str(path)], capture_output=True, text=True, check=False)
|
|
|
|
def test_the_user_settings_get_the_council_denies_once_and_keep_everything_else(self):
|
|
real = Path(self.tmp.name) / "dotfiles" / "settings.json"
|
|
real.parent.mkdir()
|
|
real.write_text(json.dumps({"model": "opus", "permissions": {"deny": ["Bash(rm -rf:*)"], "ask": ["Bash(git push:*)"]}}), encoding="utf-8")
|
|
real.chmod(0o640)
|
|
self.settings.symlink_to(real)
|
|
for _ in range(2):
|
|
self.assertEqual(self._deny(self.settings).returncode, 0)
|
|
self.assertTrue(self.settings.is_symlink())
|
|
self.assertEqual(real.stat().st_mode & 0o777, 0o640)
|
|
self.assertEqual(
|
|
json.loads(real.read_text(encoding="utf-8")),
|
|
{"model": "opus", "permissions": {"deny": ["Bash(rm -rf:*)", *DENIED], "ask": ["Bash(git push:*)"]}},
|
|
)
|
|
|
|
def test_a_dangling_settings_link_keeps_its_link_and_gets_its_file(self):
|
|
real = Path(self.tmp.name) / "dotfiles" / "settings.json"
|
|
real.parent.mkdir()
|
|
self.settings.symlink_to(real)
|
|
self.assertEqual(self._deny(self.settings).returncode, 0)
|
|
self.assertTrue(self.settings.is_symlink())
|
|
self.assertEqual(real.stat().st_mode & 0o777, 0o600)
|
|
self.assertEqual(json.loads(real.read_text(encoding="utf-8")), {"permissions": {"deny": DENIED}})
|
|
self.assertEqual(sorted(p.name for p in real.parent.iterdir()), ["settings.json"])
|
|
|
|
def test_user_settings_that_are_no_json_object_stay_untouched_and_fail_the_install(self):
|
|
for content in ("{not json", "[]"):
|
|
with self.subTest(content=content):
|
|
self.settings.write_text(content, encoding="utf-8")
|
|
done = self._deny(self.settings)
|
|
self.assertEqual(done.returncode, 1)
|
|
self.assertIn("leaving it untouched", done.stderr)
|
|
self.assertEqual(self.settings.read_text(encoding="utf-8"), content)
|
|
|
|
def test_plugin_skills_are_not_copied_twice(self):
|
|
skills = Path(self.tmp.name) / "skills"
|
|
for name in ("caveman", "ponytail-review", "cavecrew", "archify", "kvb-dream"):
|
|
(skills / name).mkdir(parents=True)
|
|
self._patch()
|
|
self.assertEqual(sorted(p.name for p in skills.iterdir()), ["archify", "kvb-dream"])
|
|
|
|
def test_existing_hooks_preserved(self):
|
|
self.settings.write_text(
|
|
json.dumps({"hooks": {"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "true"}]}]}}),
|
|
encoding="utf-8",
|
|
)
|
|
data = self._patch()
|
|
self.assertIn('"true"', json.dumps(data["hooks"]["UserPromptSubmit"]))
|
|
|
|
def test_tune_reminders_retire_and_dream_reminders_are_repointed(self):
|
|
base = Path(self.tmp.name) / "skills"
|
|
|
|
def hook(command):
|
|
return {"hooks": [{"type": "command", "command": command}]}
|
|
|
|
self.settings.write_text(
|
|
json.dumps(
|
|
{
|
|
"hooks": {
|
|
"UserPromptSubmit": [
|
|
hook(f'bash "{base}/autotune/hooks/reminder.sh"'),
|
|
hook(f'bash "{base}/kvb-skill-tune/hooks/reminder.sh"'),
|
|
hook(f'bash "{base}/kvb-skill-dream/hooks/reminder.sh"'),
|
|
hook(f'python3 "{base}/democracy/scripts/watch.py" watch'),
|
|
hook("echo keep"),
|
|
],
|
|
"PreToolUse": [
|
|
hook(f'python3 "{base}/democracy/scripts/council.py" gate'),
|
|
hook(f'python3 "{base}/democracy/scripts/watch.py" block'),
|
|
hook(f'python3 "{base}/subagent-model/scripts/log.py" spawn'),
|
|
],
|
|
"PostToolUse": [
|
|
hook(f'python3 "{base}/democracy/scripts/watch.py" watch'),
|
|
hook(f'python3 "{base}/subagent-model/scripts/log.py" persist'),
|
|
],
|
|
}
|
|
}
|
|
),
|
|
encoding="utf-8",
|
|
)
|
|
data = self._patch()
|
|
text = json.dumps(data["hooks"])
|
|
for old in ("/autotune/", "/kvb-skill-tune/", "/kvb-skill-dream/", "/democracy/", "/subagent-model/"):
|
|
self.assertNotIn(f"skills{old}", text)
|
|
self.assertIn("echo keep", text)
|
|
self.assertEqual(len(self._hooks(data, "UserPromptSubmit", "kvb-dream/hooks/reminder.sh")), 1)
|
|
self.assertEqual(len(self._hooks(data, "UserPromptSubmit", "kvb-org-organize/scripts/watch.py")), 1)
|
|
self.assertEqual(len(self._hooks(data, "PreToolUse", "kvb-org-organize/scripts/council.py")), 1)
|
|
self.assertEqual(len(self._hooks(data, "PreToolUse", "kvb-org-perform/scripts/log.py")), 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|