diff --git a/orchestrator/client/permission_hook.py b/orchestrator/client/permission_hook.py index 71c25ba..a909a5d 100755 --- a/orchestrator/client/permission_hook.py +++ b/orchestrator/client/permission_hook.py @@ -6,10 +6,17 @@ hook's timeout in settings.json. --approvers: the pinned passkeys, e.g. ~/.config/kvb-orchestrator/approvers.json. --replay: this hook's replay store, outside the hub's reach, e.g. - ~/.local/state/kvb-orchestrator-approvals/hook.json. - stdin: the Claude Code PermissionRequest hook input, or the PostToolUse - input of a call that ran, which report_ran() tells the hub and which - prints nothing. + ~/.local/state/kvb-orchestrator-approvals/hook.json; the closer + tokens live beside it (closer_path()). + --bound: set when the same registration runs this client on CLOSING + too (scripts/orchestrator.sh hook), so the hub keeps a card whose + wait ran out as open in Claude until a closing event ends it; each + registration then carries the session's closer_token(), the only + token a closing report closes its cards with. + stdin: the Claude Code PermissionRequest hook input, or the input of a + CLOSING event: the PostToolUse input of a call that ran, a Stop, + UserPromptSubmit or SessionEnd input, which report_ran() tells the + hub and which prints nothing. Returns: stdout: the PermissionRequest decision JSON: allow only when a pinned @@ -43,6 +50,9 @@ from __future__ import annotations import argparse import json +import os +import re +import secrets import sys import time import urllib.error @@ -73,7 +83,15 @@ SHELL = "Bash" SHELL_KEYS = frozenset({"command", "description", "timeout", "run_in_background"}) OPTION_KEYS = ("label", "description", "preview") RAN_EVENT = "PostToolUse" +SESSION_END = "SessionEnd" +CLOSING = (RAN_EVENT, "Stop", "UserPromptSubmit", SESSION_END) RAN_TIMEOUT = 2.0 +ANSWERS_LIMIT = 8 +QUESTION_LIMIT = 20_000 +ANSWER_LIMIT = 4000 +CLOSERS = "closers" +CLOSER = re.compile(r"[A-Za-z0-9_-]{32,128}") +CLOSER_BYTES = 32 def summary(tool: str, tool_input: object) -> str: @@ -203,34 +221,150 @@ def encoded(payload: dict) -> bytes: def call_key_of(hook: dict) -> str: """Returns: signing.call_key() of the hook input's tool_name and tool_input, the - same for the PermissionRequest and the PostToolUse input of one call; - empty when they cannot be encoded, so the ask goes without it and - never becomes an expired Match card. + same for the PermissionRequest and the PostToolUse input of one call, + an AskUserQuestion input keyed without the answers its PostToolUse + input may carry; empty when they cannot be encoded, so the ask goes + without it and never becomes an expired Match card. """ + tool_input = hook.get("tool_input") + if hook.get("tool_name") == QUESTION_TOOL and isinstance(tool_input, dict): + tool_input = {name: value for name, value in tool_input.items() if name != "answers"} try: - return signing.call_key(hook.get("tool_name"), hook.get("tool_input")) + return signing.call_key(hook.get("tool_name"), tool_input) except (TypeError, ValueError): return "" -def report_ran(base: str, hook: dict) -> None: - """Args: - hook: the PostToolUse input of a call that ran; the hub closes the - oldest still pending ask of that session and call_key_of() as - answered in the terminal. The report approves and denies nothing. +def ran_answers(hook: dict) -> dict[str, str] | None: + """Returns: + The {question: answer} an AskUserQuestion call that ran carries in + its tool_response, else in its tool_input; None for another tool or + no such map of texts within the hub's ANSWERS_LIMIT, QUESTION_LIMIT + and ANSWER_LIMIT, so the report still closes the decisions. """ - key, session = call_key_of(hook), str(hook.get("session_id") or "") - if not key or not session or len(session) > NAME_LIMIT: + if hook.get("tool_name") != QUESTION_TOOL: + return None + for source in (hook.get("tool_response"), hook.get("tool_input")): + answers = source.get("answers") if isinstance(source, dict) else None + if isinstance(answers, dict) and 0 < len(answers) <= ANSWERS_LIMIT and all(isinstance(question, str) and isinstance(answer, str) and len(question) <= QUESTION_LIMIT and len(answer) <= ANSWER_LIMIT for question, answer in answers.items()): + return answers + return None + + +def closer_path(replay: Path, session: str) -> Path | None: + """Args: + replay: --replay, this hook's replay store; the closer tokens live + beside it in CLOSERS, outside the hub's reach. + session: the hook input's session_id. + + Returns: + The file of the session's closer token, one per session id; None for + a session id signing.SESSION refuses, so no id names a path outside + CLOSERS. + """ + return replay.parent / CLOSERS / f"{session}.token" if signing.SESSION.fullmatch(session) else None + + +def read_closer(path: Path) -> str | None: + """Returns: + The closer token the file at path holds, None when there is none. + + Raises: + OSError when path is a link, ValueError when it holds no CLOSER. + """ + try: + handle = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except FileNotFoundError: + return None + with os.fdopen(handle, encoding="ascii", errors="replace") as file: + token = file.read(256) + if not CLOSER.fullmatch(token): + raise ValueError(f"{path} holds no closer token") + return token + + +def closer_token(replay: Path, session: str) -> str: + """Args: + replay: --replay (closer_path()). + session: the hook input's session_id. + + Returns: + The session's closer token, which every registration and every + CLOSING report of the session sends as closer: on first use + secrets.token_urlsafe(CLOSER_BYTES) written to a mode 0600 file and + linked into place, so a file a concurrent hook linked first wins and + no reader sees it half written; empty for a session id closer_path() + refuses, whose cards only a PostToolUse closes. + """ + path = closer_path(replay, session) + if path is None: + return "" + found = read_closer(path) + if found is not None: + return found + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.{secrets.token_hex(8)}") + handle = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + try: + with os.fdopen(handle, "w", encoding="ascii") as file: + file.write(secrets.token_urlsafe(CLOSER_BYTES)) + os.link(temporary, path) + except FileExistsError: + pass + finally: + temporary.unlink(missing_ok=True) + token = read_closer(path) + if token is None: + raise ValueError(f"{path} went away while it was made") + return token + + +def report_ran(base: str, hook: dict, replay: Path) -> None: + """Args: + hook: the input of a CLOSING event; the hub closes, of exactly that + session_id, for a PostToolUse the oldest still pending ask and + per question the oldest decision of call_key_of() as answered in + Claude, the decisions with ran_answers(); for Stop and + UserPromptSubmit every still open card of the main agent; for + SessionEnd every one as ended. Every report carries the + session's closer token when its file exists (closer_token()), + and the hub closes a card registered with a closer only for that + token; Stop, UserPromptSubmit and SessionEnd send nothing + without one. SessionEnd deletes the token file after its report, + even a failed one. One POST, no read; the report approves and + denies nothing. + replay: --replay (closer_path()). + """ + event, session = hook.get("hook_event_name"), str(hook.get("session_id") or "") + if event not in CLOSING or not session or len(session) > NAME_LIMIT: return - request = urllib.request.Request(f"{base}/api/asks/ran", data=encoded({"call_key": key, "session": session}), headers={"Content-Type": "application/json", **hub_api.GUARD}, method="POST") - hub_api.call(request, RAN_TIMEOUT) + path = closer_path(replay, session) + try: + token = None if path is None else read_closer(path) + closer = {} if token is None else {"closer": token} + if event == RAN_EVENT: + key, answers = call_key_of(hook), ran_answers(hook) + if not key: + return + body = {"event": event, "call_key": key, "session": session, **({"answers": answers} if answers else {}), **closer} + elif token is None: + return + else: + body = {"event": event, "session": session, **closer} + request = urllib.request.Request(f"{base}/api/asks/ran", data=encoded(body), headers={"Content-Type": "application/json", **hub_api.GUARD}, method="POST") + hub_api.call(request, RAN_TIMEOUT) + finally: + if event == SESSION_END and path is not None: + path.unlink(missing_ok=True) -def create(base: str, ask: dict, timeout: float, shown: dict, key: str) -> str: +def create(base: str, ask: dict, timeout: float, shown: dict, key: str, closers: bool, closer: str) -> str: """Args: key: the call's call_key_of(), sent only when not empty. + closers: --bound, sent as bound only when set. + closer: the session's closer_token(), sent only when not empty. """ - called = {"call_key": key} if key else {} + called = {**({"call_key": key} if key else {}), **({"bound": True} if closers else {}), **({"closer": closer} if closer else {})} data = encoded({**ask, "timeout": timeout, **called, **shown}) if len(data) > hub_limits.DIFF_BODY_LIMIT: print(f"kvb-orchestrator: the ask goes without its diff, its {len(data)} bytes pass the hub's {hub_limits.DIFF_BODY_LIMIT}", file=sys.stderr) @@ -291,9 +425,18 @@ def asked_questions(hook: dict) -> list[dict] | None: return questions -def ask_question(base: str, question: dict, session: str, timeout: float) -> str: +def ask_question(base: str, question: dict, hook: dict, timeout: float, closers: bool, closer: str) -> str: + """Args: + hook: the PermissionRequest input of the AskUserQuestion call; its + session_id, call_key_of() and agent_type (a subagent's) go with + the decision, so the CLOSING events close it. + closers: --bound, sent as bound only when set. + closer: the session's closer_token(), sent only when not empty. + """ options = [{key: option[key] for key in OPTION_KEYS if key in option} if isinstance(option, dict) else option for option in question["options"]] - data = encoded({"question": question["question"], "options": options, "session": session, "timeout": timeout, "multi": question.get("multiSelect") is True}) + key, subagent = call_key_of(hook), str(hook.get("agent_type") or "") + tied = {**({"call_key": key} if key else {}), **({"subagent": subagent} if subagent else {}), **({"bound": True} if closers else {}), **({"closer": closer} if closer else {})} + data = encoded({"question": question["question"], "options": options, "session": str(hook.get("session_id") or ""), "timeout": timeout, "multi": question.get("multiSelect") is True, **tied}) request = urllib.request.Request(f"{base}/api/decisions", data=data, headers={"Content-Type": "application/json", **hub_api.GUARD}, method="POST") decision_id = hub_api.call(request, hub_api.SLACK)["id"] if not isinstance(decision_id, str) or not signing.ID.fullmatch(decision_id): @@ -351,15 +494,14 @@ def signed(answer: dict, decision_id: str, question: dict, trust: verifier.Trust return True -def answers_of(base: str, hook: dict, questions: list[dict], timeout: float, trust: verifier.Trust, deadline: float) -> dict | None: +def answers_of(base: str, hook: dict, questions: list[dict], timeout: float, trust: verifier.Trust, deadline: float, closers: bool, closer: str) -> dict | None: """Returns: The PermissionRequest allow that answers every question with the option the operator picked and signed in the Agent Orchestrator; None as soon as one question goes unanswered or one signature does not hold. """ - session = str(hook.get("session_id") or "") - asked = [(ask_question(base, question, session, timeout), question) for question in questions] + asked = [(ask_question(base, question, hook, timeout, closers, closer), question) for question in questions] picks = [] for decision_id, question in asked: pick = picked(base, decision_id, question, deadline) @@ -378,18 +520,20 @@ def main() -> int: parser.add_argument("--timeout", type=float, required=True) parser.add_argument("--approvers", type=Path, required=True) parser.add_argument("--replay", type=Path, required=True) + parser.add_argument("--bound", action="store_true") args = parser.parse_args() base = hub_api.base_url(args.port) trust = verifier.Trust(approvers=args.approvers, replay=args.replay, origin=signing.origin_of(args.port)) deadline = time.monotonic() + args.timeout try: hook = json.load(sys.stdin) - if hook.get("hook_event_name") == RAN_EVENT: - report_ran(base, hook) + if hook.get("hook_event_name") in CLOSING: + report_ran(base, hook, args.replay) return 0 questions = asked_questions(hook) if questions is not None: - chosen = answers_of(base, hook, questions, args.timeout, trust, deadline) + closer = closer_token(args.replay, str(hook.get("session_id") or "")) if args.bound else "" + chosen = answers_of(base, hook, questions, args.timeout, trust, deadline, args.bound, closer) if chosen is not None: print(json.dumps({"hookSpecificOutput": {"hookEventName": "PermissionRequest", "decision": chosen}})) return 0 @@ -402,7 +546,7 @@ def main() -> int: print(f"kvb-orchestrator: {WORKTREE}", file=sys.stderr) return 0 pinned, shown = commit_diff(ask, staged_diff.rules_root()) - ask_id = create(base, ask, args.timeout, shown, call_key_of(hook)) + ask_id = create(base, ask, args.timeout, shown, call_key_of(hook), args.bound, closer_token(args.replay, ask["session"]) if args.bound else "") answer = {"status": "pending"} while answer["status"] == "pending" and (left := deadline - time.monotonic()) > 0: answer = status(base, ask_id, min(left, POLL)) diff --git a/orchestrator/client/pruning.py b/orchestrator/client/pruning.py index e474f0c..08c58d2 100644 --- a/orchestrator/client/pruning.py +++ b/orchestrator/client/pruning.py @@ -7,7 +7,6 @@ import signing ANNOUNCE = "announce" APPLY = "prune" -TASKS_LIMIT = 50 WINDOW_MIN = 60 SKEW = 300 SENDER = "Operator" @@ -22,14 +21,15 @@ def whole(value: object) -> bool: def checked_tasks(tasks: list[str]) -> list[str]: """Returns: - tasks: 1 to TASKS_LIMIT distinct register slugs signing.TASK matches, - none an operator/ or hotfix/ record. + tasks: at least one distinct register slug signing.TASK matches, + none an operator/ or hotfix/ record; the hub's body limit is the + only bound on their number. Raises: signing.Refused for any other list. """ - if not 1 <= len(tasks) <= TASKS_LIMIT or len(set(tasks)) != len(tasks): - raise signing.Refused(f"a prune names 1 to {TASKS_LIMIT} distinct tasks") + if not tasks or len(set(tasks)) != len(tasks): + raise signing.Refused("a prune names at least one task, each once") if not all(signing.TASK.fullmatch(task) and not task.startswith(RECORDS) for task in tasks): raise signing.Refused("a pruned task is no register task slug outside operator/ and hotfix/") return tasks diff --git a/orchestrator/client/resources.py b/orchestrator/client/resources.py index 083cd0f..42418a2 100755 --- a/orchestrator/client/resources.py +++ b/orchestrator/client/resources.py @@ -20,7 +20,8 @@ whose PCI runtime_status is not active is recorded asleep, and nvidia-smi is not run for it; an awake one nvidia-smi gives no reading for (no driver, a driver mismatch) keeps its name with util - and vram None. In the first minute of a 15-minute bucket, rows older + and vram None and, when nvidia-smi failed, error: its first error + line, which a mean without a reading keeps too. In the first minute of a 15-minute bucket, rows older than 7 days fold into 15-minute means and means older than 90 days into one mean per day, kept forever, each row weighted by the seconds it sampled, the queue keeping the last head and every hung id; a @@ -130,6 +131,7 @@ MEGABYTE = 1_000_000 QUEUE_ARGS = ("list", "--json") ID_TEXT = 64 REASON_TEXT = 240 +ERROR_TEXT = 240 HUNG = "suspect hung (" @@ -176,14 +178,34 @@ def percent(part: float, whole: float | None) -> float | None: return round(100 * part / whole, 1) if whole else None -def command(argv: list[str]) -> str | None: +def first_line(text: str) -> str: + """Returns: + The first line of text holding more than blanks, stripped and cut to + ERROR_TEXT characters; "" for none. + """ + return next((line.strip()[:ERROR_TEXT] for line in text.splitlines() if line.strip()), "") + + +def attempt(argv: list[str]) -> tuple[str | None, str]: + """Returns: + (stdout, "") once argv, run without a shell, exits 0; else (None, + error): the first_line() of its stderr, else of its stdout, else its + exit code, for a missing program " not found" and for one that + fails to start or times out the first_line() of that error. + """ if shutil.which(argv[0]) is None: - return None + return None, f"{argv[0]} not found" try: done = subprocess.run(argv, capture_output=True, text=True, timeout=COMMAND_SECONDS, check=False) - except (OSError, subprocess.SubprocessError): - return None - return done.stdout if done.returncode == 0 else None + except (OSError, subprocess.SubprocessError) as error: + return None, first_line(str(error)) or type(error).__name__ + if done.returncode == 0: + return done.stdout, "" + return None, first_line(done.stderr) or first_line(done.stdout) or f"{argv[0]} exited {done.returncode}" + + +def command(argv: list[str]) -> str | None: + return attempt(argv)[0] def parse_df(text: str) -> list[dict]: @@ -284,11 +306,24 @@ def nvidia_gpus(sys_root: Path) -> list[tuple[str, bool]]: return found -def gpus(sys_root: Path, run: Callable[[list[str]], str | None]) -> list[dict]: +def gpus(sys_root: Path, run: Callable[[list[str]], tuple[str | None, str]]) -> list[dict]: + """Args: + run: attempt() or a stand-in: (stdout, "") of a command that + succeeded, (None, error line) of one that failed. + + Returns: + A row per NVIDIA GPU of nvidia_gpus(): {name, asleep: true} while it + sleeps, else its reading; an awake GPU without one keeps util and + vram None and, when nvidia-smi failed, error, its first error line + (such as "Failed to initialize NVML: Driver/library version + mismatch"). + """ devices = nvidia_gpus(sys_root) awake = [address for address, active in devices if active] - readings = parse_nvidia(run(["nvidia-smi", f"--id={','.join(awake)}", f"--query-gpu={NVIDIA_QUERY}", "--format=csv,noheader,nounits"]) or "") if awake else {} - return [{"name": address, **readings.get(address, UNREAD)} if active else {"name": address, "asleep": True} for address, active in devices] + output, error = run(["nvidia-smi", f"--id={','.join(awake)}", f"--query-gpu={NVIDIA_QUERY}", "--format=csv,noheader,nounits"]) if awake else (None, "") + readings = parse_nvidia(output or "") + unread = {**UNREAD, "error": error} if error else UNREAD + return [{"name": address, **readings.get(address, unread)} if active else {"name": address, "asleep": True} for address, active in devices] def queue(council: Path) -> dict: @@ -414,7 +449,12 @@ def swap_out_since(proc: Path, state: Path, t: int) -> float | None: return round((pages - stored[1]) * PAGE_BYTES / MEGABYTE * 60 / (t - stored[0]), 1) -def sample(proc: Path, sys_root: Path, queued: Callable[[], dict], run: Callable[[list[str]], str | None], state: Path) -> dict: +def sample(proc: Path, sys_root: Path, queued: Callable[[], dict], run: Callable[[list[str]], str | None], probe: Callable[[list[str]], tuple[str | None, str]], state: Path) -> dict: + """Args: + run: command() or a stand-in, for df. + probe: attempt() or a stand-in, for nvidia-smi, whose error line a + GPU without a reading keeps. + """ t = int(time.time()) ram, swap = memory(parse_meminfo(read_text(proc / "meminfo"))) pressure = read_text(proc / "pressure" / "memory") @@ -425,7 +465,7 @@ def sample(proc: Path, sys_root: Path, queued: Callable[[], dict], run: Callable "ram": ram, "swap": swap, "load": parse_loadavg(read_text(proc / "loadavg")), - "gpus": gpus(sys_root, run), + "gpus": gpus(sys_root, probe), "queue": queued(), "psi_some": psi_avg10(pressure, "some"), "psi_full": psi_avg10(pressure, "full"), @@ -479,7 +519,9 @@ def gpu_mean(name: object, readings: list[tuple[int | float, dict]]) -> dict: awake = [(part, reading) for part, reading in readings if reading.get("asleep") is not True] if not awake: return {"name": name, "asleep": True} - return {"name": name, "util": average(means(awake, "util"), 1), "vram_used": whole(means(awake, "vram_used")), "vram_total": whole(means(awake, "vram_total"))} + found = {"name": name, "util": average(means(awake, "util"), 1), "vram_used": whole(means(awake, "vram_used")), "vram_total": whole(means(awake, "vram_total"))} + errors = [reading["error"] for _, reading in awake if isinstance(reading.get("error"), str) and reading["error"]] + return {**found, "error": errors[-1]} if errors and found["util"] is None and found["vram_used"] is None else found def disk_means(rows: list[dict]) -> list[dict]: @@ -931,7 +973,7 @@ def main() -> int: args = parser.parse_args() args.state.mkdir(parents=True, exist_ok=True) if args.command == "sample": - row = sample(args.proc, args.sys, functools.partial(queue_state, args.council, args.queue, command), command, args.state) + row = sample(args.proc, args.sys, functools.partial(queue_state, args.council, args.queue, command), command, attempt, args.state) record(args.state, row, row["t"]) else: count_tokens(args.transcripts, args.council, args.state, time.time(), BUDGET) diff --git a/orchestrator/client/signing.py b/orchestrator/client/signing.py index ecd97e1..6e30e98 100644 --- a/orchestrator/client/signing.py +++ b/orchestrator/client/signing.py @@ -15,6 +15,7 @@ LIFETIME = 900 REVIEW_LIFETIME = 7200 RULE_LIFETIME = 366 * 86400 PRUNE_KIND = "prune" +DISMISS_KIND = "dismiss" PRUNE_WINDOW = 3600 PRUNE_LIFETIME = LIFETIME + PRUNE_WINDOW ALGORITHMS = {-7: "ES256", -8: "EdDSA", -257: "RS256"} @@ -166,6 +167,22 @@ def cleanup_item(repository: str, branch: str, worktree: str, tip: str) -> dict: return {"kind": "cleanup", "repository": repository, "branch": branch, "worktree": worktree, "tip": tip} +def dismiss_item(target: str, item_id: str, request: str, mark: str) -> dict: + """Args: + target: the inbox kind of the dismissed request. + item_id: its id. + request: its request kind as the operator saw it: open, expired, + stale or failed. + mark: the hub's digest of the command and hub job the request + showed. + + Returns: + The item a dismissal signs; the hub acts on it alone and no executor + approves anything by it. + """ + return {"kind": DISMISS_KIND, "target": target, "id": item_id, "request": request, "mark": mark} + + def office_item(action: str, office: str, holder: str, session: str, work: str) -> dict: return {"kind": "office", "action": action, "office": office, "holder": holder, "session": session, "work": work} diff --git a/orchestrator/kvb_orchestrator/approving.py b/orchestrator/kvb_orchestrator/approving.py index 3784347..b4b827b 100644 --- a/orchestrator/kvb_orchestrator/approving.py +++ b/orchestrator/kvb_orchestrator/approving.py @@ -43,6 +43,7 @@ from .signed import ( verifier, ) from .tasking import task_request +from .triage import DISMISS_VERB, dismiss_entry, dismiss_request BATCH_LIMIT = 100 INBOX_KINDS = ("review", "ask", "decision", "operator", "rule") @@ -176,11 +177,16 @@ class Approving: def apply(self, batch: dict) -> None: """Args: - batch: settled item by item; operator rows after every other - item, so a commit row's job never starts before the reviews - its verify steps check are decided. + batch: its dismissals of a Match release first, through + apply_dismissals(), then the rest settled item by item; + operator rows after every other item, so a commit row's job + never starts before the reviews its verify steps check are + decided. """ - for item in sorted(batch["items"], key=lambda item: item["kind"] == "operator"): + dismissed = [item for item in batch["items"] if item["verb"] == DISMISS_VERB] + if dismissed: + self.apply_dismissals({**batch, "items": dismissed}) + for item in sorted((item for item in batch["items"] if item["verb"] != DISMISS_VERB), key=lambda item: item["kind"] == "operator"): try: outcome = self.settle_item(item, batch["proof"] if item["signed"] is not None else None) except (OSError, ToolError) as error: @@ -318,6 +324,29 @@ class Approving: raise Conflict({"status": "held"}) return items + def released(self, raw: object) -> list[dict]: + """Args: + raw: the page's entries: inbox entries (checked()) and the dismiss + entries (dismissable()) of a Match release, which one + signature covers together. + + Returns: + The batch items of the inbox entries, then of the dismissals. + + Raises: + ToolError as checked() for no inbox entry and no dismissal, and + for two items of one request. + """ + dropped = [entry for entry in raw if dismiss_entry(entry)] if isinstance(raw, list) else [] + if not dropped: + return self.checked(raw) + kept = [entry for entry in raw if not dismiss_entry(entry)] + items = (self.checked(kept) if kept else []) + self.dismissable(dropped) + keys = [(item["kind"], item["id"]) for item in items] + if len(set(keys)) != len(keys): + raise ToolError("items must be distinct") + return items + def sign(self, body: bytes) -> dict: payload = decode(body) expect(payload, ("items",)) @@ -338,18 +367,28 @@ class Approving: signed = self.prune_changes(raw) elif settings_request(raw): signed = self.settings_changes(raw) + elif dismiss_request(raw): + signed = [item["signed"] for item in self.dismissable(raw)] elif enable_request(raw): signed = self.enable_items(raw) return {**self.challenge_for(signed), "enables": signed[0]["rule"]} else: - signed = signed_of(self.checked(raw)) + signed = signed_of(self.released(raw)) return self.challenge_for(signed) def approve(self, body: bytes) -> dict: + """Args: + body: {"items", "proof"}: the entries released() takes and the + one passkey assertion over their signed items; the hub + verifies a dismissal's signature itself, since it acts on it. + """ payload = decode(body) expect(payload, ("items", "proof")) - items = self.checked(payload["items"]) + items = self.released(payload["items"]) proof = self.covered(payload["proof"], signed_of(items), time.time()) + for item in items: + if item["verb"] == DISMISS_VERB: + self.operator_proven(proof, item["signed"]) return self.batches.add(items, "operator", proof, self.apply) def undo(self, batch_id: str) -> dict: diff --git a/orchestrator/kvb_orchestrator/asking.py b/orchestrator/kvb_orchestrator/asking.py index 8d3abe3..69cbea9 100644 --- a/orchestrator/kvb_orchestrator/asking.py +++ b/orchestrator/kvb_orchestrator/asking.py @@ -1,5 +1,7 @@ from __future__ import annotations +import hashlib +import hmac import time from .choosing import EVERYONE, PICKED, answer_text, decision_status @@ -12,6 +14,7 @@ from .fields import ( MCP_WAIT_CAP, OPTION_LIMIT, PATH_LIMIT, + TEXT_LIMIT, WAIT_CAP, bounded, decode, @@ -30,6 +33,97 @@ ASK_TEXTS = {"command": COMMAND_LIMIT, "cwd": PATH_LIMIT, "session": 200, "agent ANSWERS = {"allow": "allowed", "deny": "denied"} RECOMMENDED = "(Recommended)" TERMINAL = "terminal" +ENDED = "ended" +IN_CLAUDE = "claude" +IN_CLAUDE_WORDS = "Open in Claude: answer it there; its hook stopped waiting for the hub" +RAN = "PostToolUse" +TURN_ENDS = ("Stop", "UserPromptSubmit") +SESSION_END = "SessionEnd" +CLOSING = (RAN, *TURN_ENDS, SESSION_END) +ANSWERS_LIMIT = 8 +ANSWER_LIMIT = 4000 + + +def dialog_state(record: dict, now: float) -> str: + """Args: + record: an ask or a decision. + now: the current time in epoch seconds. + + Returns: + Where its card stands over the lifecycle of its Claude dialog: + pending while the hook waits for the hub; IN_CLAUDE once the hook + stopped waiting on a bound record (the hook registration closes it + by CLOSING), expired on an unbound one; allowed, denied or decided + once the hub answered; TERMINAL once Claude answered it, ENDED once + its session ended. + """ + if record["status"] != "pending" or record.get("expires", now + 1) > now: + return record["status"] + return IN_CLAUDE if record.get("bound") else "expired" + + +def ran_answers(raw: object) -> dict[str, str]: + """Args: + raw: {question: answer} of an AskUserQuestion call that ran, at most + ANSWERS_LIMIT texts of at most ANSWER_LIMIT characters each. + + Returns: + The answers by stripped question, each answer stripped. + """ + if not isinstance(raw, dict) or len(raw) > ANSWERS_LIMIT or not all(isinstance(question, str) and isinstance(answer, str) and len(question) <= TEXT_LIMIT and len(answer) <= ANSWER_LIMIT for question, answer in raw.items()): + raise ToolError(f"answers must map at most {ANSWERS_LIMIT} questions to answers of at most {ANSWER_LIMIT} characters") + visible([{"question": question, "answer": answer} for question, answer in raw.items()]) + return {question.strip(): answer.strip() for question, answer in raw.items()} + + +def bound_of(payload: dict) -> bool: + """Returns: + The optional bound flag the hook sends when its registration also + closes the session's cards (CLOSING), popped from payload; False when + absent. + """ + bound = payload.pop("bound", False) + if not isinstance(bound, bool): + raise ToolError("bound must be true or false") + return bound + + +def closer_of(payload: dict) -> str: + """Args: + payload: a registration or a close report, holding the optional + closer, the hook's per-session token (permission_hook.closer_token()). + + Returns: + The sha256 hex digest of the closer, popped from payload, the only + form the hub keeps; empty when absent, as an older hook sends it. + """ + if "closer" not in payload: + return "" + token = field(payload, "closer") + payload.pop("closer") + return hashlib.sha256(token.encode()).hexdigest() + + +def closes(record: dict, presented: str) -> bool: + """Args: + record: an ask or a decision. + presented: closer_of() a close report, empty without a closer. + + Returns: + True only when the record stores a closer digest (closer_of() of its + registration) and presented equals it, compared in constant time. + """ + stored = record.get("closer_digest", "") + return bool(stored) and bool(presented) and hmac.compare_digest(stored, presented) + + +def ran_closes(record: dict, presented: str) -> bool: + """Returns: + Whether a RAN report with presented may close the record: by + closes(), or for a record of an older hook, which stores no closer + digest, by its call_key alone. + """ + return closes(record, presented) or not record.get("closer_digest") def ask_state(ask: dict, now: float) -> dict: @@ -95,20 +189,24 @@ class Asking: def ask(self, body: bytes) -> dict: """Args: body: the hook's ask: tool, ASK_TEXTS, timeout, optionally its diff - and sealed patches, and the call's signing.call_key(), which - an older hook leaves out; ask_ran() closes the ask by it. + and sealed patches, the call's signing.call_key(), which + an older hook leaves out (ask_ran() closes the ask by it), + bound (bound_of()) and closer (closer_of()), whose digest + alone the ask keeps as closer_digest. """ payload = decode(body) diff = valid_diff(payload.pop("diff")) if "diff" in payload else None sealed = valid_sealed(payload.pop("sealed"), diff) if "sealed" in payload else {} key = field(payload, "call_key") if "call_key" in payload else "" payload.pop("call_key", None) + bound = bound_of(payload) + closer = closer_of(payload) expect(payload, ("tool", *ASK_TEXTS, "timeout")) values = {name: bounded(payload, name, limit) for name, limit in ASK_TEXTS.items()} visible(values) lifetime = seconds(payload, "timeout", ASK_LIFETIME) created = time.time() - fields = {**values, "tool": field(payload, "tool").strip(), "call_key": key, "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)} + fields = {**values, "tool": field(payload, "tool").strip(), "call_key": key, "bound": bound, "closer_digest": closer, "status": "pending", "decided": None, "proof": None, "diff_files": None if diff is None else len(diff)} with self.asks.changed: ask_id = self.asks.fresh() if diff is not None: @@ -121,28 +219,92 @@ class Asking: def ask_ran(self, body: bytes) -> dict: """Args: - body: {"call_key", "session"}: the PostToolUse report of a tool - call that ran, keyed by signing.call_key(). + body: what a hook of the CLOSING events reports, each with the + session_id of its stdin: {"event": RAN, "call_key", "session"} + and for an AskUserQuestion call its "answers" (ran_answers()) + once a tool call ran, keyed by signing.call_key(); an older + hook sends only call_key and session, which counts as RAN. + {"event", "session"} for a TURN_ENDS event, which ends a turn + with every dialog of the main agent closed (a denial or an + interrupt in Claude), and for SESSION_END. Each optionally + carries closer, the session's token (closer_of()). Returns: - {"closed"}: the id of the oldest ask of that session and key still - pending and created before the report, now TERMINAL, as answered - in the terminal; null when none is. An ask of another session or - one already decided stays as it is. Nothing is approved or + {"asks", "decisions"}: the ids of the records now closed, each + created before the report and of exactly that session. RAN closes + the oldest pending ask of that key and, per question, the oldest + pending decision of that key that ran_closes() admits, the + decision with its answer as choice only when closes() holds, all + TERMINAL (answered in Claude); a TURN_ENDS event closes every + pending record of the main agent that closes() admits TERMINAL, + never one of a subagent, whose dialog may still be open while the + main agent waits; SESSION_END closes every pending record that + closes() admits ENDED. A record of another session, one already + decided or, for TURN_ENDS and SESSION_END, one without the + matching closer digest stays as it is. Nothing is approved or denied, and no signature is relayed. """ payload = decode(body) - expect(payload, ("call_key", "session")) - key = field(payload, "call_key") + event = payload.get("event", RAN) + if not isinstance(event, str) or event not in CLOSING: + raise ToolError(f"event must be one of {', '.join(CLOSING)}") + keyed = event == RAN + optional = ("event", "answers", "closer") if keyed else ("event", "closer") + expect(payload, (*(("call_key",) if keyed else ()), "session", *(name for name in optional if name in payload))) session = bounded(payload, "session", ASK_TEXTS["session"]) if not session: raise ToolError("session must not be empty") + presented = closer_of(payload) now = time.time() - found = sorted((ask for ask in self.asks.pending() if ask.get("call_key") == key and ask["session"] == session and ask["created_ts"] <= now), key=lambda ask: (ask["created_ts"], ask["id"])) + if keyed: + key = field(payload, "call_key") + answers = ran_answers(payload["answers"]) if "answers" in payload else {} + return {"asks": self.close_ran(session, key, presented, now), "decisions": self.close_answered(session, key, answers, presented, now)} + status = ENDED if event == SESSION_END else TERMINAL + main = event in TURN_ENDS + asks = [ask["id"] for ask in self.asks.pending() if ask["session"] == session and ask["created_ts"] <= now and not (main and ask["agent"]) and closes(ask, presented) and self.asks.decide(ask["id"], {"status": status})[1]] + decisions = [decision["id"] for decision in self.decisions.pending() if decision.get("hooked") and decision["session"] == session and decision["created_ts"] <= now and not (main and decision.get("subagent")) and closes(decision, presented) and self.decisions.decide(decision["id"], {"status": status})[1]] + for ask_id in asks: + sealed_file(self.reviews.pages, "ask", ask_id).unlink(missing_ok=True) + return {"asks": asks, "decisions": decisions} + + def close_ran(self, session: str, key: str, presented: str, now: float) -> list[str]: + """Args: + presented: closer_of() the report, empty without a closer. + + Returns: + The id of the oldest pending ask of session and key created by + now that ran_closes() admits, closed TERMINAL; empty when none is. + """ + found = sorted((ask for ask in self.asks.pending() if ask.get("call_key") == key and ask["session"] == session and ask["created_ts"] <= now and ran_closes(ask, presented)), key=lambda ask: (ask["created_ts"], ask["id"])) closed = next((ask["id"] for ask in found if self.asks.decide(ask["id"], {"status": TERMINAL})[1]), None) - if closed is not None: - sealed_file(self.reviews.pages, "ask", closed).unlink(missing_ok=True) - return {"closed": closed} + if closed is None: + return [] + sealed_file(self.reviews.pages, "ask", closed).unlink(missing_ok=True) + return [closed] + + def close_answered(self, session: str, key: str, answers: dict[str, str], presented: str, now: float) -> list[str]: + """Args: + answers: ran_answers() of the call, empty for a call of another + tool. + presented: closer_of() the report, empty without a closer. + + Returns: + The ids of the decisions closed TERMINAL: per question, the + oldest pending decision the hook asked for session and key by + now that ran_closes() admits, its choice the answer to its + question when closes() holds, else None, as when answers lacks + it. + """ + found = sorted((decision for decision in self.decisions.pending() if decision.get("hooked") and decision.get("call_key") == key and decision["session"] == session and decision["created_ts"] <= now and ran_closes(decision, presented)), key=lambda decision: (decision["created_ts"], decision["id"])) + closed: list[str] = [] + asked: set[str] = set() + for decision in found: + choice = answers.get(decision["question"]) if closes(decision, presented) else None + if decision["question"] not in asked and self.decisions.decide(decision["id"], {"status": TERMINAL, "choice": choice})[1]: + asked.add(decision["question"]) + closed.append(decision["id"]) + return closed def ask_wait(self, ask_id: str, query: dict[str, list[str]]) -> dict: wait = instant(query, "wait") @@ -182,9 +344,21 @@ class Asking: multi one takes several options as a pick (choosing.picks), its recommendation is the options labelled RECOMMENDED (the first of them for a single one), and a signed pick is - kept for the hook instead of being posted. + kept for the hook instead of being posted. Optionally the + call's signing.call_key() and subagent, the agent_type of a + subagent's call, by which ask_ran() closes it, bound + (bound_of()) and closer (closer_of()), whose digest alone + the decision keeps as closer_digest; an older hook leaves + them out. """ payload = decode(body) + key = field(payload, "call_key") if "call_key" in payload else "" + subagent = bounded(payload, "subagent", ASK_TEXTS["agent"]) if "subagent" in payload else "" + visible({"subagent": subagent}) + bound = bound_of(payload) + closer = closer_of(payload) + for name in ("call_key", "subagent"): + payload.pop(name, None) expect(payload, ("question", "options", "session", "timeout", "multi")) question, parsed = choice_of(payload) multi = payload["multi"] @@ -200,7 +374,7 @@ class Asking: raise ToolError(f"the asking session's name holds {EVERYONE}") marked = [option["label"] for option in parsed if option["label"].endswith(RECOMMENDED)] recommended = PICKED.join(marked) if multi else next(iter(marked), "") - fields = {"question": question, "options": parsed, "agent": asker, "recommended": recommended, "session": session, "hooked": True, "multi": multi} + fields = {"question": question, "options": parsed, "agent": asker, "recommended": recommended, "session": session, "hooked": True, "multi": multi, "call_key": key, "subagent": subagent, "bound": bound, "closer_digest": closer} record = self.decisions.add({**fields, "status": "pending", "choice": None, "decided": None, "proof": None, "created_ts": created, "expires": created + seconds(payload, "timeout", ASK_LIFETIME)}) return {"id": record["id"], "status": record["status"]} diff --git a/orchestrator/kvb_orchestrator/fields.py b/orchestrator/kvb_orchestrator/fields.py index cbe94b2..4dd4b24 100644 --- a/orchestrator/kvb_orchestrator/fields.py +++ b/orchestrator/kvb_orchestrator/fields.py @@ -33,6 +33,7 @@ FIELDS = { "tool": (re.compile(LINE.format(200)), "one line of 1 to 200 characters"), "id": (re.compile(r"[0-9a-f]{16}"), "an id the Agent Orchestrator returned"), "call_key": (re.compile(r"[0-9a-f]{64}"), "the sha256 hex digest signing.call_key() gives the tool call"), + "closer": (re.compile(r"[A-Za-z0-9_-]{32,128}"), "the hook's closer token of the session, 32 to 128 URL-safe characters"), } diff --git a/orchestrator/kvb_orchestrator/handler.py b/orchestrator/kvb_orchestrator/handler.py index 9af0c00..25fb0be 100644 --- a/orchestrator/kvb_orchestrator/handler.py +++ b/orchestrator/kvb_orchestrator/handler.py @@ -32,6 +32,7 @@ ENTRY = re.compile(r"/api/stream/([0-9]{1,12})") BOARD = re.compile(r"/api/board/([a-z-]{1,32})") UPLOADS = "/api/uploads" MATCH_ROUTE = "/api/match" +CLOSED_ROUTE = "/api/match/closed" PREVIEWS_ROUTE = "/api/runner/previews" RESTART_ROUTE = "/api/runner/restart" MATCH_POSTS = {"/api/match/stale": "match_stale", "/api/match/snapshot": "match_snapshot"} @@ -61,6 +62,7 @@ TASKS_ROUTE = "/api/tasks" GATES_ROUTE = "/api/gates" QUEUE_ROUTE = "/api/queue" PRUNE_ROUTE = "/api/prune" +DISMISS_ROUTE = "/api/requests/dismiss" TOKEN_ROUTE = "/api/cleanup/token" VIEW_ROUTE = "/api/view" USAGE_ROUTE = "/api/usage" @@ -97,7 +99,7 @@ ACCOUNTS_IMPORT = {"/api/accounts/import/preview": "preview", "/api/accounts/imp SCHEDULES_ROUTE = "/api/schedules" LIMITS_ROUTE = "/api/limits" LIMITS_SIGN_ROUTE = "/api/limits/sign" -ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE, LIMITS_SIGN_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, RULE_MATCH_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, QUEUE_ROUTE, PRUNE_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS) +ACTION_POSTS = (ACCOUNTS_ROUTE, *ACCOUNTS_IMPORT, SCHEDULES_ROUTE, LIMITS_SIGN_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, RULE_MATCH_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, QUEUE_ROUTE, PRUNE_ROUTE, DISMISS_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS) class Handler(Exchange): @@ -172,6 +174,8 @@ class Handler(Exchange): self.answer(lambda: served(hub.tree.file.with_name(SKILLS_INDEX)), HTTPStatus.OK) elif path == MATCH_ROUTE: self.answer(hub.match_cards, HTTPStatus.OK) + elif path == CLOSED_ROUTE: + self.answer(hub.match_closed, HTTPStatus.OK) elif path == ACCOUNTS_ROUTE: self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK) elif path == ACCOUNTS_EXPORT: @@ -275,6 +279,8 @@ class Handler(Exchange): return lambda body: self.answer(lambda: hub.change_queue(body), HTTPStatus.ACCEPTED) if path == PRUNE_ROUTE: return lambda body: self.answer(lambda: hub.prune(body), HTTPStatus.ACCEPTED) + if path == DISMISS_ROUTE: + return lambda body: self.answer(lambda: hub.dismiss_requests(body), HTTPStatus.ACCEPTED) if path == TOKEN_ROUTE: return lambda body: self.answer(lambda: hub.token_row(body), HTTPStatus.CREATED) if inbox: diff --git a/orchestrator/kvb_orchestrator/hub.py b/orchestrator/kvb_orchestrator/hub.py index ae4953a..ea3c45a 100644 --- a/orchestrator/kvb_orchestrator/hub.py +++ b/orchestrator/kvb_orchestrator/hub.py @@ -68,6 +68,7 @@ from .tasking import Tasking from .timeline import Timeline from .transcripts import Transcripts from .tree import TREE_HEARTBEAT, Tree +from .triage import Triage from .view import RADIO_WINDOW, View from .viewstore import ViewStore from .voicenotes import VoiceNotes @@ -96,7 +97,7 @@ def environment(templates: Path) -> jinja2.Environment: @dataclass(frozen=True) -class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Queueing, Scheduling, Limiting, Prunes, Firewall, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language): +class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Denying, Requesting, Cleaning, Offices, Tasking, Gating, Queueing, Scheduling, Limiting, Prunes, Firewall, Triage, Inbox, Matching, Previewing, Rules, Jobs, Sources, Timeline, View, Language): council: Path pages: Path public_port: int @@ -150,6 +151,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den live_state: LiveState accounts: Accounts schedule_settings: Schedules + dismissals: Ledger def hosts(self) -> tuple[str, str]: return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}" @@ -252,6 +254,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta answers=Ledger(state / "answers.json"), messages=messages, rule_requests=Ledger(state / "rule-requests.json"), + dismissals=Ledger(state / "dismissals.json"), uploads=uploads, host_state=host_state, transcripts=Transcripts(transcripts), diff --git a/orchestrator/kvb_orchestrator/inbox.py b/orchestrator/kvb_orchestrator/inbox.py index 1a6aa09..3e77279 100644 --- a/orchestrator/kvb_orchestrator/inbox.py +++ b/orchestrator/kvb_orchestrator/inbox.py @@ -3,6 +3,7 @@ from __future__ import annotations import time from .approving import INBOX_KINDS +from .asking import IN_CLAUDE_WORDS from .choosing import answered, decision_status from .council import read_claims from .denying import requester_of @@ -20,7 +21,21 @@ LAPSE_WINDOW = 86400 def item_base() -> dict: - return {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": ""} + return {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": "", "stale": False, "claude": False} + + +def lapsed_item(item: dict, record: dict) -> dict: + """Args: + item: the inbox item of a record lapsed_of() keeps. + record: that ask or decision. + + Returns: + The item with its expires; a bound record's (asking.dialog_state() + IN_CLAUDE) also with claude true and IN_CLAUDE_WORDS as blocked, as + its dialog is open in Claude and the hub learns when it closes. + """ + claude = {"claude": True, "blocked": IN_CLAUDE_WORDS} if record.get("bound") else {} + return {**item, "expires": record["expires"], **claude} def lapsed_of(records: list[dict], now: float, called: bool) -> list[dict]: @@ -54,7 +69,7 @@ class Inbox: created = iso_epoch(review["created"]) or now gate = review.get("gate", "") agent = review.get("agent", "") - fields = {"title": review["title"], "detail": review["branch"], "green": gate == "pass", "gate": gate, "score": review.get("score", ""), "directory": review["worktree"], "agent": agent, "to": requester_of(claims, agent)[0], "diff": review.get("diff_files")} + fields = {"title": review["title"], "detail": review["branch"], "green": gate == "pass", "gate": gate, "score": review.get("score", ""), "directory": review["worktree"], "agent": agent, "to": requester_of(claims, agent)[0], "diff": review.get("diff_files"), "stale": self.review_moved(review)} items.append({**base, "kind": "review", "id": review["id"], "ts": created, **fields}) items += [self.inbox_ask(base, ask, claims, directory) for ask in self.asks.pending() if ask["expires"] > now] items += [decision_item(base, decision) for decision in self.decisions.pending() if decision_status(decision, now) == "pending"] @@ -67,7 +82,7 @@ class Inbox: busy = row["task"] in held answer = self.answers.get(row["task"]) fields = {"answered": answer["label"] if answered(answer, row) else "", "title": row["command"], "detail": row["why"], "agent": adder(tasks[row["task"]]), "to": requester_of(claims, adder(tasks[row["task"]]))[0], "command": row["command"], "directory": row["directory"], "sha256": digest(row["command"]), "check": row["check"], "options": row["options"], "recommended": row["recommended"]} - state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"]), "blocked": row_blocked(row, reasons)} + state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"]), "blocked": row_blocked(row, reasons), "stale": self.row_moved(row)} items.append({**base, "kind": "operator", "id": row["task"], "ts": self.watch.first(row["task"], now), **fields, **state}) listed = {row["task"] for row in rows} for task, job in consoles.items(): @@ -75,7 +90,7 @@ class Inbox: fields = {"title": job["command"], "command": job["command"], "directory": job["directory"], "job": console_of(job), "settled": True} items.append({**base, "kind": "operator", "id": task, "ts": job["created_ts"], **fields}) items += self.request_items(base, now, claims) - return self.marked_items(items, now) + return self.marked_items(self.triaged(items), now) def marked_items(self, items: list[dict], now: float) -> list[dict]: for item in items: @@ -90,15 +105,17 @@ class Inbox: def lapsed_items(self, now: float, directory: Directory) -> list[dict]: """Returns: - An item as inbox() builds it, with its expires, of every ask and - decision lapsed_of() keeps; the Inbox lists none of them, Match - keeps each greyed until the operator denies it. + An item as inbox() builds it, through lapsed_item(), of every ask + and decision lapsed_of() keeps and no dismissal hides; the + snapshot lists them apart from the inbox, Match keeps each greyed + until the operator denies it or, for a bound one, a hook closes + it (asking.CLOSING). """ claims = read_claims(self.council) base = item_base() - asks = [{**self.inbox_ask(base, ask, claims, directory), "expires": ask["expires"]} for ask in lapsed_of(self.asks.pending(), now, True)] - decisions = [{**decision_item(base, decision), "to": requester_of(claims, decision["agent"])[0], "expires": decision["expires"]} for decision in lapsed_of(self.decisions.pending(), now, False)] - return self.marked_items(asks + decisions, now) + asks = [lapsed_item(self.inbox_ask(base, ask, claims, directory), ask) for ask in lapsed_of(self.asks.pending(), now, True)] + decisions = [lapsed_item({**decision_item(base, decision), "to": requester_of(claims, decision["agent"])[0]}, decision) for decision in lapsed_of(self.decisions.pending(), now, False)] + return self.marked_items(self.triaged(asks + decisions), now) def linked(self, command: str) -> list[dict]: """Returns: diff --git a/orchestrator/kvb_orchestrator/ledger.py b/orchestrator/kvb_orchestrator/ledger.py index aeddc83..54db4be 100644 --- a/orchestrator/kvb_orchestrator/ledger.py +++ b/orchestrator/kvb_orchestrator/ledger.py @@ -22,6 +22,7 @@ class Ledger: self.file = file self.changed = threading.Condition() self.items: dict[str, dict] = {} + self.moves = 0 if file.is_file(): self.items = json.loads(file.read_text(encoding="utf-8")) @@ -93,6 +94,7 @@ class Ledger: return dict(record), False updated = {**record, **changes} self.write({**self.items, item_id: updated}) + self.moves += 1 self.changed.notify_all() return dict(updated), True diff --git a/orchestrator/kvb_orchestrator/limiting.py b/orchestrator/kvb_orchestrator/limiting.py index 652283d..fb8cbb8 100644 --- a/orchestrator/kvb_orchestrator/limiting.py +++ b/orchestrator/kvb_orchestrator/limiting.py @@ -121,9 +121,11 @@ class Limiting: def save_limits(self, body: bytes) -> dict: """Args: - body: {limits, proof}: the whole limits object and, when a value - loosens against the limits in force at this save, the - passkey proof over signing.limits_item() of exactly it. + body: {limits, proof}: the whole limits object, which carries a + batch of staged changes at once (requirement 091), and, + when any value of it loosens against the limits in force at + this save, one passkey proof over signing.limits_item() of + exactly it, which covers every looser value of the batch. Returns: limits_view() after the write; ToolError (400) for limits diff --git a/orchestrator/kvb_orchestrator/matching.py b/orchestrator/kvb_orchestrator/matching.py index c651cbc..61dd40f 100644 --- a/orchestrator/kvb_orchestrator/matching.py +++ b/orchestrator/kvb_orchestrator/matching.py @@ -3,6 +3,7 @@ from __future__ import annotations import json import time +from .asking import IN_CLAUDE, IN_CLAUDE_WORDS from .council import NEWS, read_claims from .denying import LAPSED, requester_of from .diffs import stored_diff @@ -38,6 +39,24 @@ def expired_card(card: dict, expires: float) -> dict: return {**card, "blocked": EXPIRED_REASONS[card["kind"]], "blocked_kind": EXPIRED, "expires": expires} +def claude_card(card: dict, expires: float) -> dict: + """Args: + card: the waiting_card() of a bound ask or decision lapsed_of() + keeps (inbox.lapsed_item()). + expires: when its hook stopped waiting, in epoch seconds. + + Returns: + The card greyed with blocked_kind IN_CLAUDE, IN_CLAUDE_WORDS and its + expires time: no stale or expired stamp, as its dialog is still open + in Claude until a hook closes it. + """ + return {**card, "blocked": IN_CLAUDE_WORDS, "blocked_kind": IN_CLAUDE, "expires": expires} + + +def lapsed_card(card: dict, item: dict) -> dict: + return (claude_card if item["claude"] else expired_card)(card, item["expires"]) + + def repository_of(common_dir: str) -> str: return common_dir.removesuffix("/.git") if common_dir.endswith("/.git") else common_dir @@ -66,10 +85,12 @@ class Matching: def match_cards(self) -> dict: """Returns: {"now", "cards"}: every card waiting on the operator, none held - by a release in its undo window or while it applies; a held + by a release in its undo window or while it applies and none + dismissed (Triage.hidden_refs()); a held command card keeps its snapshot, so an undo shows it unchanged; - an expired ask or decision stays, greyed by expired_card(), - until the operator denies it. + an expired ask or decision stays, greyed by lapsed_card(), + until the operator denies it or, for a bound one, a hook closes + it. """ now = time.time() claims = read_claims(self.council) @@ -77,7 +98,9 @@ class Matching: reviews = self.reviews.pending() labels = score_labels(self.scripts.skills) senders = {review["id"]: review.get("agent", "") for review in reviews} - cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"])] + hidden = self.hidden_refs() + consoles = self.consoles() + cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"]) and not self.review_hidden(hidden, review["id"])] tasks = read_register(self.council / REGISTER) blocked = self.blocked_rows(now) kinds = blocked_kinds(self.jobs.listed()) @@ -86,14 +109,14 @@ class Matching: roots = denied_roots(self.settings_files()[0]) scan = self.tree.get() for row in rows: - if f"operator:{row['task']}" in releasing: + if f"operator:{row['task']}" in releasing or self.row_hidden(hidden, row, consoles): continue owner = adder(tasks[row["task"]]) cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0], "blocked": row_blocked(row, blocked), "blocked_kind": row_blocked_kind(row, kinds)}) directory = self.directory(claims, read_jsonl(self.council / NEWS), now) items = self.inbox(now, tasks, directory) cards += [self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels) for item in items if self.waits(item)] - cards += [expired_card(self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels), item["expires"]) for item in self.lapsed_items(now, directory) if self.waits(item)] + cards += [lapsed_card(self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels), item) for item in self.lapsed_items(now, directory) if self.waits(item)] asked = {row["task"] for row in operator_rows(tasks) if row["check"] == "decision"} for answer in self.answers.listed(): if answer["id"] not in asked: @@ -105,15 +128,26 @@ class Matching: store.remove(snapshot["id"]) return {"now": now, "cards": cards} + def match_closed(self) -> dict: + """Returns: + {"closed"}: how many asks, decisions and reviews left pending + since the hub started, read from the ledgers' counters without + building a card or the state; a page that sees it move fetches + Match and the state at once instead of at its next interval. + """ + return {"closed": self.asks.moves + self.decisions.moves + self.reviews.moves} + def match_open(self, inbox: list[dict]) -> int: """Returns: How many cards match_cards() lists that can be decided, by its filters without building them: pending reviews, open command rows - not held by a release and without a row_blocked() reason, and the - inbox items waits() keeps. + not held by a release and without a row_blocked() reason, none + dismissed, and the inbox items waits() keeps. """ - reviews = sum(1 for review in self.reviews.pending() if not self.batches.holds("review", review["id"])) - rows = sum(1 for row in self.open_rows() if not self.batches.holds("operator", row["task"]) and not row_blocked(row, {})) + hidden = self.hidden_refs() + consoles = self.consoles() + reviews = sum(1 for review in self.reviews.pending() if not self.batches.holds("review", review["id"]) and not self.review_hidden(hidden, review["id"])) + rows = sum(1 for row in self.open_rows() if not self.batches.holds("operator", row["task"]) and not row_blocked(row, {}) and not self.row_hidden(hidden, row, consoles)) return reviews + rows + sum(1 for item in inbox if self.waits(item)) def commit_card(self, review: dict, born: float | None, labels: dict | None) -> dict: diff --git a/orchestrator/kvb_orchestrator/settings.py b/orchestrator/kvb_orchestrator/settings.py index f6cd172..bd2f0aa 100644 --- a/orchestrator/kvb_orchestrator/settings.py +++ b/orchestrator/kvb_orchestrator/settings.py @@ -20,11 +20,12 @@ TRENDS = ("off", "regression", "velocity") TREND_DAYS = (1, 365) THRESHOLDS = tuple(range(0, ALWAYS + 1, 10)) WPM = (5, 40) -LATE = ("rates", "morse", "undo", "popups", "agents", "forecast", "match") +LATE = ("rates", "morse", "undo", "popups", "agents", "forecast", "match", "hook") AGENT_SWITCHES = ("sound", "aloud", "bubbles") AGENTS_LIMIT = 200 UNDO_RANGE = (0, 60) MATCH_REFRESH = (1, 60) +HOOK_WAIT = (1, 60) POPUP_SOURCES = ("resources", "mayday", "dream") POPUP_UNTIL = 4102444800 NOTIFY = "notify.json" @@ -62,6 +63,7 @@ SETTINGS = { "agents": {}, "forecast": False, "match": {"refresh": 2}, + "hook": {"wait": 60}, } RATE_CHIP = (2, 9) SPACE_AXES = ("none", "time", "spawn") @@ -217,6 +219,21 @@ def match_setting(raw: object) -> dict: return {"refresh": refresh} +def hook_setting(raw: object) -> dict: + """Args: + raw: {"wait"}: whole minutes the PermissionRequest hook waits for the + hub while Claude shows its own dialog; scripts/orchestrator.sh + hook writes it into the hook's --timeout and its settings.json + timeout, so it applies from the next make orchestrator-hook. + """ + entry = section(raw, "hook", tuple(SETTINGS["hook"])) + low, high = HOOK_WAIT + wait = entry["wait"] + if isinstance(wait, bool) or not isinstance(wait, int) or not low <= wait <= high: + raise ToolError(f"hook.wait must be whole minutes from {low} to {high}") + return {"wait": wait} + + def popups_setting(raw: object) -> dict: data = section(raw, "popups", POPUP_SOURCES) popups = {} @@ -288,6 +305,7 @@ def valid_settings(raw: object) -> dict: "agents": agents_setting(data["agents"]), "forecast": flag(data["forecast"], "forecast"), "match": match_setting(data["match"]), + "hook": hook_setting(data["hook"]), } diff --git a/orchestrator/kvb_orchestrator/timeline.py b/orchestrator/kvb_orchestrator/timeline.py index e0fbc4f..dadf5bd 100644 --- a/orchestrator/kvb_orchestrator/timeline.py +++ b/orchestrator/kvb_orchestrator/timeline.py @@ -2,8 +2,8 @@ from __future__ import annotations import time -from .asking import ask_state -from .choosing import answered, decision_status +from .asking import dialog_state +from .choosing import answered from .council import MAYDAY_ACTIVE, NEWS, message_rows, read_claims, sessions from .crons import cron_event from .errors import Missing, ToolError @@ -69,13 +69,13 @@ class Timeline: ref = {key: review.get(key, "") for key in ("id", "status", "gate", "score", "branch", "worktree", "tree", "files")} rows.append(event({"id": f"review:{review['id']}", "ts": created, "kind": "review", "title": review["title"], "text": review["notes"][:STREAM_CUT], "waiting": review["status"] == "pending", "ref": ref})) for ask in self.asks.listed(): - state = ask_state(ask, now) - if ask["created_ts"] <= end and (state["status"] == "pending" or ask["created_ts"] >= begin): - ref = {"id": ask["id"], "status": state["status"], "cwd": ask["cwd"], "tool": ask["tool"], "warnings": signing.warnings(ask["command"])} + status = dialog_state(ask, now) + if ask["created_ts"] <= end and (status == "pending" or ask["created_ts"] >= begin): + ref = {"id": ask["id"], "status": status, "cwd": ask["cwd"], "tool": ask["tool"], "warnings": signing.warnings(ask["command"])} who = {"agent": directory.at(ask["session"], ask["created_ts"]), "now": directory.now(ask["session"]), "session": ask["session"]} - rows.append(event({"id": f"ask:{ask['id']}", "ts": ask["created_ts"], "kind": "ask", **who, "title": ask["tool"], "text": ask["command"], "waiting": state["status"] == "pending", "ref": ref})) + rows.append(event({"id": f"ask:{ask['id']}", "ts": ask["created_ts"], "kind": "ask", **who, "title": ask["tool"], "text": ask["command"], "waiting": status == "pending", "ref": ref})) for decision in self.decisions.listed(): - status = decision_status(decision, now) + status = dialog_state(decision, now) if decision["created_ts"] <= end and (status == "pending" or decision["created_ts"] >= begin): ref = {**{key: decision.get(key, "") for key in ("id", "choice", "recommended", "options")}, "status": status} text = " · ".join(option["label"] for option in decision["options"]) diff --git a/orchestrator/kvb_orchestrator/triage.py b/orchestrator/kvb_orchestrator/triage.py new file mode 100644 index 0000000..1e94c9e --- /dev/null +++ b/orchestrator/kvb_orchestrator/triage.py @@ -0,0 +1,205 @@ +from __future__ import annotations + +import json +import time + +from .council import NEWS, read_claims +from .errors import Conflict, Missing, ToolError +from .fields import decode, expect +from .jobs import console_of +from .previewing import card_id, merge_hash, review_card +from .records import digest, read_jsonl, shown +from .register import REGISTER, read_register +from .signed import signing + +REQUEST_KINDS = ("open", "expired", "stale", "failed") +ALL = "all" +SCOPES = (*REQUEST_KINDS, ALL) +FAILED_JOBS = ("failed", "refused") +DISMISS_VERB = "dismiss" +DISMISS_KEYS = ("kind", "target", "id", "scope") +DISMISS_LIMIT = 100 +REF_LIMIT = 200 +TITLE_LIMIT = 200 +TITLE_SHOWN = 80 + + +def request_kind(item: dict) -> str: + """Args: + item: an inbox item, or one of lapsed_items(), the only items that + carry expires. + + Returns: + Its one request kind: expired for a lapsed ask or decision, open for + a lapsed bound one (claude), whose dialog is still open in Claude; + failed for an operator row whose last hub job failed or the runner + refused; stale for a review or row whose tree or merge preview moved + since it was added; open for every other request. + """ + if "expires" in item: + return "open" if item["claude"] else "expired" + job = item["job"] + if item["kind"] == "operator" and job is not None and job["status"] in FAILED_JOBS: + return "failed" + return "stale" if item["stale"] else "open" + + +def request_mark(command: str, job: dict | None) -> str: + """Args: + command: the command the request shows, "" for one without. + job: the hub job console it shows, None for none. + + Returns: + What a dismissal binds besides kind and id, so a row whose command + changed or that ran again shows again. + """ + return digest(json.dumps([command, "" if job is None else job["id"]])) + + +def dismiss_entry(entry: object) -> bool: + return isinstance(entry, dict) and entry.get("kind") == signing.DISMISS_KIND + + +def dismiss_request(raw: object) -> bool: + return isinstance(raw, list) and bool(raw) and all(dismiss_entry(entry) for entry in raw) + + +def hides(hidden: tuple[dict[str, str], set[str]], key: str, mark: str) -> bool: + """Args: + hidden: Triage.hidden_refs(). + key: : of a request. + mark: its request_mark(). + """ + dismissed, pending = hidden + return key in pending or dismissed.get(key) == mark + + +class Triage: + def hidden_refs(self) -> tuple[dict[str, str], set[str]]: + """Returns: + The request_mark() of every dismissed request by :, and + the keys a dismissal holds in its undo window; hides() keeps both + out of the snapshot, Match and the badge for every browser. + """ + dismissed = {key: mark for record in self.dismissals.listed() for key, mark in record["refs"].items()} + pending = {f"{item['kind']}:{item['id']}" for batch in self.batches.listed() for item in batch["items"] if item["verb"] == DISMISS_VERB} + return dismissed, pending + + def triaged(self, items: list[dict]) -> list[dict]: + """Returns: + The items hides() keeps, each with its request_kind() as request. + """ + hidden = self.hidden_refs() + return [{**item, "request": request_kind(item)} for item in items if not hides(hidden, f"{item['kind']}:{item['id']}", request_mark(item["command"], item["job"]))] + + def review_hidden(self, hidden: tuple[dict[str, str], set[str]], review_id: str) -> bool: + return hides(hidden, review_card(review_id), request_mark("", None)) + + def row_hidden(self, hidden: tuple[dict[str, str], set[str]], row: dict, consoles: dict[str, dict]) -> bool: + return hides(hidden, card_id(row["task"]), request_mark(row["command"], console_of(consoles.get(row["task"])))) + + def review_moved(self, review: dict) -> bool: + """Returns: + Whether the commit card of a pending review is stale, read from + the ledgers alone: its staged tree changed, or the runner saw its + worktree's HEAD move. + """ + preview = self.merge_previews.get(review_card(review["id"])) or {} + return review.get("live_tree") not in (None, review["tree"]) or bool(preview.get("moved")) + + def row_moved(self, row: dict) -> bool: + """Returns: + Whether the command card of an open row is stale by its merge + preview: the snapshot Match took is bound to another HEAD, merge + base or diff than the preview the runner sent last. A changed + payload file marks only the card, which reads the files. + """ + snapshot = self.match_snapshots.get(card_id(row["task"])) + preview = self.preview_of(row) + if row["check"] == "decision" or snapshot is None or preview is None or not snapshot.get("previewed"): + return False + return snapshot["command_sha256"] == digest(row["command"]) and snapshot["hash"] != merge_hash(row, preview) + + def listed_requests(self) -> dict[str, dict]: + """Returns: + Every request the snapshot lists, the inbox and the lapsed asks + and decisions, by :. + """ + now = time.time() + claims = read_claims(self.council) + directory = self.directory(claims, read_jsonl(self.council / NEWS), now) + items = self.inbox(now, read_register(self.council / REGISTER), directory) + self.lapsed_items(now, directory) + return {f"{item['kind']}:{item['id']}": item for item in items} + + def dismissable(self, raw: object) -> list[dict]: + """Args: + raw: the page's entries, each {"kind": "dismiss", "target", "id", + "scope"}: the inbox kind and id of a request the snapshot + lists, and the chip it is deleted from, one of SCOPES. + + Returns: + One batch item per entry, its signed the dismiss_item() the + passkey signs: a listed request no batch holds whose request + kind is the scope, any kind under the scope all. + + Raises: + ToolError for a malformed entry, Missing for a request the + snapshot no longer lists, Conflict for a held one or one of + another kind than its scope. + """ + if not isinstance(raw, list) or not 1 <= len(raw) <= DISMISS_LIMIT: + raise ToolError(f"items must be a list of 1 to {DISMISS_LIMIT} requests") + listed = self.listed_requests() + chosen: list[dict] = [] + for entry in raw: + if not isinstance(entry, dict): + raise ToolError("every item must be an object with kind, target, id and scope") + expect(entry, DISMISS_KEYS) + target, item_id, scope = entry["target"], entry["id"], entry["scope"] + if not all(isinstance(value, str) and 0 < len(value) <= REF_LIMIT for value in (target, item_id)) or not isinstance(scope, str) or scope not in SCOPES: + raise ToolError(f"target and id must name a listed request and scope be one of {', '.join(SCOPES)}") + item = listed.get(f"{target}:{item_id}") + if item is None: + raise Missing(shown(item_id)[:REF_LIMIT]) + if item["held"]: + raise Conflict({"id": item_id, "status": "held"}) + if scope not in (ALL, item["request"]): + raise Conflict({"id": item_id, "status": item["request"]}) + signed = signing.dismiss_item(target, item_id, item["request"], request_mark(item["command"], item["job"])) + if any(other["signed"] == signed for other in chosen): + raise ToolError("items must be distinct") + chosen.append({"kind": target, "id": item_id, "verb": DISMISS_VERB, "label": "", "sha256": "", "title": shown(item["title"])[:TITLE_LIMIT], "gate": "", "request": item["request"], "signed": signed, "note": None}) + return chosen + + def dismiss_requests(self, body: bytes) -> dict: + """Args: + body: {"items", "proof"}: the page's entries (dismissable()) and + the one passkey assertion over their dismiss items. + + Returns: + The batch in its undo window, without proof and timer; the + requests leave the snapshot at once, /api/inbox/undo brings them + back until apply_dismissals() settles the batch. + """ + payload = decode(body) + expect(payload, ("items", "proof")) + items = self.dismissable(payload["items"]) + self.proven(payload["proof"], [item["signed"] for item in items]) + return self.batches.add(items, "operator", None, self.apply_dismissals) + + def apply_dismissals(self, batch: dict) -> None: + """Args: + batch: dismissed requests past their undo window. Each stays out + of the hub while its request_mark() holds; an open ask whose + hook still waits is also denied without a reason, so its hook + stops waiting for a card nobody sees, while one open in + Claude stays pending for its dialog. No agent gets a radio + message. + """ + now = time.time() + refs = {f"{item['kind']}:{item['id']}": item["signed"]["mark"] for item in batch["items"]} + self.dismissals.add({"refs": refs, "ts": now}) + waiting = [item["id"] for item in batch["items"] if item["kind"] == "ask" and item["request"] == "open" and (self.asks.get(item["id"]) or {"expires": now})["expires"] > now] + denied = [ask_id for ask_id in waiting if self.asks.decide(ask_id, {"status": "denied", "proof": None})[1]] + titles = ", ".join(item["title"][:TITLE_SHOWN] for item in batch["items"]) + self.log.add({"kind": "approval", "title": f"Deleted {len(refs)} requests: {titles}"[:TITLE_LIMIT], "text": f"{len(denied)} open asks denied ({batch['source']})", "ref": {"verb": DISMISS_VERB, "items": sorted(refs), "denied": denied, "source": batch["source"]}}) diff --git a/orchestrator/kvb_orchestrator/view.py b/orchestrator/kvb_orchestrator/view.py index 017b716..3ed0872 100644 --- a/orchestrator/kvb_orchestrator/view.py +++ b/orchestrator/kvb_orchestrator/view.py @@ -156,6 +156,7 @@ class View: "speech": {**self.speech.describe(), "gate": self.speech_gate.state()}, "people": people, "inbox": inbox, + "lapsed": self.lapsed_items(now, directory), "badges": badges(self.match_open(inbox), claims, self.jobs.listed(), now), "pending": self.batches.listed(), "rules": self.rule_rows(now), diff --git a/scripts/orchestrator.sh b/scripts/orchestrator.sh index 244f72a..81808db 100644 --- a/scripts/orchestrator.sh +++ b/scripts/orchestrator.sh @@ -26,9 +26,12 @@ # council.py, nofollow.py, councilroot.py or rasci.py differ from # this tree # hook register the PermissionRequest hook in ~/.claude/settings.json, -# and the same client as async PostToolUse hook that reports a -# call that ran, replacing an earlier entry, keeping everything else and the file -# mode, after a copy to settings.json.before-kvb-orchestrator-hook +# waiting the hub Settings' hook wait (else HOOK_TIMEOUT), and the +# same client as async PostToolUse, Stop and UserPromptSubmit hook +# and as SessionEnd hook, which close the session's cards in the +# hub, replacing an earlier entry, keeping everything else and the +# file mode, after a copy to settings.json.before-kvb-orchestrator-hook; +# refuse while the installed client lacks --bound # idle exit 1 with the hub row's task and job id while runner-job.json # in ~/.local/state/kvb-orchestrator names a live pid, the runner # running that row, which a stop of the runner would kill; exit 0 @@ -48,7 +51,9 @@ COUNCIL="$(python3 "${COUNCIL_ROOT}" root)" KEPT="$(python3 "${COUNCIL_ROOT}" durable)" SETTINGS="${HOME}/.claude/settings.json" LOCAL_SETTINGS="${HOME}/.claude/settings.local.json" -HOOK_TIMEOUT=110 +HOOK_TIMEOUT=3600 +HOOK_WAIT_CAP=3600 +CLOSER_TIMEOUT=10 RUNNER="${NAME}-runner.service" TREE_UNIT="${NAME}-tree" CLEANUP_UNIT="${NAME}-cleanup" @@ -86,7 +91,10 @@ has_systemd() { } # Args: settings file, marker every dropped hook command contains, then -# optionally the command and timeout of the entry to append. +# optionally the command, the PermissionRequest timeout and the timeout of +# the closing hooks (PostToolUse, Stop, UserPromptSubmit, SessionEnd) to +# append; SessionEnd runs in the foreground, since Claude Code may exit +# before an async hook ran. rewrite_hooks() { python3 - "$@" <<'PY' import json, os, sys @@ -95,11 +103,16 @@ from pathlib import Path path, (marker, *added) = Path(sys.argv[1]), sys.argv[2:] settings = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} mode = path.stat().st_mode & 0o777 if path.exists() else 0o600 -for event, extra in (("PermissionRequest", {}), ("PostToolUse", {"async": True})): - entries = settings.setdefault("hooks", {}).setdefault(event, []) - entries[:] = [entry for entry in entries if not any(marker in hook.get("command", "") for hook in entry.get("hooks", []))] +events = {"PermissionRequest": ("*", False), "PostToolUse": ("*", True), "Stop": (None, True), "UserPromptSubmit": (None, True), "SessionEnd": (None, False)} +hooks = settings.setdefault("hooks", {}) +for event, (matcher, background) in events.items(): + entries = [entry for entry in hooks.get(event, []) if not any(marker in hook.get("command", "") for hook in entry.get("hooks", []))] if added: - entries.append({"matcher": "*", "hooks":[{"type": "command", "command": added[0], "timeout": int(added[1]), **extra}]}) + timeout = int(added[1] if event == "PermissionRequest" else added[2]) + hook = {"type": "command", "command": added[0], "timeout": timeout, **({"async": True} if background else {})} + entries.append({**({"matcher": matcher} if matcher else {}), "hooks": [hook]}) + if entries or event in hooks: + hooks[event] = entries temporary = path.with_name(f"{path.name}.{os.getpid()}") temporary.write_text(json.dumps(settings, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") temporary.chmod(mode) @@ -505,12 +518,35 @@ pin() { return "${FAILED}" } +# Args: the hub's settings.json and the fallback in seconds. Prints the +# seconds the PermissionRequest hook waits: the whole minutes of its +# hook.wait times 60 when they lie from 1 to 60, at most HOOK_WAIT_CAP, +# else the fallback. +hook_wait() { + python3 - "$1" "$2" "${HOOK_WAIT_CAP}" <<'PY' +import json, sys +from pathlib import Path + +path, fallback, cap = Path(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) +try: + minutes = json.loads(path.read_text(encoding="utf-8"))["hook"]["wait"] +except (OSError, ValueError, KeyError, TypeError): + minutes = None +print(min(minutes * 60, cap) if type(minutes) is int and 1 <= minutes <= 60 else fallback) +PY +} + hook() { - local command - command="/usr/bin/python3 -E -s \"${HUB}/client/permission_hook.py\" --port $(port_of "${HUB}/.env") --timeout ${HOOK_TIMEOUT} --approvers \"${APPROVERS}/approvers.json\" --replay \"${APPROVALS}/hook.json\"" + local command seconds client="${HUB}/client/permission_hook.py" + if ! grep -qF -- '"--bound"' "${client}"; then + warn "skills: ${client} predates the closing hooks; run make install first, then make orchestrator-hook" + exit 1 + fi + seconds="$(hook_wait "${STATE}/settings.json" "${HOOK_TIMEOUT}")" + command="/usr/bin/python3 -E -s \"${client}\" --port $(port_of "${HUB}/.env") --timeout ${seconds} --approvers \"${APPROVERS}/approvers.json\" --replay \"${APPROVALS}/hook.json\" --bound" [[ -f "${SETTINGS}" ]] && cp -p "${SETTINGS}" "${SETTINGS}.before-${NAME}-hook" - rewrite_hooks "${SETTINGS}" "${NAME}/client/permission_hook.py" "${command}" "$((HOOK_TIMEOUT + 10))" - log "skills: registered the PermissionRequest hook in ${SETTINGS} (copy before: ${SETTINGS}.before-${NAME}-hook); restart Claude Code to load it" + rewrite_hooks "${SETTINGS}" "${NAME}/client/permission_hook.py" "${command}" "$((seconds + 10))" "${CLOSER_TIMEOUT}" + log "skills: registered the PermissionRequest hook (wait ${seconds} s) and its closing hooks in ${SETTINGS} (copy before: ${SETTINGS}.before-${NAME}-hook); restart every Claude Code session to load them" } case "${1:-}" in diff --git a/tests/test_hook_exec_hardening.py b/tests/test_hook_exec_hardening.py index 4e4b0eb..079cea6 100644 --- a/tests/test_hook_exec_hardening.py +++ b/tests/test_hook_exec_hardening.py @@ -507,6 +507,51 @@ class TestPermissionHookInstall(Scratch): self.assertEqual((done.returncode, done.stdout, done.stderr), (0, "", "")) self.assertFalse(self.marker.exists()) + def registered(self, saved: dict | None) -> tuple[subprocess.CompletedProcess, dict]: + home = self.root / "home" + hub = home / ".local" / "share" / "kvb-orchestrator" + shutil.rmtree(home, ignore_errors=True) + shutil.copytree(CLIENT, hub / "client", ignore=shutil.ignore_patterns("__pycache__")) + (hub / ".env").write_text("KVB_ORCHESTRATOR_PORT=1\n", encoding="utf-8") + (home / ".claude").mkdir(parents=True) + if saved is not None: + state = home / ".local" / "state" / "kvb-orchestrator" + state.mkdir(parents=True) + (state / "settings.json").write_text(json.dumps(saved), encoding="utf-8") + done = subprocess.run(["/usr/bin/bash", str(ORCHESTRATOR), "hook"], env={**os.environ, "HOME": str(home)}, capture_output=True, text=True, timeout=60, check=False) + path = home / ".claude" / "settings.json" + return done, json.loads(path.read_text(encoding="utf-8")) if path.is_file() else {} + + def test_the_hook_waits_the_settings_minutes_and_registers_the_closing_hooks_beside_it(self): + for saved, wait in ((None, 3600), ({"hook": {"wait": 5}}, 300), ({"hook": {"wait": 60}}, 3600), ({"hook": {"wait": 61}}, 3600), ({"hook": {"wait": "5"}}, 3600), ({"match": {"refresh": 2}}, 3600)): + with self.subTest(saved=saved): + done, settings = self.registered(saved) + self.assertEqual(done.returncode, 0, done.stderr) + hooks = settings["hooks"] + asked = hooks["PermissionRequest"][-1] + self.assertEqual((asked["matcher"], asked["hooks"][0]["timeout"]), ("*", wait + 10)) + self.assertNotIn("async", asked["hooks"][0]) + command = asked["hooks"][0]["command"] + self.assertIn(f"--timeout {wait} ", command) + self.assertTrue(command.endswith(" --bound"), command) + shapes = {event: (entries[-1].get("matcher"), entries[-1]["hooks"][0]["command"], entries[-1]["hooks"][0]["timeout"], entries[-1]["hooks"][0].get("async", False)) for event, entries in hooks.items() if event != "PermissionRequest"} + self.assertEqual(shapes, {"PostToolUse": ("*", command, 10, True), "Stop": (None, command, 10, True), "UserPromptSubmit": (None, command, 10, True), "SessionEnd": (None, command, 10, False)}) + + def test_a_second_registration_replaces_every_entry_and_a_client_without_bound_is_refused(self): + self.registered(None) + home = self.root / "home" + done = subprocess.run(["/usr/bin/bash", str(ORCHESTRATOR), "hook"], env={**os.environ, "HOME": str(home)}, capture_output=True, text=True, timeout=60, check=False) + self.assertEqual(done.returncode, 0, done.stderr) + settings = json.loads((home / ".claude" / "settings.json").read_text(encoding="utf-8")) + self.assertEqual({event: len(entries) for event, entries in settings["hooks"].items()}, dict.fromkeys(("PermissionRequest", "PostToolUse", "Stop", "UserPromptSubmit", "SessionEnd"), 1)) + client = home / ".local" / "share" / "kvb-orchestrator" / "client" / "permission_hook.py" + client.write_text(client.read_text(encoding="utf-8").replace('"--bound"', '"--other"'), encoding="utf-8") + before = (home / ".claude" / "settings.json").read_text(encoding="utf-8") + done = subprocess.run(["/usr/bin/bash", str(ORCHESTRATOR), "hook"], env={**os.environ, "HOME": str(home)}, capture_output=True, text=True, timeout=60, check=False) + self.assertEqual(done.returncode, 1, done.stderr) + self.assertIn("make install first", done.stderr) + self.assertEqual((home / ".claude" / "settings.json").read_text(encoding="utf-8"), before) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_hub_dialog_bound_cards.py b/tests/test_hub_dialog_bound_cards.py new file mode 100644 index 0000000..2c48fa2 --- /dev/null +++ b/tests/test_hub_dialog_bound_cards.py @@ -0,0 +1,416 @@ +"""Exercise requirement 094: a hub card lives as long as its Claude dialog and closes the moment either side answers.""" + +from __future__ import annotations + +import hashlib +import importlib +import json +import os +import stat +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +from hub_support import ASK, CLIENT, HOOK, signing +from kvb_orchestrator import batches, settings +from kvb_orchestrator.asking import ( + ENDED, + IN_CLAUDE, + IN_CLAUDE_WORDS, + TERMINAL, + dialog_state, +) +from kvb_orchestrator.errors import ToolError +from kvb_orchestrator.inbox import item_base, lapsed_item +from kvb_orchestrator.matching import claude_card, expired_card, lapsed_card +from kvb_orchestrator.triage import request_kind +from test_hub_match import MatchCase + +permission_hook = importlib.import_module("permission_hook") + +KEY = signing.call_key("Bash", {"command": "make deploy"}) +OTHER = signing.call_key("Bash", {"command": "make other"}) +TOKEN = "a" * 43 +FOREIGN_TOKEN = "b" * 43 +WRONG = "c" * 43 +CLOSER = {"closer": TOKEN} +BOUND = {**ASK, "call_key": KEY, "bound": True, **CLOSER} +FIRST = "Clean up the two worktrees?" +SECOND = "Push the branch?" +QUESTIONS = {"questions": [{"question": FIRST, "options": [{"label": "Yes"}, {"label": "No"}]}, {"question": SECOND, "options": [{"label": "Now"}, {"label": "Later"}]}]} +ASKED = signing.call_key("AskUserQuestion", QUESTIONS) +OPTIONS = [{"label": "Yes", "description": ""}, {"label": "No", "description": ""}] + + +def question(text: str, session: str, extra: dict) -> dict: + return {"question": text, "options": OPTIONS, "session": session, "timeout": 600, "multi": False, **extra} + + +class TestCardLifecycle(unittest.TestCase): + def test_a_card_is_open_then_answered_in_the_hub_or_in_claude_or_open_in_claude(self): + now = 10000.0 + live = {"status": "pending", "expires": now + 60, "bound": True} + cases = { + "open": (live, "pending"), + "allowed in the hub": ({**live, "status": "allowed"}, "allowed"), + "denied in the hub": ({**live, "status": "denied"}, "denied"), + "picked in the hub": ({**live, "status": "decided"}, "decided"), + "answered in Claude": ({**live, "status": TERMINAL}, TERMINAL), + "answered in Claude after the wait": ({**live, "status": TERMINAL, "expires": now - 60}, TERMINAL), + "open in Claude": ({**live, "expires": now - 1}, IN_CLAUDE), + "open in Claude at the edge": ({**live, "expires": now}, IN_CLAUDE), + "session ended": ({**live, "status": ENDED, "expires": now - 60}, ENDED), + "unbound after the wait": ({**live, "bound": False, "expires": now - 1}, "expired"), + "older hook after the wait": ({"status": "pending", "expires": now - 1}, "expired"), + "decision without a wait": ({"status": "pending"}, "pending"), + } + for name, (record, state) in cases.items(): + with self.subTest(name=name): + self.assertEqual(dialog_state(record, now), state) + + def test_a_card_open_in_claude_counts_as_open_and_carries_no_stale_or_expired_stamp(self): + record = {"status": "pending", "expires": 990.0, "bound": True} + item = lapsed_item({**item_base(), "kind": "ask", "id": "a1"}, record) + self.assertEqual((item["claude"], item["blocked"], item["expires"], request_kind(item)), (True, IN_CLAUDE_WORDS, 990.0, "open")) + card = lapsed_card({"id": "ask:a1", "kind": "ask", "stale": False}, item) + self.assertEqual(card, claude_card({"id": "ask:a1", "kind": "ask", "stale": False}, 990.0)) + self.assertEqual((card["blocked_kind"], card["blocked"], card["expires"], card["stale"]), (IN_CLAUDE, IN_CLAUDE_WORDS, 990.0, False)) + self.assertTrue(card["blocked"].startswith("Open in Claude: answer it there")) + self.assertNotIn("expired", card["blocked"].lower()) + self.assertNotIn("stale", card["blocked"].lower()) + + def test_an_unbound_lapsed_card_stays_expired_as_080_has_it(self): + item = lapsed_item({**item_base(), "kind": "ask", "id": "a1"}, {"status": "pending", "expires": 990.0}) + self.assertEqual((item["claude"], item["blocked"], request_kind(item)), (False, "", "expired")) + self.assertEqual(lapsed_card({"id": "ask:a1", "kind": "ask", "stale": False}, item), expired_card({"id": "ask:a1", "kind": "ask", "stale": False}, 990.0)) + + +class TestHookWaitSetting(unittest.TestCase): + def test_the_wait_defaults_to_60_minutes_takes_whole_minutes_from_1_to_60_and_an_older_page_keeps_it(self): + self.assertEqual(settings.SETTINGS["hook"], {"wait": 60}) + for good in (1, 30, 60): + with self.subTest(good=good): + self.assertEqual(settings.hook_setting({"wait": good}), {"wait": good}) + for bad in ({"wait": 0}, {"wait": 61}, {"wait": True}, {"wait": "5"}, {"wait": 5.5}, {}, {"wait": 5, "extra": 1}, 5): + with self.subTest(bad=bad), self.assertRaises(ToolError): + settings.hook_setting(bad) + saved = settings.valid_settings({**settings.SETTINGS, "hook": {"wait": 7}}) + older = {key: value for key, value in saved.items() if key != "hook"} + self.assertEqual(settings.valid_settings(settings.completed(older, saved))["hook"], {"wait": 7}) + + +class TestHookClient(unittest.TestCase): + def test_an_ask_user_question_is_keyed_without_the_answers_its_post_tool_use_input_carries(self): + asked = {"tool_name": "AskUserQuestion", "tool_input": QUESTIONS} + answered = {"tool_name": "AskUserQuestion", "tool_input": {**QUESTIONS, "answers": {FIRST: "Yes"}}} + self.assertEqual(permission_hook.call_key_of(asked), ASKED) + self.assertEqual(permission_hook.call_key_of(answered), ASKED) + bash = {"tool_name": "Bash", "tool_input": {"command": "make deploy", "answers": {}}} + self.assertNotEqual(permission_hook.call_key_of(bash), KEY) + + def test_the_answers_come_from_the_tool_response_else_the_tool_input_and_only_within_the_hub_limits(self): + response = {"tool_name": "AskUserQuestion", "tool_input": QUESTIONS, "tool_response": {"questions": QUESTIONS["questions"], "answers": {FIRST: "Yes", SECOND: "Later"}}} + self.assertEqual(permission_hook.ran_answers(response), {FIRST: "Yes", SECOND: "Later"}) + fallback = {"tool_name": "AskUserQuestion", "tool_input": {**QUESTIONS, "answers": {FIRST: "No"}}, "tool_response": "done"} + self.assertEqual(permission_hook.ran_answers(fallback), {FIRST: "No"}) + for bad in ({**response, "tool_name": "Bash"}, {**response, "tool_response": {"answers": {FIRST: "x" * (permission_hook.ANSWER_LIMIT + 1)}}}, {**response, "tool_response": {"answers": {FIRST: 7}}}, {"tool_name": "AskUserQuestion", "tool_input": QUESTIONS}): + with self.subTest(bad=str(bad)[:80]): + self.assertIsNone(permission_hook.ran_answers(bad)) + + +class ClosingCase(MatchCase): + def setUp(self): + super().setUp() + self.claim("s1", "Skills session") + self.claim("s2", "Other session") + + def ran(self, payload: dict) -> tuple[int, dict]: + status, _, body = self.post_json("/api/asks/ran", payload, self.local()) + return status, json.loads(body) if status == 200 else {} + + def closed(self, payload: dict) -> tuple[int, set[str], set[str]]: + status, found = self.ran(payload) + return status, set(found.get("asks", [])), set(found.get("decisions", [])) + + def decide(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 statuses(self) -> dict[str, str]: + return {**{record["id"]: record["status"] for record in self.httpd.hub.asks.listed()}, **{record["id"]: record["status"] for record in self.httpd.hub.decisions.listed()}} + + def shown(self) -> set[str]: + return {card["ref"] for card in self.cards()} + + +class TestClosingEvents(ClosingCase): + def test_post_tool_use_closes_only_the_oldest_ask_of_its_session_and_call_key_as_answered_in_claude(self): + mine, twin = self.create_ask(BOUND), self.create_ask(BOUND) + self.httpd.hub.asks.change(mine, {"created_ts": time.time() - 60}) + foreign, other = self.create_ask({**BOUND, "session": "s2"}), self.create_ask({**BOUND, "call_key": OTHER}) + self.assertEqual(self.ran({"event": "PostToolUse", "call_key": KEY, "session": "s1", **CLOSER}), (200, {"asks": [mine], "decisions": []})) + self.assertEqual(self.statuses(), {mine: TERMINAL, twin: "pending", foreign: "pending", other: "pending"}) + self.assertEqual(self.ask_status(mine, "0"), TERMINAL) + self.assertEqual(self.shown() & {mine, twin, foreign, other}, {twin, foreign, other}) + self.assertEqual([item["id"] for item in self.snapshot()["inbox"] if item["kind"] == "ask"].count(mine), 0) + + def test_post_tool_use_of_an_ask_user_question_closes_its_decisions_with_the_answers_and_no_other_sessions(self): + tied = {"call_key": ASKED, "bound": True, **CLOSER} + first, second = self.decide(question(FIRST, "s1", tied)), self.decide(question(SECOND, "s1", tied)) + foreign, loose = self.decide(question(FIRST, "s2", tied)), self.decide(question(FIRST, "s1", CLOSER)) + report = {"event": "PostToolUse", "call_key": ASKED, "session": "s1", "answers": {f" {FIRST} ": "Yes", SECOND: "Later"}, **CLOSER} + self.assertEqual(self.closed(report), (200, set(), {first, second})) + self.assertEqual(self.statuses(), {first: TERMINAL, second: TERMINAL, foreign: "pending", loose: "pending"}) + self.assertEqual((self.httpd.hub.decisions.get(first)["choice"], self.httpd.hub.decisions.get(second)["choice"]), ("Yes", "Later")) + status, _, body = self.get(f"/api/decisions/{first}?wait=0") + self.assertEqual((status, json.loads(body)["status"], json.loads(body)["proof"]), (200, TERMINAL, None)) + refs = {event["ref"]["id"]: event["ref"] for event in self.events("kinds=decision")["events"]} + self.assertEqual((refs[first]["status"], refs[first]["choice"]), (TERMINAL, "Yes")) + self.assertEqual(self.shown() & {first, second, foreign, loose}, {foreign, loose}) + + def test_stop_and_user_prompt_submit_close_every_open_card_of_the_main_agent_of_their_session_only(self): + for event in ("Stop", "UserPromptSubmit"): + with self.subTest(event=event): + ask, lapsed = self.create_ask(BOUND), self.create_ask({**BOUND, "call_key": OTHER}) + self.httpd.hub.asks.change(lapsed, {"expires": time.time() - 60}) + decision = self.decide(question(FIRST, "s1", {"bound": True, **CLOSER})) + sub, sub_decision = self.create_ask({**BOUND, "agent": "Explore"}), self.decide(question(SECOND, "s1", {"subagent": "Explore", **CLOSER})) + foreign = self.create_ask({**BOUND, "session": "s2"}) + self.assertEqual(self.closed({"event": event, "session": "s1", **CLOSER}), (200, {ask, lapsed}, {decision})) + self.assertEqual({key: value for key, value in self.statuses().items() if key in (ask, lapsed, decision, sub, sub_decision, foreign)}, {ask: TERMINAL, lapsed: TERMINAL, decision: TERMINAL, sub: "pending", sub_decision: "pending", foreign: "pending"}) + self.assertEqual(self.shown() & {ask, lapsed, decision, sub, sub_decision, foreign}, {sub, sub_decision, foreign}) + self.ran({"event": "SessionEnd", "session": "s1", **CLOSER}) + self.ran({"event": "SessionEnd", "session": "s2", **CLOSER}) + + def test_session_end_closes_every_card_of_its_session_as_ended_subagents_included_and_no_other(self): + ask, sub = self.create_ask(BOUND), self.create_ask({**BOUND, "agent": "Explore"}) + decision = self.decide(question(FIRST, "s1", {"subagent": "Explore", "bound": True, **CLOSER})) + foreign, foreign_decision = self.create_ask({**BOUND, "session": "s2"}), self.decide(question(FIRST, "s2", CLOSER)) + self.assertEqual(self.closed({"event": "SessionEnd", "session": "s1", **CLOSER}), (200, {ask, sub}, {decision})) + self.assertEqual(self.statuses(), {ask: ENDED, sub: ENDED, decision: ENDED, foreign: "pending", foreign_decision: "pending"}) + self.assertEqual(self.ran({"event": "SessionEnd", "session": "s1", **CLOSER}), (200, {"asks": [], "decisions": []})) + self.assertEqual(self.shown() & {ask, sub, decision, foreign, foreign_decision}, {foreign, foreign_decision}) + refs = {event["ref"]["id"]: event["ref"]["status"] for event in self.events("kinds=ask")["events"]} + self.assertEqual((refs[ask], refs[foreign]), (ENDED, "pending")) + + def test_a_closing_report_needs_the_local_guard_and_valid_fields_and_never_closes_a_card_created_after_it(self): + ask = self.create_ask(BOUND) + later = self.create_ask({**BOUND, "call_key": OTHER}) + self.httpd.hub.asks.change(later, {"created_ts": time.time() + 60}) + stop = {"event": "Stop", "session": "s1", **CLOSER} + self.assertEqual(self.post_json("/api/asks/ran", stop, {"Host": self.host})[0], 403) + self.assertEqual(self.post_json("/api/asks/ran", stop, {**self.local(), "Origin": "http://evil.example"})[0], 403) + bad = ( + {"event": "Notification", "session": "s1"}, {"event": ["Stop"], "session": "s1"}, {"event": "Stop"}, {"event": "Stop", "session": ""}, {"event": "Stop", "session": "s" * 201}, + {"event": "Stop", "session": "s1", "call_key": KEY}, {"event": "SessionEnd", "session": "s1", "answers": {}}, {"event": "PostToolUse", "session": "s1"}, + {"event": "PostToolUse", "call_key": KEY, "session": "s1", "answers": {FIRST: "x" * 4001}}, {"event": "PostToolUse", "call_key": KEY, "session": "s1", "answers": {FIRST: "a\u200bb"}}, + {"event": "PostToolUse", "call_key": KEY, "session": "s1", "answers": [FIRST]}, {"event": "Stop", "session": "s1", "status": "allowed"}, + {**stop, "closer": "short"}, {**stop, "closer": 7}, {**stop, "closer": "a" * 129}, {**stop, "closer": "a/" * 20}, {**stop, "closer": TOKEN + "\u200b"}, + {"event": "PostToolUse", "call_key": KEY, "session": "s1", "closer": "../" * 12}, + ) + for payload in bad: + with self.subTest(payload=str(payload)[:80]): + self.assertEqual(self.ran(payload)[0], 400) + self.assertEqual(self.statuses(), {ask: "pending", later: "pending"}) + self.assertEqual(self.ran(stop), (200, {"asks": [ask], "decisions": []})) + self.assertEqual(self.httpd.hub.asks.get(later)["status"], "pending") + + def test_a_bound_card_whose_hook_timed_out_reads_open_in_claude_until_a_closing_event_and_an_unbound_one_expires(self): + bound, unbound = self.create_ask(BOUND), self.create_ask({**ASK, "call_key": OTHER}) + for ask in (bound, unbound): + self.httpd.hub.asks.change(ask, {"expires": time.time() - 600}) + card = self.card(f"ask:{bound}") + self.assertEqual((card["blocked_kind"], card["blocked"], card["stale"], card["stale_reason"]), (IN_CLAUDE, IN_CLAUDE_WORDS, False, "")) + self.assertEqual(self.card(f"ask:{unbound}")["blocked_kind"], "expired") + lapsed = {item["id"]: item for item in self.snapshot()["lapsed"]} + self.assertEqual((lapsed[bound]["request"], lapsed[bound]["claude"], lapsed[unbound]["request"]), ("open", True, "expired")) + self.assertEqual(self.ask_status(bound, "0"), "expired") + refs = {event["ref"]["id"]: event["ref"]["status"] for event in self.events("kinds=ask")["events"]} + self.assertEqual((refs[bound], refs[unbound]), (IN_CLAUDE, "expired")) + self.assertEqual(self.ran({"event": "PostToolUse", "call_key": KEY, "session": "s1", **CLOSER}), (200, {"asks": [bound], "decisions": []})) + self.assertNotIn(f"ask:{bound}", [card["id"] for card in self.cards()]) + + def test_a_dismissed_card_open_in_claude_leaves_the_hub_but_stays_pending_for_its_dialog(self): + ask = self.create_ask(BOUND) + self.httpd.hub.asks.change(ask, {"expires": time.time() - 600}) + entries = [{"kind": "dismiss", "target": "ask", "id": ask, "scope": "open"}] + with mock.patch.object(batches, "UNDO", 0.05): + status, _, body = self.post_json("/api/requests/dismiss", {"items": entries, "proof": self.signed(entries, self.pin())}, self.guard(self.host)) + self.assertEqual(status, 202, body) + self.settle(lambda: self.httpd.hub.dismissals.listed() != []) + self.assertEqual(self.httpd.hub.asks.get(ask)["status"], "pending") + self.assertNotIn(f"ask:{ask}", [card["id"] for card in self.cards()]) + + def client(self, event: dict, timeout: str) -> subprocess.CompletedProcess: + trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json"), "--bound"] + return subprocess.run([sys.executable, str(CLIENT), "--port", str(self.port), "--timeout", timeout, *trust], input=json.dumps(event), capture_output=True, text=True, timeout=60, check=False) + + def test_the_hook_client_reports_stop_user_prompt_submit_and_session_end_of_its_own_session_and_prints_nothing(self): + base = {"session_id": "s1", "transcript_path": HOOK["transcript_path"], "cwd": "/repo"} + replay = self.replay / "hook.json" + for event, extra, closed in (("Stop", {"stop_hook_active": False}, TERMINAL), ("UserPromptSubmit", {"prompt": "go on"}, TERMINAL), ("SessionEnd", {"reason": "prompt_input_exit"}, ENDED)): + with self.subTest(event=event): + token = permission_hook.closer_token(replay, "s1") + ask, foreign = self.create_ask({**BOUND, "closer": token}), self.create_ask({**BOUND, "session": "s2", "closer": token}) + done = self.client({**base, "hook_event_name": event, **extra}, "5") + self.assertEqual((done.returncode, done.stdout), (0, ""), done.stderr) + self.assertEqual((self.httpd.hub.asks.get(ask)["status"], self.httpd.hub.asks.get(foreign)["status"]), (closed, "pending")) + self.assertEqual(permission_hook.closer_path(replay, "s1").exists(), event != "SessionEnd") + self.ran({"event": "SessionEnd", "session": "s2", "closer": token}) + + def test_a_waiting_hook_whose_dialog_claude_answered_returns_at_once_without_a_decision(self): + trust = ["--approvers", str(self.approvers), "--replay", str(self.replay / "hook.json"), "--bound"] + argv = [sys.executable, str(CLIENT), "--port", str(self.port), "--timeout", "3600", *trust] + with subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as hook: + hook.stdin.write(json.dumps(HOOK)) + hook.stdin.close() + self.settle(lambda: any(ask["status"] == "pending" for ask in self.httpd.hub.asks.listed())) + ask = next(ask for ask in self.httpd.hub.asks.listed() if ask["status"] == "pending") + self.assertEqual((ask["bound"], ask["call_key"]), (True, signing.call_key(HOOK["tool_name"], HOOK["tool_input"]))) + token = permission_hook.closer_path(self.replay / "hook.json", HOOK["session_id"]).read_text(encoding="ascii") + self.assertEqual(ask["closer_digest"], hashlib.sha256(token.encode()).hexdigest()) + self.assertNotIn(token, json.dumps(ask)) + self.assertAlmostEqual(ask["expires"] - ask["created_ts"], 3600.0, places=3) + done = self.client({**HOOK, "hook_event_name": "PostToolUse", "tool_use_id": "toolu_01Ran", "tool_response": {"stdout": ""}}, "5") + self.assertEqual((done.returncode, done.stdout), (0, ""), done.stderr) + started = time.monotonic() + self.assertEqual(hook.wait(timeout=30), 0) + self.assertLess(time.monotonic() - started, 10) + self.assertEqual(hook.stdout.read(), "") + self.assertEqual(self.httpd.hub.asks.get(ask["id"])["status"], TERMINAL) + + +class TestCloserBinding(ClosingCase): + def test_a_close_without_or_with_a_wrong_closer_closes_nothing(self): + ask = self.create_ask(BOUND) + decision = self.decide(question(FIRST, "s1", {"call_key": ASKED, "bound": True, **CLOSER})) + for closer in ({}, {"closer": WRONG}, {"closer": FOREIGN_TOKEN}): + for report in ({"event": "Stop", "session": "s1"}, {"event": "UserPromptSubmit", "session": "s1"}, {"event": "SessionEnd", "session": "s1"}, {"event": "PostToolUse", "call_key": KEY, "session": "s1"}, {"event": "PostToolUse", "call_key": ASKED, "session": "s1", "answers": {FIRST: "No"}}): + with self.subTest(report=report, closer=closer): + self.assertEqual(self.closed({**report, **closer}), (200, set(), set())) + self.assertEqual(self.statuses(), {ask: "pending", decision: "pending"}) + self.assertIsNone(self.httpd.hub.decisions.get(decision)["choice"]) + + def test_the_right_closer_closes_only_the_cards_of_its_own_session(self): + mine, theirs = self.create_ask(BOUND), self.create_ask({**BOUND, "session": "s2", "closer": FOREIGN_TOKEN}) + mine_decision, their_decision = self.decide(question(FIRST, "s1", CLOSER)), self.decide(question(FIRST, "s2", {"closer": FOREIGN_TOKEN})) + self.assertEqual(self.closed({"event": "SessionEnd", "session": "s2", **CLOSER}), (200, set(), set())) + self.assertEqual(self.closed({"event": "SessionEnd", "session": "s1", "closer": FOREIGN_TOKEN}), (200, set(), set())) + self.assertEqual(self.closed({"event": "SessionEnd", "session": "s1", **CLOSER}), (200, {mine}, {mine_decision})) + self.assertEqual(self.statuses(), {mine: ENDED, mine_decision: ENDED, theirs: "pending", their_decision: "pending"}) + self.assertEqual(self.closed({"event": "SessionEnd", "session": "s2", "closer": FOREIGN_TOKEN}), (200, {theirs}, {their_decision})) + + def test_a_forged_choice_is_never_recorded(self): + bound = self.decide(question(FIRST, "s1", {"call_key": ASKED, "bound": True, **CLOSER})) + older = self.decide(question(SECOND, "s1", {"call_key": ASKED})) + forged = {"event": "PostToolUse", "call_key": ASKED, "session": "s1", "answers": {FIRST: "No", SECOND: "Now"}} + self.assertEqual(self.closed({**forged, "closer": WRONG}), (200, set(), {older})) + self.assertEqual((self.httpd.hub.decisions.get(older)["status"], self.httpd.hub.decisions.get(older)["choice"]), (TERMINAL, None)) + self.assertEqual((self.httpd.hub.decisions.get(bound)["status"], self.httpd.hub.decisions.get(bound)["choice"]), ("pending", None)) + self.assertEqual(self.closed({**forged, "answers": {FIRST: "Yes"}, **CLOSER}), (200, set(), {bound})) + self.assertEqual(self.httpd.hub.decisions.get(bound)["choice"], "Yes") + + def test_an_older_hook_card_closes_by_its_call_key_but_never_by_a_session_wide_event(self): + ask = self.create_ask({**ASK, "call_key": KEY}) + decision = self.decide(question(FIRST, "s1", {"call_key": ASKED})) + self.assertEqual((self.httpd.hub.asks.get(ask)["closer_digest"], self.httpd.hub.decisions.get(decision)["closer_digest"]), ("", "")) + for closer in ({}, CLOSER): + for event in ("Stop", "UserPromptSubmit", "SessionEnd"): + with self.subTest(event=event, closer=closer): + self.assertEqual(self.closed({"event": event, "session": "s1", **closer}), (200, set(), set())) + self.assertEqual(self.closed({"event": "PostToolUse", "call_key": KEY, "session": "s1"}), (200, {ask}, set())) + self.assertEqual(self.closed({"event": "PostToolUse", "call_key": ASKED, "session": "s1"}), (200, set(), {decision})) + self.assertEqual(self.statuses(), {ask: TERMINAL, decision: TERMINAL}) + + def test_the_hub_keeps_only_the_digest_of_the_closer(self): + ask = self.httpd.hub.asks.get(self.create_ask(BOUND)) + decision = self.httpd.hub.decisions.get(self.decide(question(FIRST, "s1", CLOSER))) + digest = hashlib.sha256(TOKEN.encode()).hexdigest() + for record in (ask, decision): + with self.subTest(record=record["id"]): + self.assertEqual(record["closer_digest"], digest) + self.assertNotIn(TOKEN, json.dumps(record)) + self.assertNotIn("closer", record) + for bad in ("short", 7, "a" * 129, "../" * 12): + with self.subTest(bad=bad): + self.assertEqual(self.post_json("/api/asks", {**BOUND, "closer": bad}, self.local())[0], 400) + self.assertEqual(self.post_json("/api/decisions", question(FIRST, "s1", {"closer": bad}), self.local())[0], 400) + + +class TestCloserToken(unittest.TestCase): + def setUp(self): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + self.root = Path(folder.name) + self.replay = self.root / "approvals" / "hook.json" + + def test_the_token_file_is_made_once_per_session_with_mode_0600_and_kept(self): + token = permission_hook.closer_token(self.replay, "s1") + path = permission_hook.closer_path(self.replay, "s1") + self.assertRegex(token, r"^[A-Za-z0-9_-]{43}$") + self.assertEqual((path.parent, path.read_text(encoding="ascii")), (self.replay.parent / permission_hook.CLOSERS, token)) + self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) + self.assertEqual(stat.S_IMODE(path.parent.stat().st_mode) & 0o077, 0) + self.assertEqual(permission_hook.closer_token(self.replay, "s1"), token) + self.assertNotEqual(permission_hook.closer_token(self.replay, "s2"), token) + self.assertEqual(sorted(name.name for name in path.parent.iterdir()), ["s1.token", "s2.token"]) + + def test_a_file_a_concurrent_hook_linked_first_wins(self): + path = permission_hook.closer_path(self.replay, "s1") + path.parent.mkdir(parents=True) + path.write_text(TOKEN, encoding="ascii") + real = permission_hook.read_closer + reads = iter([None]) + with mock.patch.object(permission_hook, "read_closer", side_effect=lambda found: next(reads, real(found))), mock.patch.object(permission_hook.os, "link", wraps=os.link) as link: + self.assertEqual(permission_hook.closer_token(self.replay, "s1"), TOKEN) + self.assertEqual(link.call_count, 1) + self.assertEqual((path.read_text(encoding="ascii"), sorted(name.name for name in path.parent.iterdir())), (TOKEN, ["s1.token"])) + + def test_a_session_id_outside_the_pattern_never_names_a_path_and_gets_no_token(self): + for bad in ("", "..", "../s1", "a/b", "-s1", "s1.token", "s" * 129, "s1\n", "/etc/passwd"): + with self.subTest(bad=bad): + self.assertIsNone(permission_hook.closer_path(self.replay, bad)) + self.assertEqual(permission_hook.closer_token(self.replay, bad), "") + self.assertEqual(list(self.root.iterdir()), []) + + def test_a_linked_or_malformed_token_file_is_refused(self): + path = permission_hook.closer_path(self.replay, "s1") + path.parent.mkdir(parents=True) + target = self.root / "elsewhere" + target.write_text(TOKEN, encoding="ascii") + path.symlink_to(target) + with self.assertRaises(OSError): + permission_hook.closer_token(self.replay, "s1") + path.unlink() + path.write_text("x", encoding="ascii") + with self.assertRaises(ValueError): + permission_hook.closer_token(self.replay, "s1") + + def reports(self, hook: dict) -> list[dict]: + sent: list[dict] = [] + with mock.patch.object(permission_hook.hub_api, "call", side_effect=lambda request, _: sent.append(json.loads(request.data))): + permission_hook.report_ran("http://127.0.0.1:9", hook, self.replay) + return sent + + def test_every_report_carries_the_token_and_session_end_deletes_its_file_even_when_the_report_fails(self): + self.assertEqual(self.reports({"hook_event_name": "Stop", "session_id": "s1"}), []) + token = permission_hook.closer_token(self.replay, "s1") + ran = {"hook_event_name": "PostToolUse", "session_id": "s1", "tool_name": "Bash", "tool_input": {"command": "make deploy"}} + self.assertEqual(self.reports(ran), [{"event": "PostToolUse", "call_key": KEY, "session": "s1", "closer": token}]) + self.assertEqual(self.reports({"hook_event_name": "Stop", "session_id": "s1"}), [{"event": "Stop", "session": "s1", "closer": token}]) + self.assertEqual(self.reports({"hook_event_name": "SessionEnd", "session_id": "s1"}), [{"event": "SessionEnd", "session": "s1", "closer": token}]) + self.assertFalse(permission_hook.closer_path(self.replay, "s1").exists()) + self.assertEqual(self.reports({**ran, "session_id": "s2"}), [{"event": "PostToolUse", "call_key": KEY, "session": "s2"}]) + permission_hook.closer_token(self.replay, "s1") + with mock.patch.object(permission_hook.hub_api, "call", side_effect=OSError("hub down")), self.assertRaises(OSError): + permission_hook.report_ran("http://127.0.0.1:9", {"hook_event_name": "SessionEnd", "session_id": "s1"}, self.replay) + self.assertFalse(permission_hook.closer_path(self.replay, "s1").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_match_expired.py b/tests/test_hub_match_expired.py index e3eb260..40a555f 100644 --- a/tests/test_hub_match_expired.py +++ b/tests/test_hub_match_expired.py @@ -21,6 +21,7 @@ CALL = signing.call_key("Bash", {"command": "make deploy"}) OTHER = signing.call_key("Bash", {"command": "make deploy", "run_in_background": True}) CALLED = {**ASK, "call_key": CALL} QUESTION = {"question": "Clean up the two worktrees?", "options": [{"label": PICK, "description": "Both are merged"}], "session": "s1", "timeout": 60, "multi": False} +NONE = {"asks": [], "decisions": []} class TestExpiredFilter(unittest.TestCase): @@ -121,20 +122,20 @@ class TestExpiredRelease(MatchCase): report = {"call_key": CALL, "session": "s1"} self.assertEqual(self.ran(report, {"Host": self.host})[0], 403) self.assertEqual(self.ran(report, {**self.local(), "Origin": "http://evil.example"})[0], 403) - self.assertEqual(self.ran(report, self.local()), (200, {"closed": first})) + self.assertEqual(self.ran(report, self.local()), (200, {**NONE, "asks": [first]})) record = self.httpd.hub.asks.get(first) self.assertEqual((record["status"], record["proof"]), (TERMINAL, None)) self.assertEqual(self.ask_status(first, "0"), TERMINAL) self.assertEqual(self.httpd.hub.asks.get(second)["status"], "pending") self.assertNotIn(f"ask:{first}", [card["id"] for card in self.cards()]) - self.assertEqual(self.ran(report, self.local()), (200, {"closed": second})) - self.assertEqual(self.ran(report, self.local()), (200, {"closed": None})) + self.assertEqual(self.ran(report, self.local()), (200, {**NONE, "asks": [second]})) + self.assertEqual(self.ran(report, self.local()), (200, NONE)) self.assertEqual(self.post_json("/api/sign", {"items": [self.denial("ask", first, "Skills")]}, self.guard(self.host))[0], 409) def test_a_report_never_closes_an_ask_created_after_it(self): ask = self.lapsed_ask(CALLED) self.httpd.hub.asks.change(ask, {"created_ts": time.time() + 60}) - self.assertEqual(self.ran({"call_key": CALL, "session": "s1"}, self.local()), (200, {"closed": None})) + self.assertEqual(self.ran({"call_key": CALL, "session": "s1"}, self.local()), (200, NONE)) self.assertEqual(self.httpd.hub.asks.get(ask)["status"], "pending") def test_the_hook_client_keys_its_ask_and_reports_the_call_that_ran_and_prints_nothing(self): @@ -148,8 +149,8 @@ class TestExpiredRelease(MatchCase): def test_a_foreign_session_a_different_input_or_a_bad_report_closes_nothing(self): ask = self.lapsed_ask(CALLED) - self.assertEqual(self.ran({"call_key": CALL, "session": "s2"}, self.local()), (200, {"closed": None})) - self.assertEqual(self.ran({"call_key": OTHER, "session": "s1"}, self.local()), (200, {"closed": None})) + self.assertEqual(self.ran({"call_key": CALL, "session": "s2"}, self.local()), (200, NONE)) + self.assertEqual(self.ran({"call_key": OTHER, "session": "s1"}, self.local()), (200, NONE)) for bad in ({"call_key": CALL}, {"call_key": CALL, "session": ""}, {"call_key": "../x", "session": "s1"}, {"call_key": CALL, "session": "s1", "status": "allowed"}): with self.subTest(bad=bad): self.assertEqual(self.ran(bad, self.local())[0], 400) diff --git a/tests/test_hub_stale_requests.py b/tests/test_hub_stale_requests.py new file mode 100644 index 0000000..ba81566 --- /dev/null +++ b/tests/test_hub_stale_requests.py @@ -0,0 +1,176 @@ +"""Exercise requirement 093: every request has one kind, and a signed dismissal hides many in the hub with an undo.""" + +from __future__ import annotations + +import json +import time +import unittest +from unittest import mock + +from hub_support import ASK, signing +from kvb_orchestrator import batches, skill_scripts +from kvb_orchestrator.inbox import item_base +from kvb_orchestrator.triage import REQUEST_KINDS, hides, request_kind, request_mark +from test_hub_match import MatchCase + +CALLED = {**ASK, "call_key": signing.call_key("Bash", {"command": ASK["command"]})} +FAILED_JOB = {"id": "0123456789abcdef", "status": "failed", "code": 2, "output": "", "created_ts": 1.0, "started": 1.0, "finished": 2.0} + + +def job(status: str) -> dict: + return {**FAILED_JOB, "status": status} + + +class TestRequestKind(unittest.TestCase): + def test_every_request_has_exactly_one_kind(self): + base = item_base() + cases = { + "open ask": ({**base, "kind": "ask"}, "open"), + "open review": ({**base, "kind": "review"}, "open"), + "lapsed ask": ({**base, "kind": "ask", "expires": 10.0}, "expired"), + "lapsed decision": ({**base, "kind": "decision", "expires": 10.0}, "expired"), + "stale review": ({**base, "kind": "review", "stale": True}, "stale"), + "stale row": ({**base, "kind": "operator", "stale": True}, "stale"), + "failed row": ({**base, "kind": "operator", "job": job("failed")}, "failed"), + "refused row": ({**base, "kind": "operator", "job": job("refused")}, "failed"), + "failed and stale row": ({**base, "kind": "operator", "stale": True, "job": job("failed")}, "failed"), + "row that ran": ({**base, "kind": "operator", "job": job("done")}, "open"), + "row running": ({**base, "kind": "operator", "job": job("running")}, "open"), + } + for name, (item, kind) in cases.items(): + with self.subTest(name=name): + self.assertEqual(request_kind(item), kind) + self.assertIn(request_kind(item), REQUEST_KINDS) + + def test_a_dismissal_hides_only_the_same_command_and_job_and_a_pending_one_hides_any(self): + mark = request_mark("make deploy", FAILED_JOB) + hidden = ({"operator:operator/greet": mark}, {"ask:a1"}) + self.assertTrue(hides(hidden, "operator:operator/greet", mark)) + self.assertFalse(hides(hidden, "operator:operator/greet", request_mark("make deploy", {**FAILED_JOB, "id": "1123456789abcdef"}))) + self.assertFalse(hides(hidden, "operator:operator/greet", request_mark("make other", FAILED_JOB))) + self.assertTrue(hides(hidden, "ask:a1", request_mark("anything", None))) + self.assertFalse(hides(hidden, "ask:a2", request_mark("", None))) + + +class TestDismissRequests(MatchCase): + def setUp(self): + super().setUp() + self.claim("s1", "Skills session") + self.expired = self.create_ask(CALLED) + self.httpd.hub.asks.change(self.expired, {"expires": time.time() - 600}) + self.open = self.create_ask({**ASK, "command": "make open", "timeout": 3600}) + self.review = self.request("feat: stale", "notes") + status, _, body = self.post_json("/api/match/stale", {"id": self.review, "tree": "f" * 40}, self.local()) + self.assertEqual(status, 200, body) + greet = {"title": "echo greet", "workdir": str(self.outside), "description": "greets", "check": "manual", "status": "queued", "roles": {"Operator": "R", "Skills session": "A"}} + self.write_council({"rasci.json": {"operator/greet": greet}}) + fields = {"task": "operator/greet", "command": "echo greet", "directory": str(self.outside), "sha256": "", "status": "failed", "proof": None} + now = time.time() + self.httpd.hub.jobs.add({**fields, "code": 2, "output": "boom\n", "created_ts": now - 20, "started": now - 19, "finished": now - 10, "dismissed": False}) + + def kinds(self) -> dict[str, str]: + snapshot = self.snapshot() + return {f"{item['kind']}:{item['id']}": item["request"] for item in snapshot["inbox"] + snapshot["lapsed"]} + + def entry(self, target: str, ident: str, scope: str) -> dict: + return {"kind": "dismiss", "target": target, "id": ident, "scope": scope} + + def dismiss(self, entries: list[dict], proof: object) -> tuple[int, dict, bytes]: + return self.post_json("/api/requests/dismiss", {"items": entries, "proof": proof}, self.guard(self.host)) + + def backlog(self) -> list[dict]: + return [self.entry("ask", self.expired, "expired"), self.entry("review", self.review, "stale"), self.entry("operator", "operator/greet", "failed")] + + def test_the_snapshot_names_each_requests_kind(self): + kinds = self.kinds() + self.assertEqual(kinds[f"ask:{self.expired}"], "expired") + self.assertEqual(kinds[f"ask:{self.open}"], "open") + self.assertEqual(kinds[f"review:{self.review}"], "stale") + self.assertEqual(kinds["operator:operator/greet"], "failed") + self.assertNotIn(f"ask:{self.expired}", [item["id"] for item in self.snapshot()["inbox"]]) + + def test_the_endpoint_refuses_an_unsigned_or_foreign_call_and_malformed_entries(self): + entries = self.backlog() + status, _, body = self.dismiss(entries, None) + self.assertEqual(status, 400, body) + self.assertIn("not signed", body.decode()) + foreign = {**self.guard(self.host), "Origin": "http://evil.example"} + self.assertEqual(self.post_json("/api/requests/dismiss", {"items": entries, "proof": None}, foreign)[0], 403) + self.assertEqual(self.post_json("/api/requests/dismiss", {"items": entries, "proof": None}, {"Host": self.host})[0], 403) + signer = self.pin() + proof = self.signed(entries, signer) + forged = {**proof, "payload": {**proof["payload"], "nonce": "0" * 32}} + self.assertEqual(self.dismiss(entries, forged)[0], 400) + for bad in ([], "x", [{**entries[0], "extra": 1}], [{**entries[0], "scope": "bogus"}], [{**entries[0], "target": 7}], [entries[0], entries[0]]): + with self.subTest(bad=bad): + self.assertEqual(self.post_json("/api/sign", {"items": bad}, self.guard(self.host))[0], 400) + self.assertEqual(self.post_json("/api/sign", {"items": [self.entry("ask", "0123456789abcdef", "expired")]}, self.guard(self.host))[0], 404) + self.assertEqual(self.kinds()[f"ask:{self.expired}"], "expired") + self.assertEqual(self.httpd.hub.dismissals.listed(), []) + + def test_a_signed_dismissal_hides_the_list_at_once_and_the_undo_brings_it_back(self): + entries = self.backlog() + signer = self.pin() + with mock.patch.object(batches, "UNDO", 60): + status, _, body = self.dismiss(entries, self.signed(entries, signer)) + self.assertEqual(status, 202, body) + batch = json.loads(body) + self.assertEqual(sorted((item["kind"], item["id"], item["verb"]) for item in batch["items"]), sorted([("ask", self.expired, "dismiss"), ("review", self.review, "dismiss"), ("operator", "operator/greet", "dismiss")])) + kinds = self.kinds() + for key in (f"ask:{self.expired}", f"review:{self.review}", "operator:operator/greet"): + self.assertNotIn(key, kinds) + self.assertIn(f"ask:{self.open}", kinds) + self.assertNotIn(f"review:{self.review}", [card["id"] for card in self.cards()]) + status, _, body = self.post_json(f"/api/inbox/undo/{batch['id']}", {}, self.guard(self.host)) + self.assertEqual(status, 200, body) + kinds = self.kinds() + self.assertEqual((kinds[f"ask:{self.expired}"], kinds[f"review:{self.review}"], kinds["operator:operator/greet"]), ("expired", "stale", "failed")) + self.assertEqual(self.httpd.hub.dismissals.listed(), []) + + def test_an_applied_dismissal_stays_for_every_browser_and_tells_no_agent(self): + entries = self.backlog() + with mock.patch.object(batches, "UNDO", 0.05): + status, _, body = self.dismiss(entries, self.signed(entries, self.pin())) + self.assertEqual(status, 202, body) + self.settle(lambda: self.httpd.hub.dismissals.listed() != []) + kinds = self.kinds() + self.assertEqual([key for key in (f"ask:{self.expired}", f"review:{self.review}", "operator:operator/greet") if key in kinds], []) + shown = [card["id"] for card in self.cards()] + self.assertNotIn(f"ask:{self.expired}", shown) + self.assertNotIn(f"review:{self.review}", shown) + self.assertEqual(self.httpd.hub.asks.get(self.expired)["status"], "pending") + self.assertEqual(self.status(self.review), "pending") + self.assertEqual([args for script, args in self.scripts.calls if script == skill_scripts.RADIO], []) + + def test_an_open_request_is_deleted_only_from_open_or_all_and_its_ask_is_denied_without_a_message(self): + for scope in ("expired", "stale", "failed"): + with self.subTest(scope=scope): + status, _, body = self.post_json("/api/sign", {"items": [self.entry("ask", self.open, scope)]}, self.guard(self.host)) + self.assertEqual(status, 409, body) + self.assertEqual(json.loads(body)["status"], "open") + self.assertEqual(self.post_json("/api/sign", {"items": [self.entry("ask", self.expired, "open")]}, self.guard(self.host))[0], 409) + entries = [self.entry("ask", self.open, "all")] + with mock.patch.object(batches, "UNDO", 0.05): + status, _, body = self.dismiss(entries, self.signed(entries, self.pin())) + self.assertEqual(status, 202, body) + self.settle(lambda: self.httpd.hub.asks.get(self.open)["status"] == "denied") + record = self.httpd.hub.asks.get(self.open) + self.assertEqual((record["proof"], record.get("reason")), (None, None)) + self.assertEqual(self.ask_status(self.open, "0"), "denied") + self.assertNotIn(f"ask:{self.open}", self.kinds()) + self.assertEqual([args for script, args in self.scripts.calls if script == skill_scripts.RADIO], []) + + def test_a_row_that_ran_again_shows_again_after_its_dismissal(self): + entries = [self.entry("operator", "operator/greet", "failed")] + with mock.patch.object(batches, "UNDO", 0.05): + self.assertEqual(self.dismiss(entries, self.signed(entries, self.pin()))[0], 202) + self.settle(lambda: self.httpd.hub.dismissals.listed() != []) + self.assertNotIn("operator:operator/greet", self.kinds()) + fields = {"task": "operator/greet", "command": "echo greet", "directory": str(self.outside), "sha256": "", "status": "refused", "proof": None} + now = time.time() + self.httpd.hub.jobs.add({**fields, "code": None, "output": "", "created_ts": now, "started": now, "finished": now, "dismissed": False}) + self.assertEqual(self.kinds()["operator:operator/greet"], "failed") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hub_state.py b/tests/test_hub_state.py index 6991aed..2f4e6fc 100644 --- a/tests/test_hub_state.py +++ b/tests/test_hub_state.py @@ -154,7 +154,7 @@ class TestHubState(HubCase): { "now", "since", "until", "first", "alarm_since", "reviews", "asks", "decisions", "messages", "reasons", "operator", "schedules", "tasks", "task_edges", "queue_line", "queue_jobs", "agent_order", "radio", "claims", "grants", "night", "night_parts", "presence", "beats", "runner", "silence", "graph", - "inbox", "pending", "rules", "approvers", "jobs", "views", "llm", "people", "settings", "media", "speech", + "inbox", "lapsed", "pending", "rules", "approvers", "jobs", "views", "llm", "people", "settings", "media", "speech", "badges", "kinds", }, ) diff --git a/tests/test_orchestrator_migration.py b/tests/test_orchestrator_migration.py index 44c7c35..6562968 100644 --- a/tests/test_orchestrator_migration.py +++ b/tests/test_orchestrator_migration.py @@ -135,8 +135,10 @@ class TestOrchestratorMigration(unittest.TestCase): settings = self.home / ".claude" / "settings.json" data = json.loads(settings.read_text(encoding="utf-8")) hooks = data["hooks"]["PermissionRequest"] - self.assertEqual((data["model"], data["hooks"]["Stop"], hooks[0], len(hooks)), ("x", [self.other], self.other, 2)) + stops = data["hooks"]["Stop"] + self.assertEqual((data["model"], stops[0], len(stops), hooks[0], len(hooks)), ("x", self.other, 2, self.other, 2)) self.assertIn(f"{share / NEW}/client/permission_hook.py", hooks[1]["hooks"][0]["command"]) + self.assertIn(f"{share / NEW}/client/permission_hook.py", stops[1]["hooks"][0]["command"]) self.assertEqual(settings.stat().st_mode & 0o777, 0o640) self.assertIn(f"{OLD}/client", (self.home / ".claude" / f"settings.json.before-{NEW}-migration").read_text(encoding="utf-8")) self.assertEqual((first["images"], first["mcp"], first["enabled"]), ([f"{NEW}:local"], {NEW: "http://127.0.0.1:8737/mcp"}, [f"{NEW}-firewall.path", f"{NEW}-firewall.timer", f"{NEW}-offices.path", f"{NEW}-resources.timer", f"{NEW}-runner.service", f"{NEW}-sessions.timer", f"{NEW}-tokens.timer"])) diff --git a/tests/test_resources_sample.py b/tests/test_resources_sample.py index 8029e9f..2b3e6db 100644 --- a/tests/test_resources_sample.py +++ b/tests/test_resources_sample.py @@ -191,7 +191,7 @@ class TestQueueView(unittest.TestCase): (council / "queue.json").write_text(json.dumps({"entries": [{"status": "waiting", "enqueued": NOW}]}), encoding="utf-8") self.calls.clear() silent = self.answer(None) - found = sampler.sample(council, council / "sys", functools.partial(sampler.queue_state, council, council / "missing.py", silent), silent, state) + found = sampler.sample(council, council / "sys", functools.partial(sampler.queue_state, council, council / "missing.py", silent), silent, lambda _argv: (None, ""), state) self.assertEqual(found["queue"], {"waiting": 1, "active": 0}) self.assertEqual([argv[0] for argv in self.calls], ["df", "env"]) @@ -218,7 +218,7 @@ class TestCpu(unittest.TestCase): state.mkdir() (proc / "stat").write_text(STAT_BEFORE, encoding="utf-8") with mock.patch.object(sampler.time, "sleep", side_effect=AssertionError("slept")), mock.patch.object(sampler.time, "time", return_value=NOW - 60): - self.assertIsNone(sampler.sample(proc, Path(tmp) / "sys", functools.partial(sampler.queue_state, Path(tmp), Path(tmp) / "queue.py", lambda _argv: None), lambda _argv: None, state)["cpu"]) + self.assertIsNone(sampler.sample(proc, Path(tmp) / "sys", functools.partial(sampler.queue_state, Path(tmp), Path(tmp) / "queue.py", lambda _argv: None), lambda _argv: None, lambda _argv: (None, ""), state)["cpu"]) (proc / "stat").write_text(STAT_AFTER, encoding="utf-8") self.assertEqual(sampler.cpu_since(proc, state, NOW), 61.5) (proc / "stat").write_text(STAT_LATER, encoding="utf-8") @@ -259,7 +259,7 @@ class TestPressure(unittest.TestCase): def test_a_sample_row_adds_the_pressure_keys_and_keeps_every_other_key(self): (self.proc / "pressure" / "memory").write_text("some avg10=3.00 avg60=0 avg300=0 total=1\n", encoding="utf-8") - found = sampler.sample(self.proc, self.proc / "sys", functools.partial(sampler.queue_state, self.proc, self.proc / "queue.py", lambda _argv: None), lambda _argv: None, self.state) + found = sampler.sample(self.proc, self.proc / "sys", functools.partial(sampler.queue_state, self.proc, self.proc / "queue.py", lambda _argv: None), lambda _argv: None, lambda _argv: (None, ""), self.state) self.assertEqual(sorted(found), ["cpu", "disks", "gpus", "load", "psi_full", "psi_some", "queue", "ram", "swap", "swap_out_mb_min", "t"]) self.assertEqual((found["psi_some"], found["psi_full"], found["swap_out_mb_min"]), (3.0, None, None)) @@ -280,9 +280,9 @@ class TestGpus(unittest.TestCase): self.root = Path(tmp.name) self.calls = [] - def run_smi(self, argv: list[str]) -> str: + def run_smi(self, argv: list[str]) -> tuple[str | None, str]: self.calls.append(argv) - return NVIDIA_SMI + return NVIDIA_SMI, "" def test_an_asleep_gpu_is_recorded_asleep_and_nvidia_smi_queries_only_the_awake_one(self): found = sampler.gpus(host_sys(self.root), self.run_smi) @@ -300,10 +300,30 @@ class TestGpus(unittest.TestCase): def test_an_awake_gpu_nvidia_smi_gives_no_reading_for_is_recorded_unknown(self): unknown = {"name": AWAKE, "util": None, "vram_used": None, "vram_total": None} - self.assertEqual(sampler.gpus(host_sys(self.root), lambda argv: None), [unknown, {"name": ASLEEP, "asleep": True}]) - self.assertEqual(sampler.gpus(self.root, lambda argv: NVIDIA_SMI.splitlines()[1]), [unknown, {"name": ASLEEP, "asleep": True}]) + self.assertEqual(sampler.gpus(host_sys(self.root), lambda argv: (None, "")), [unknown, {"name": ASLEEP, "asleep": True}]) + self.assertEqual(sampler.gpus(self.root, lambda argv: (NVIDIA_SMI.splitlines()[1], "")), [unknown, {"name": ASLEEP, "asleep": True}]) self.assertEqual(sampler.mean_row(NOW, sampler.BUCKET, [row(NOW + 60, 1.0, 1, 0, unknown), row(NOW + 120, 1.0, 1, 0, unknown)])["gpus"], [unknown]) + def test_a_failed_nvidia_smi_read_keeps_its_first_error_line_in_the_sample_and_the_mean(self): + mismatch = "Failed to initialize NVML: Driver/library version mismatch" + failed = {"name": AWAKE, "util": None, "vram_used": None, "vram_total": None, "error": mismatch} + self.assertEqual(sampler.gpus(host_sys(self.root), lambda argv: (None, mismatch)), [failed, {"name": ASLEEP, "asleep": True}]) + rows = [row(NOW + 60, 1.0, 1, 0, failed), row(NOW + 120, 1.0, 1, 0, {**failed, "error": "NVIDIA-SMI has failed"})] + self.assertEqual(sampler.mean_row(NOW, sampler.BUCKET, rows)["gpus"], [{**failed, "error": "NVIDIA-SMI has failed"}]) + read = {"name": AWAKE, "util": 40.0, "vram_used": 10, "vram_total": 100} + self.assertEqual(sampler.mean_row(NOW, sampler.BUCKET, [row(NOW + 60, 1.0, 1, 0, failed), row(NOW + 120, 1.0, 1, 0, read)])["gpus"], [read]) + + def test_attempt_names_the_first_stderr_line_else_the_first_stdout_line_of_a_failed_command(self): + script = "import sys; print(); print(' Failed to initialize NVML: Driver/library version mismatch '); print('NVML library version: 620.70', file=sys.stderr); sys.exit(9)" + self.assertEqual(sampler.attempt([sys.executable, "-c", script]), (None, "NVML library version: 620.70")) + quiet = "print('\\n\\nFailed to initialize NVML: Driver/library version mismatch'); raise SystemExit(18)" + self.assertEqual(sampler.attempt([sys.executable, "-c", quiet]), (None, "Failed to initialize NVML: Driver/library version mismatch")) + self.assertEqual(sampler.attempt([sys.executable, "-c", "raise SystemExit(3)"]), (None, f"{sys.executable} exited 3")) + self.assertEqual(sampler.attempt([sys.executable, "-c", "print('x' * 500); raise SystemExit(1)"]), (None, "x" * sampler.ERROR_TEXT)) + self.assertEqual(sampler.attempt([sys.executable, "-c", "print('ok')"]), ("ok\n", "")) + self.assertEqual(sampler.attempt(["kvb-no-such-tool-091"]), (None, "kvb-no-such-tool-091 not found")) + self.assertIsNone(sampler.command([sys.executable, "-c", "raise SystemExit(1)"])) + def test_no_nvidia_gpu_means_no_gpu_row_and_no_call(self): device(self.root, "0000:00:02.0", "0x8086", "0x030000", "active") self.assertEqual(sampler.gpus(self.root, self.run_smi), [])