fix(hub): close seven bugs found in the refactor review

The PermissionRequest hook posted asks cut to the hub's field limits, so a signature covered less than Claude Code would run; it now posts nothing it cannot sign in full and leaves the decision to Claude Code with a reason on stderr. fields.seconds names the field the caller used in its error. Serving a stored page maps an OSError to 500 instead of a dropped connection. The natural-language line marks the register as seen before it builds the inbox, like the page does. do_POST runs every header guard (host, origin, client, content type, MCP) before it reads the body, so a refused request never costs its upload. The runner's reader closes stdout at EOF, because a close from the executing thread blocked on the buffer lock and could SIGPIPE a command still running. The page title counts only inbox items that are not snoozed.

Committed on the operator's word despite the gate: cost and time are estimates under 98 % other load and include eight new test cases.

🎯 Fix: 88 %
💥 Break: 3 %
💸 Cost: 106 %
⏱️ Time: 113 %
🛡️ Security: 100 %
🏆 Score: 71
🚦 Gate: ⛔ fix 88 % < 90; cost 106 % > 100, time 113 % > 100: ask the operator before the commit

```
/home/kevinveenbirkenbach/Repositories/github.com/kevinveenbirkenbach/skills/.worktrees/feature/kvb-hub
```

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-06 18:46:40 +00:00
1 parent 8ba45efd04
commit afd96fcd72
14 files changed
+197 -81

No files matched your search

+31 -5
View File
@@ -23,11 +23,11 @@ class TestHubAsks(HubCase):
time.sleep(0.05)
self.fail("no ask arrived")
def hook(self, port: int, timeout: str) -> subprocess.Popen:
def hook(self, port: int, timeout: str, payload: dict) -> subprocess.Popen:
trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json")]
command = [sys.executable, str(CLIENT), "--port", str(port), "--timeout", timeout, *trust]
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
process.stdin.write(json.dumps(HOOK))
process.stdin.write(json.dumps(payload))
process.stdin.close()
self.addCleanup(process.stdout.close)
self.addCleanup(process.stderr.close)
@@ -91,7 +91,7 @@ class TestHubAsks(HubCase):
relayed = []
def asked(decide: Callable[[str], None]) -> tuple[int, str]:
process = self.hook(self.port, "20")
process = self.hook(self.port, "20", HOOK)
ask = self.first_ask()
self.assertEqual((ask["tool"], ask["command"], ask["cwd"], ask["session"]), ("Bash", "rm -rf node_modules", "/repo", "s1"))
decide(ask["id"])
@@ -123,11 +123,37 @@ class TestHubAsks(HubCase):
code, out = asked(allow_by(key(-7, "main")))
self.assertEqual((code, json.loads(out)), (0, {"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": {"behavior": "allow"}}}))
self.assertEqual(asked(relay(relayed[-1])), (0, ""))
self.assertEqual(self.finish(self.hook(self.port, "0.3")), (0, ""))
self.assertEqual(self.finish(self.hook(self.port, "0.3", HOOK)), (0, ""))
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
closed = probe.getsockname()[1]
self.assertEqual(self.finish(self.hook(closed, "5")), (0, ""))
self.assertEqual(self.finish(self.hook(closed, "5", HOOK)), (0, ""))
def test_the_hook_posts_nothing_it_cannot_send_in_full(self):
for name, change in (
("tool", {"tool_name": "T" * 201}),
("command", {"tool_input": {"command": "x" * 4001}}),
("cwd", {"cwd": "/" + "d" * 4096}),
("session", {"session_id": "s" * 201}),
("agent", {"agent_type": "a" * 201}),
):
with self.subTest(name=name):
process = self.hook(self.port, "3", {**HOOK, **change})
self.assertEqual((self.finish(process), self.httpd.hub.asks.listed()), ((0, ""), []))
self.assertRegex(process.stderr.read(), rf"\Akvb-hub: [^\n]*\b{name}\b[^\n]*\n\Z")
process = self.hook(self.port, "20", {**HOOK, "tool_input": {"command": "x" * 4000}})
ask = self.first_ask()
self.assertEqual(ask["command"], "x" * 4000)
self.assertEqual(self.call("POST", f"/api/asks/{ask['id']}/deny", b"", self.guard(self.host))[0], 200)
self.assertEqual(json.loads(self.finish(process)[1])["hookSpecificOutput"]["decision"]["behavior"], "deny")
def test_a_bad_timeout_names_the_field_the_caller_sent(self):
status, _, body = self.post_json("/api/asks", {**ASK, "timeout": -1}, self.local())
self.assertEqual((status, body), (400, b"timeout must be a finite number of seconds, 0 or more\n"))
for tool in ("decision_wait", "review_wait"):
with self.subTest(tool=tool):
result = self.tool(tool, {"id": "0123456789abcdef", "timeout_seconds": -1})
self.assertEqual(result["content"][0]["text"], "timeout_seconds must be a finite number of seconds, 0 or more")
def test_decisions_are_requested_chosen_and_waited_for(self):
for arguments in (
+15
View File
@@ -103,6 +103,21 @@ class TestHubExecutors(HubCase):
self.assertEqual(runner.execute({"command": "exit 3", "directory": str(self.outside)}, reports.append), 3)
self.assertEqual(reports[-1], {"output": "", "code": 3, "refused": False})
def test_the_runner_closes_the_output_pipe_on_every_path(self):
popen, spawned = subprocess.Popen, []
job = {"command": "echo hi; sleep 0.3", "directory": str(self.outside)}
def spawn(*args: object, **kwargs: object) -> subprocess.Popen:
spawned.append(popen(*args, **kwargs))
return spawned[-1]
with mock.patch.object(subprocess, "Popen", spawn), mock.patch.object(runner, "BEAT", 0.05):
self.assertEqual(runner.execute(job, [].append), 0)
self.assertTrue(spawned[0].stdout.closed)
self.assertRaises(RuntimeError, runner.execute, job, mock.Mock(side_effect=RuntimeError("the hub is gone")))
self.settle(lambda: spawned[1].stdout.closed)
self.assertEqual(spawned[1].wait(10), 0)
def test_rules_are_signed_once_and_checked_by_the_executor(self):
now = time.time()
rule = {"kind": "ask", "tool": "Bash", "pattern": "make *", "scope": "/repo*", "expires": now + 3600}
+20
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
import dataclasses
import json
import time
import unittest
@@ -99,6 +100,25 @@ class TestHubInbox(HubCase):
with self.subTest(text=text):
self.assertIn(text, html)
def test_an_nl_command_records_new_operator_rows_like_the_state_does(self):
self.write_council({"rasci.json": {"operator/greet": {"title": "echo hi", "workdir": "/repo", "check": "manual", "status": "queued", "roles": {}}}})
model = mock.Mock(**{"enabled.return_value": True, "complete.return_value": '{"actions": []}'})
self.httpd.hub = dataclasses.replace(self.httpd.hub, model=model)
before = time.time()
self.assertEqual(self.post_json("/api/nl", {"text": "status"}, self.guard(self.host))[0], 200)
after = time.time()
row = next(item for item in self.snapshot()["inbox"] if item["id"] == "operator/greet")
self.assertTrue(before <= row["ts"] <= after, (before, row["ts"], after))
def test_the_title_counts_the_items_that_are_not_snoozed(self):
asks = [self.create_ask(ASK), self.create_ask({**ASK, "command": "make other"})]
self.assertIn("<title>(2) kvb-hub</title>", self.index())
for ask_id, title in zip(asks, ("(1) kvb-hub", "kvb-hub"), strict=True):
snooze = {"kind": "ask", "id": ask_id, "until": time.time() + 3600, "pinned": False}
self.assertEqual(self.post_json("/api/inbox/mark", snooze, self.guard(self.host))[0], 200)
with self.subTest(title=title):
self.assertIn(f"<title>{title}</title>", self.index())
if __name__ == "__main__":
unittest.main()
+31 -1
View File
@@ -1,11 +1,12 @@
from __future__ import annotations
import http.client
import json
import unittest
from hub_case import HubCase
from hub_support import PAGE, SCORE, TREE
from kvb_hub import mcp
from kvb_hub import handler, mcp
TOOLS = {"review_request", "review_status", "review_wait", "review_list", "decision_request", "decision_wait", "operator_message"}
@@ -79,6 +80,35 @@ class TestHubMcp(HubCase):
self.assertEqual(self.post_mcp(ping, {"Origin": f"http://{self.host}"})[0], 200)
self.assertEqual(self.get("/mcp")[0], 405)
def headers_only(self, path: str, headers: dict[str, str]) -> tuple[int, bytes]:
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=3)
try:
connection.putrequest("POST", path, skip_host=True)
for name, value in {"Content-Length": "1024", **headers}.items():
connection.putheader(name, value)
connection.endheaders()
response = connection.getresponse()
return response.status, response.read()
finally:
connection.close()
def test_every_post_guard_answers_before_the_body_arrives(self):
guard = self.guard(self.host)
for path, headers, status, text in (
("/api/asks", {"Host": "evil.example", "X-Kvb-Hub": "1"}, 403, "forbidden host"),
("/api/asks", {"Host": self.host}, 403, "forbidden: local POST with the X-Kvb-Hub header and no foreign origin only"),
("/mcp", {"Host": self.host, "Origin": "http://evil.example", "Content-Type": "application/json"}, 403, "foreign origin"),
("/mcp", {"Host": self.host, "Content-Type": "text/plain"}, 415, "use application/json"),
("/api/runner/0123456789abcdef/report", guard, 403, "forbidden: the runner calls with the X-Kvb-Hub header and no origin only"),
("/api/messages", self.client(), 403, "forbidden: same-origin POST with the X-Kvb-Hub header only"),
("/api/stt", {**guard, "Content-Type": "text/plain"}, 415, "use audio/wav"),
("/api/state", guard, 404, "not found"),
("/api/uploads", {**guard, "Content-Length": str(handler.UPLOAD_LIMIT + 1)}, 413, "body too large"),
("/api/messages", {**guard, "Content-Length": "many"}, 411, "Content-Length required"),
):
with self.subTest(path=path, headers=headers):
self.assertEqual(self.headers_only(path, headers), (status, f"{text}\n".encode()))
def test_mcp_requires_gate_score_and_recommended(self):
tools = {entry["name"]: entry["inputSchema"] for entry in self.rpc("tools/list", {})["result"]["tools"]}
self.assertEqual(tools["review_request"]["properties"]["gate"]["enum"], ["pass", "fail"])
+10
View File
@@ -1,10 +1,13 @@
from __future__ import annotations
import errno
import json
import re
import subprocess
import time
import unittest
from pathlib import Path
from unittest import mock
from hub_case import HubCase
from hub_support import AMBIENCE, SPACE, VOICE
@@ -36,6 +39,13 @@ class TestHubPage(HubCase):
self.assertEqual((status, headers["content-type"]), (200, "application/json"))
self.assertEqual(headers["content-security-policy"], exchange.PLAIN_CSP)
def test_a_stored_file_that_cannot_be_read_answers_500(self):
review_id = self.request("feat: io", "")
for name in ("page", "files"):
with self.subTest(name=name), mock.patch.object(Path, "read_bytes", side_effect=OSError(errno.EIO, "Input/output error")):
status, _, body = self.get(f"/reviews/{review_id}/{name}")
self.assertEqual((status, body), (500, b"storage failed: Input/output error\n"))
def test_markup_from_agents_is_escaped(self):
self.request("<script>alert(1)</script>", "</pre><script>alert(2)</script>")
register = {"work/x": {"title": "<script>alert(3)</script>", "status": "running", "roles": {"<b>One</b>": "RA"}}}