feat(hub): answer AskUserQuestion in the hub with a signed pick

The permission hook mirrors every question of an AskUserQuestion call as one hub decision (POST /api/decisions, hooked, multi for multiSelect, recommended from the (Recommended) labels) and waits for its pick. Once the operator's pinned passkey signed the pick of every question, checked locally in signature-counter order, the allow carries updatedInput with the answers, multi picks joined by ', '. A hub that does not answer, an expired decision or a pick whose signature fails leaves the terminal dialog untouched. choosing.picks accepts one label, ordered multi labels joined by a newline, or for a hooked decision one trimmed line of other text; decision_status expires a hooked decision whose wait ran out, and the state view and Match drop expired ones. decision_request shares choice_of with the hook; the answer text moves to signing.choice_text unchanged.

Rebased from its lane base 2754568 onto f95196c: the scan copy's diff against 2aea6d1 would have reverted the release-flash fix, so the bundle was re-exported against 2754568; conflicts in view.py (reasons next to the decision_status filter) and page-match.js (toggles next to epoch and the ux constants) keep both sides. ruff and node --check pass.

Tests: test_hub_questions (210 lines) and test_question_multi_e2e. Written, not run: the full suite runs once on master after all bundles (operator order).

Security: MEDUSA over the staged tree on master: 100, no findings over 17 files; index.html.j2 is not covered and was read by hand (one style rule).

🎯 Fix: 90 %
💥 Break: 5 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

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-22 15:02:23 +00:00
1 parent f95196ca82
commit a6eee78165
18 files changed
+763 -64

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
from unittest import mock
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
from hub_support import iso
from kvb_orchestrator import batches
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-question-multi-shots"))
SENT_AT = 1366
GROUPS = ["Scratch (Recommended)", "Logs", "Worktrees (Recommended)"]
QUESTION = "Which groups go?"
PICKED = f"{GROUPS[0]}\n{GROUPS[2]}"
CAPTURE = """
const posted = [];
const send = window.fetch.bind(window);
window.fetch = async (path, init) => {
if (String(path) === "/api/inbox/approve") {
posted.push(JSON.parse(init.body).items.map((item) => [item.kind, item.id, item.verb, item.label]));
}
return send(path, init);
};
const look = (options, submit) => ({pressed: options.map((option) => option.getAttribute("aria-pressed")), recommended: options.map((option) => option.classList.contains("recommended")), disabled: submit ? submit.disabled : null});
const wide = () => document.documentElement.scrollWidth > window.innerWidth + 1;
"""
MATCH = """(async () => {@HELPERS@@CAPTURE@
const card = await until(() => document.querySelector('#main .match-card.front[data-card="@CARD@"]'), 8000);
if (!card) {
return {error: text(document.getElementById("main"))};
}
const options = () => all(".match-options .option", card);
const pick = card.querySelector(".match-pick");
const before = look(options(), pick);
[0, 2, 1, 1].forEach((index) => options()[index].click());
const toggled = {...look(options(), pick), front: document.querySelector("#main .match-card.front") === card, other: Boolean(card.querySelector(`.match-other input[maxlength="1000"]`))};
pick.click();
const overview = await until(() => document.querySelector("#main .match-overview"), 3000);
const found = {before, toggled, rows: overview ? all("#main .match-decision").map((item) => [item.dataset.card, text(item.querySelector(".match-verdict"))]) : [], wide: wide()};
if (@SEND@) {
document.querySelector("#main .match-release").click();
found.toast = await until(() => all("#toasts .toast").map(text).find((entry) => entry.startsWith("Release")), 15000);
found.posted = posted;
}
return found;
})()"""
INBOX = """(async () => {@HELPERS@@CAPTURE@
const row = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@QUESTION@")), 8000);
if (!row) {
return {error: text(document.getElementById("main"))};
}
const options = all(".options button.option", row);
const submit = row.querySelector(".choice-send");
const before = look(options, submit);
[0, 2].forEach((index) => options[index].click());
const found = {before, toggled: look(options, submit), wide: wide()};
if (@SEND@) {
const shown = new Set(all("#toasts .toast"));
submit.click();
found.toast = await until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith("Choice:")), 20000);
found.gone = Boolean(await until(() => !all("#main .inbox-list > li").some((li) => li.textContent.includes("@QUESTION@")), 20000));
found.posted = posted;
}
return found;
})()"""
OTHER = """(async () => {@HELPERS@@CAPTURE@
const row = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@QUESTION@")), 8000);
if (!row) {
return {error: text(document.getElementById("main"))};
}
const field = row.querySelector(".option.other input");
const found = {field: field ? [field.maxLength, field.getAttribute("aria-label").startsWith("Other answer to ")] : null, wide: wide()};
if (@SEND@) {
field.value = " @TYPED@ ";
const shown = new Set(all("#toasts .toast"));
row.querySelector(".option.other button[type=submit]").click();
found.toast = await until(() => all("#toasts .toast").filter((box) => !shown.has(box)).map(text).find((entry) => entry.startsWith("Choice:")), 20000);
found.posted = posted;
}
return found;
})()"""
TYPED = "Keep the old one"
UNTOUCHED = {"pressed": ["false"] * 3, "recommended": [True, False, True], "disabled": True}
TOGGLED = {"pressed": ["true", "false", "true"], "recommended": [True, False, True], "disabled": False}
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestQuestionMulti(HubCase):
drive = base.OrchestratorE2ECase.drive
authenticator = base.OrchestratorE2ECase.authenticator
def setUp(self):
super().setUp()
now = time.time()
self.write_council({"work/s1/claim.json": {"office": "work/s1", "session": "s1", "runtime": "claude", "name": "Skills session", "since": iso(now - 86400), "beat": now, "work": "questions"}})
self.decision = self.question(QUESTION, GROUPS, True)
OUT.mkdir(parents=True, exist_ok=True)
def question(self, text: str, labels: list[str], multi: bool) -> str:
body = {"question": text, "options": [{"label": label, "description": ""} for label in labels], "session": "s1", "timeout": 600, "multi": multi}
status, _, answer = self.post_json("/api/decisions", body, self.local())
self.assertEqual(status, 201, answer)
return json.loads(answer)["id"]
def steps(self, probe: str, view: str, fills: dict[str, str]) -> list[dict]:
found = []
for width, height in sorted(base.WIDTHS, key=lambda size: size[0] == SENT_AT):
script = probe.replace("@HELPERS@", base.HELPERS).replace("@CAPTURE@", CAPTURE).replace("@SEND@", "true" if width == SENT_AT else "false")
for name, value in fills.items():
script = script.replace(f"@{name}@", value)
found.append({"width": width, "height": height, "url": f"http://localhost:{self.port}/?{width}{view}", "wait": 1500, "probe": script, "shot": str(OUT / f"chromium-{width}-{view.rsplit('/', 1)[-1]}.png")})
return found
def run_steps(self, probe: str, view: str, decision_id: str, expected: str, question: str = QUESTION) -> list[dict]:
"""Args:
decision_id: the decision the last step answers.
expected: the choice it holds afterwards.
question: the question whose row or card the probe drives.
"""
with mock.patch.object(batches, "UNDO", 0.3):
steps = self.steps(probe, view, {"CARD": f"decision:{decision_id}", "QUESTION": question, "TYPED": TYPED})
data = self.drive(steps, self.authenticator(), "cdp.mjs", os.environ.get("CHROMIUM", "chromium"))
self.settle(lambda: self.httpd.hub.decisions.get(decision_id)["status"] == "decided")
(OUT / f"chromium-{view.rsplit('/', 1)[-1]}.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
self.assertEqual(self.httpd.hub.decisions.get(decision_id)["choice"], expected)
return data["results"]
def test_chromium_match_toggles_a_multi_question_and_releases_the_picked_labels_in_option_order(self):
results = self.run_steps(MATCH, "#tasks/match", self.decision, PICKED)
for found in results:
with self.subTest(sent="posted" in found):
self.assertNotIn("error", found, found)
self.assertEqual((found["before"], found["toggled"]), (UNTOUCHED, {**TOGGLED, "front": True, "other": True}), found)
self.assertEqual(found["rows"], [[f"decision:{self.decision}", f"Accept: {GROUPS[0]}, {GROUPS[2]}"]], found)
self.assertFalse(found["wide"], found)
self.assertTrue(results[-1]["toast"].startswith("Release: 1 decision"), results[-1])
self.assertEqual(results[-1]["posted"], [[["decision", self.decision, "approve", PICKED]]])
def test_chromium_inbox_toggles_a_multi_question_and_sends_the_picked_labels_with_one_signature(self):
results = self.run_steps(INBOX, "#stream/inbox", self.decision, PICKED)
for found in results:
with self.subTest(sent="posted" in found):
self.assertNotIn("error", found, found)
self.assertEqual((found["before"], found["toggled"]), (UNTOUCHED, TOGGLED), found)
self.assertFalse(found["wide"], found)
self.assertTrue(results[-1]["toast"].startswith(f"Choice: {GROUPS[0]}, {GROUPS[2]}") and results[-1]["gone"], results[-1])
self.assertEqual(results[-1]["posted"], [[["decision", self.decision, "approve", PICKED]]])
def test_chromium_inbox_sends_one_trimmed_line_of_other_text_for_a_hook_question(self):
branch = "Name the branch?"
single = self.question(branch, ["main", "dev"], False)
results = self.run_steps(OTHER, "#stream/inbox", single, TYPED, branch)
for found in results:
with self.subTest(sent="posted" in found):
self.assertNotIn("error", found, found)
self.assertEqual(found["field"], [1000, True], found)
self.assertFalse(found["wide"], found)
self.assertTrue(results[-1]["toast"].startswith(f"Choice: {TYPED}"), results[-1])
self.assertEqual(results[-1]["posted"], [[["decision", single, "approve", TYPED]]])
if __name__ == "__main__":
unittest.main()
+210
View File
@@ -0,0 +1,210 @@
from __future__ import annotations
import json
import subprocess
import sys
import time
import unittest
from unittest import mock
from hub_case import HubCase
from hub_support import CLIENT, HOOK, PRESENT, Key, key
from kvb_orchestrator import batches
PICK = "Execute (Recommended)"
QUESTION = {
"question": "Clean up the two worktrees?",
"header": "Cleanup",
"options": [{"label": PICK, "description": "Both are merged"}, {"label": "Keep", "description": "Nothing changes", "preview": "a\nb"}],
"multiSelect": False,
}
SECOND = {"question": "Post the report?", "header": "Report", "options": [{"label": "Post", "description": ""}, {"label": "Skip", "description": ""}], "multiSelect": False}
GROUPS = ["Scratch (Recommended)", "Logs", "Worktrees (Recommended)"]
MULTI = {"question": "Which groups go?", "header": "Groups", "options": [{"label": label, "description": ""} for label in GROUPS], "multiSelect": True}
ASKED = {**HOOK, "tool_name": "AskUserQuestion", "tool_input": {"questions": [QUESTION, SECOND]}}
BODY = {"question": QUESTION["question"], "options": [{"label": PICK, "description": "Both are merged"}], "session": "s1", "timeout": 60, "multi": False}
MULTI_BODY = {**BODY, "question": MULTI["question"], "options": MULTI["options"], "multi": True}
class TestHubQuestions(HubCase):
def ask_question(self, payload: dict) -> str:
status, _, body = self.post_json("/api/decisions", payload, self.local())
self.assertEqual(status, 201, body)
return json.loads(body)["id"]
def state(self, decision_id: str) -> dict:
status, _, body = self.get(f"/api/decisions/{decision_id}?wait=0")
self.assertEqual(status, 200, body)
return json.loads(body)
def pick(self, decision_id: str, label: str, signer: Key) -> None:
self.counted(decision_id, label, signer, 0)
def counted(self, decision_id: str, label: str, signer: Key, count: int) -> None:
"""Args:
count: the signature counter the authenticator reports.
"""
items = [self.entry("decision", decision_id, label, "")]
payload = self.prepare(items)["payload"]
proof = {"payload": payload, "assertion": signer.assertion(payload, self.origin, "localhost", PRESENT, count)}
with mock.patch.object(batches, "UNDO", 0.05):
status, _, body = self.approve(items, proof)
self.assertEqual(status, 202, body)
self.settle(lambda: self.state(decision_id)["status"] == "decided")
def hook(self, payload: dict, timeout: str) -> subprocess.Popen:
trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json")]
process = subprocess.Popen([sys.executable, str(CLIENT), "--port", str(self.port), "--timeout", timeout, *trust], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
process.stdin.write(json.dumps(payload))
process.stdin.close()
self.addCleanup(process.stdout.close)
self.addCleanup(process.stderr.close)
return process
def waiting(self, count: int) -> list[dict]:
deadline = time.monotonic() + 20
while time.monotonic() < deadline:
found = [item for item in self.snapshot()["inbox"] if item["kind"] == "decision"]
if len(found) >= count:
return sorted(found, key=lambda item: item["ts"])
time.sleep(0.05)
self.fail("the questions did not arrive")
def test_a_question_is_a_local_expiring_decision_card_in_the_inbox_and_on_match(self):
self.claim("s1", "Skills session")
for headers in ({"Host": self.host}, {**self.local(), "Origin": "http://evil.example"}):
with self.subTest(headers=headers):
self.assertEqual(self.post_json("/api/decisions", BODY, headers)[0], 403)
for payload in ({**BODY, "extra": 1}, {**BODY, "session": " "}, {**BODY, "options": []}, {**BODY, "timeout": -1}, {**BODY, "multi": "yes"}, {name: value for name, value in BODY.items() if name != "session"}):
with self.subTest(payload=payload):
self.assertEqual(self.post_json("/api/decisions", payload, self.local())[0], 400)
decision_id = self.ask_question(BODY)
self.assertEqual(self.state(decision_id), {"id": decision_id, "status": "pending", "choice": None, "proof": None, "to": "Skills"})
item = next(item for item in self.snapshot()["inbox"] if item["id"] == decision_id)
self.assertEqual((item["kind"], item["agent"], item["recommended"]), ("decision", "Skills", PICK))
cards = json.loads(self.get("/api/match")[2])["cards"]
self.assertEqual([card["kind"] for card in cards if card["ref"] == decision_id], ["decision"])
self.assertEqual(self.get(f"/api/decisions/{self.decision('')}?wait=0")[0], 404)
self.assertEqual(self.get("/api/decisions/0123456789abcdef?wait=0")[0], 404)
expired = self.ask_question({**BODY, "timeout": 0})
self.assertEqual(self.state(expired)["status"], "expired")
self.assertNotIn(expired, [item["id"] for item in self.snapshot()["inbox"]])
self.assertNotIn(f"decision:{expired}", [card["id"] for card in json.loads(self.get("/api/match")[2])["cards"]])
self.assertNotIn(expired, [row["id"] for row in self.snapshot()["decisions"]])
self.assertEqual(self.approve([self.entry("decision", expired, PICK, "")], None)[0], 409)
def test_a_signed_pick_is_kept_for_the_hook_and_posts_nothing(self):
self.claim("s1", "Skills session")
signer = self.pin()
decision_id = self.ask_question(BODY)
self.pick(decision_id, PICK, signer)
state = self.state(decision_id)
self.assertEqual((state["status"], state["choice"], state["to"]), ("decided", PICK, "Skills"))
self.assertEqual(set(state["proof"]), {"payload", "assertion"})
self.assertEqual(self.scripts.calls, [])
self.assertEqual(self.snapshot()["messages"], [])
def test_a_multi_question_takes_one_or_more_labels_in_option_order_and_recommends_every_marked_one(self):
self.claim("s1", "Skills session")
signer = self.pin()
decision_id = self.ask_question(MULTI_BODY)
item = next(item for item in self.snapshot()["inbox"] if item["id"] == decision_id)
self.assertEqual((item["multi"], item["recommended"]), (True, f"{GROUPS[0]}\n{GROUPS[2]}"))
card = next(card for card in json.loads(self.get("/api/match")[2])["cards"] if card["ref"] == decision_id)
self.assertEqual((card["multi"], card["recommended"]), (True, item["recommended"]))
for label in ("", f"{GROUPS[2]}\n{GROUPS[0]}", f"{GROUPS[0]}\n{GROUPS[0]}", f"{GROUPS[0]}\nOther", f"{GROUPS[0]}\n"):
with self.subTest(label=label):
self.assertEqual(self.approve([self.entry("decision", decision_id, label, "")], None)[0], 400)
self.pick(decision_id, f"{GROUPS[1]}\n{GROUPS[2]}", signer)
self.assertEqual(self.state(decision_id)["choice"], f"{GROUPS[1]}\n{GROUPS[2]}")
single = self.ask_question(BODY)
self.assertEqual(self.approve([self.entry("decision", single, f"{PICK}\n{PICK}", "")], None)[0], 400)
def test_a_hook_question_also_takes_one_trimmed_line_of_other_text_and_an_mcp_decision_does_not(self):
self.claim("s1", "Skills session")
signer = self.pin()
single, multi, mcp = self.ask_question(BODY), self.ask_question(MULTI_BODY), self.decision("")
item = next(item for item in self.snapshot()["inbox"] if item["id"] == mcp)
self.assertFalse(item["other"])
self.assertTrue(next(item for item in self.snapshot()["inbox"] if item["id"] == single)["other"])
for decision_id, label in ((single, " padded"), (single, "x" * 1001), (single, "tab\there"), (mcp, "free text")):
with self.subTest(label=label[:20]):
self.assertEqual(self.approve([self.entry("decision", decision_id, label, "")], None)[0], 400)
self.pick(single, "Keep the old one", signer)
self.pick(multi, "None of these", signer)
self.assertEqual((self.state(single)["choice"], self.state(multi)["choice"]), ("Keep the old one", "None of these"))
def test_the_hook_passes_a_signed_other_text_on_as_the_answer(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook({**ASKED, "tool_input": {"questions": [QUESTION, MULTI]}}, "20")
first, second = self.waiting(2)
self.pick(first["id"], "Only the first one", signer)
self.pick(second["id"], "Logs only, keep the rest", signer)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision["updatedInput"]["answers"], {QUESTION["question"]: "Only the first one", MULTI["question"]: "Logs only, keep the rest"})
def test_the_hook_answers_a_multi_select_question_with_the_picked_labels_joined_by_commas(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook({**ASKED, "tool_input": {"questions": [MULTI]}}, "20")
card = self.waiting(1)[0]
self.assertTrue(card["multi"])
self.pick(card["id"], f"{GROUPS[0]}\n{GROUPS[2]}", signer)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision["updatedInput"]["answers"], {MULTI["question"]: f"{GROUPS[0]}, {GROUPS[2]}"})
def test_the_hook_answers_every_question_with_the_signed_picks(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook(ASKED, "20")
first, second = self.waiting(2)
self.assertEqual([option["label"] for option in first["options"]], [PICK, "Keep"])
self.assertEqual(first["options"][1]["preview"], "a\nb")
self.pick(first["id"], PICK, signer)
self.pick(second["id"], "Skip", signer)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision, {"behavior": "allow", "updatedInput": {"questions": [QUESTION, SECOND], "answers": {QUESTION["question"]: PICK, SECOND["question"]: "Skip"}}})
def test_the_hook_takes_the_picks_of_a_counting_authenticator_signed_out_of_question_order(self):
self.claim("s1", "Skills session")
signer = self.pin()
process = self.hook(ASKED, "20")
first, second = self.waiting(2)
self.counted(second["id"], "Skip", signer, 1)
self.counted(first["id"], PICK, signer, 2)
process.wait(30)
decision = json.loads(process.stdout.read())["hookSpecificOutput"]["decision"]
self.assertEqual(decision["updatedInput"]["answers"], {QUESTION["question"]: PICK, SECOND["question"]: "Skip"})
def test_the_hook_leaves_the_question_to_the_terminal_without_a_pinned_signature_over_the_pick(self):
self.claim("s1", "Skills session")
signer = self.pin()
single = {**ASKED, "tool_input": {"questions": [QUESTION]}}
relayed = {
"unpinned key": lambda card: (PICK, self.signed([self.entry("decision", card, PICK, "")], key(-8, "stranger"))),
"no proof": lambda card: (PICK, None),
"other label": lambda card: (PICK, self.signed([self.entry("decision", card, "Keep", "")], signer)),
}
for case, relay in relayed.items():
with self.subTest(case=case):
process = self.hook(single, "20")
card = self.waiting(1)[0]["id"]
choice, proof = relay(card)
self.httpd.hub.decisions.decide(card, {"status": "decided", "choice": choice, "proof": proof})
process.wait(30)
self.assertEqual((process.returncode, process.stdout.read()), (0, ""))
process = self.hook({**ASKED, "tool_input": {"questions": [{**QUESTION, "options": "Keep"}]}}, "20")
process.wait(30)
self.assertEqual((process.returncode, process.stdout.read()), (0, ""))
self.assertEqual(len(self.httpd.hub.decisions.listed()), len(relayed))
process = self.hook(single, "0.5")
process.wait(30)
self.assertEqual((process.returncode, process.stdout.read()), (0, ""))
if __name__ == "__main__":
unittest.main()