"}; [] when nothing holds.'), + ]) diff --git a/skills/kvb-code-review/scripts/review_memory.py b/skills/kvb-code-review/scripts/review_memory.py new file mode 100644 index 0000000..4b2980d --- /dev/null +++ b/skills/kvb-code-review/scripts/review_memory.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import contextlib +import fcntl +import hashlib +import json +import os +import tempfile +from collections.abc import Iterator +from pathlib import Path + +CACHE = "kvb-review-cache.json" +STAMPS = "kvb-review.json" +SECTIONS = ("files", "diffs", "verdicts") +FILE_MODE = 0o600 + + +def digest(*parts: str) -> str: + return hashlib.sha256("\0".join(parts).encode("utf-8")).hexdigest() + + +def file_key(lens: str, version: str, path: str, blob: str, context: str) -> str: + """Args: + context: the digest of the standards the lens judged against, "" + for a lens that reads none. + """ + return digest("file", lens, version, path, blob, context) + + +def diff_key(lens: str, version: str, patch: str, context: str) -> str: + return digest("diff", lens, version, patch, context) + + +def finding_key(finding: dict, blob: str, flagged: str) -> str: + """Args: + finding: lens, rule and path of the finding. + blob: the blob of its path after the change. + flagged: the text of its flagged line, "" without a line. + """ + return digest("finding", finding["lens"], str(finding.get("rule") or ""), finding["path"], blob, flagged) + + +def read(path: Path) -> dict: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return {} + except ValueError as error: + raise ValueError(f"{path} is not JSON: {error}") from error + if not isinstance(data, dict): + raise TypeError(f"{path} holds no JSON object") + return data + + +def write(path: Path, data: dict) -> None: + handle, name = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump(data, stream, indent=1, sort_keys=True) + os.chmod(name, FILE_MODE) + os.replace(name, path) + except BaseException: + Path(name).unlink(missing_ok=True) + raise + + +@contextlib.contextmanager +def held(path: Path) -> Iterator[dict]: + """Args: + path: the JSON file, read and written back under an exclusive lock on + its .lock sibling. + """ + lock = path.with_name(f"{path.name}.lock") + with open(os.open(lock, os.O_RDWR | os.O_CREAT, FILE_MODE), "r+", encoding="utf-8") as guard: + fcntl.flock(guard, fcntl.LOCK_EX) + data = read(path) + yield data + write(path, data) + + +def cache(common: Path) -> contextlib.AbstractContextManager[dict]: + return held(common / CACHE) + + +def sections(data: dict) -> dict: + for name in SECTIONS: + data.setdefault(name, {}) + return data diff --git a/skills/kvb-code-review/scripts/review_scope.py b/skills/kvb-code-review/scripts/review_scope.py new file mode 100644 index 0000000..ac0f52c --- /dev/null +++ b/skills/kvb-code-review/scripts/review_scope.py @@ -0,0 +1,216 @@ +from __future__ import annotations + +import json +import shutil +import subprocess +from dataclasses import dataclass +from pathlib import Path + +DEFAULTS = ("main", "master") +STAGED = "staged" +PULL = "pr" +BRANCH = "branch" +RANGE = "range" +GH_SECONDS = 30 + + +class ScopeError(Exception): + pass + + +@dataclass(frozen=True) +class Scope: + """Args: + kind: STAGED, PULL, BRANCH or RANGE. + base: the commit the change starts from; HEAD for STAGED. + head: the last commit of the change; None for STAGED, whose change + is the index. + spec: the target as the operator picked it. + """ + + kind: str + base: str + head: str | None + spec: str + + +def git(repo: Path, *args: str) -> str: + done = subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True, check=False) + if done.returncode != 0: + raise ScopeError(f"git {' '.join(args)}: {done.stderr.strip() or done.returncode}") + return done.stdout + + +def git_bytes(repo: Path, args: list[str], given: bytes | None) -> bytes: + done = subprocess.run(["git", *args], cwd=repo, input=given, capture_output=True, check=False) + if done.returncode != 0: + raise ScopeError(f"git {' '.join(args)}: {done.stderr.decode(errors='replace').strip() or done.returncode}") + return done.stdout + + +def succeeds(repo: Path, *args: str) -> bool: + return subprocess.run(["git", *args], cwd=repo, capture_output=True, check=False).returncode == 0 + + +def commit(repo: Path, ref: str) -> str: + return git(repo, "rev-parse", "--verify", f"{ref}^{{commit}}").strip() + + +def upstream(repo: Path) -> str | None: + done = subprocess.run(["git", "rev-parse", "--verify", "--quiet", "@{u}^{commit}"], cwd=repo, capture_output=True, text=True, check=False) + return done.stdout.strip() if done.returncode == 0 else None + + +def default_branch(repo: Path) -> str | None: + done = subprocess.run(["git", "symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"], cwd=repo, capture_output=True, text=True, check=False) + if done.returncode == 0 and done.stdout.strip(): + return done.stdout.strip().split("/", 1)[-1] + return next((name for name in DEFAULTS if succeeds(repo, "rev-parse", "--verify", "--quiet", f"refs/heads/{name}")), None) + + +def pull_request(repo: Path, number: str) -> dict | None: + """Returns: + number, state, baseRefName and headRefOid of the pull request gh + names for the branch (number "") or for that number; None without + gh, without one, or when gh fails. + """ + gh = shutil.which("gh") + if gh is None: + return None + argv = [gh, "pr", "view", *([number] if number else []), "--json", "number,state,baseRefName,headRefOid"] + try: + done = subprocess.run(argv, cwd=repo, capture_output=True, text=True, check=False, timeout=GH_SECONDS) + except subprocess.TimeoutExpired: + return None + if done.returncode != 0: + return None + try: + data = json.loads(done.stdout) + except ValueError: + return None + return data if isinstance(data, dict) and isinstance(data.get("number"), int) else None + + +def detect(repo: Path) -> str: + """Returns: + The recommended target: STAGED with staged changes, else `pr` + for an open pull request of the branch, else `branch ` + with commits ahead of the default branch, else `range ..HEAD` + with unpushed commits, else RANGE for the operator to name. + """ + if not succeeds(repo, "diff", "--cached", "--quiet"): + return STAGED + found = pull_request(repo, "") + if found is not None and found.get("state") == "OPEN": + return f"{PULL} {found['number']}" + default = default_branch(repo) + if default is not None and int(git(repo, "rev-list", "--count", f"{default}..HEAD").strip()) > 0: + return f"{BRANCH} {default}" + pushed = upstream(repo) + if pushed is not None and int(git(repo, "rev-list", "--count", f"{pushed}..HEAD").strip()) > 0: + return f"{RANGE} {pushed}..HEAD" + return RANGE + + +def unknown(spec: str) -> ScopeError: + return ScopeError(f"target must be staged, pr , branch or range .., not {spec!r}") + + +def named(repo: Path, kind: str, value: str, spec: str) -> Scope: + if kind == BRANCH: + head = commit(repo, "HEAD") + return Scope(BRANCH, git(repo, "merge-base", value, head).strip(), head, spec) + if kind == RANGE and ".." in value: + start, end = value.split("..", 1) + return Scope(RANGE, commit(repo, start), commit(repo, end or "HEAD"), spec) + if kind == PULL and value.isdigit(): + return pull_scope(repo, value, spec) + raise unknown(spec) + + +def resolve(repo: Path, spec: str) -> Scope: + parts = spec.split() + if parts == [STAGED]: + return Scope(STAGED, commit(repo, "HEAD"), None, spec) + if len(parts) == 2: + return named(repo, parts[0], parts[1], spec) + raise unknown(spec) + + +def pull_scope(repo: Path, number: str, spec: str) -> Scope: + found = pull_request(repo, number) + if found is None: + raise ScopeError(f"gh knows no pull request {number} here") + head = commit(repo, "HEAD") + if found.get("headRefOid") != head: + raise ScopeError(f"HEAD is not the head of pull request {number}; check it out first: gh pr checkout {number}") + base_ref = found.get("baseRefName") or "" + remote = f"origin/{base_ref}" + base_name = remote if succeeds(repo, "rev-parse", "--verify", "--quiet", remote) else base_ref + return Scope(PULL, git(repo, "merge-base", base_name, head).strip(), head, spec) + + +def diff_args(scope: Scope) -> list[str]: + return ["--cached", scope.base] if scope.head is None else [scope.base, scope.head] + + +def changed(repo: Path, scope: Scope) -> dict[str, str]: + """Returns: + Every path the change adds, copies, modifies or renames, with the + blob it has after the change: the index entry for STAGED, else the + entry in the head commit. + """ + names = [name for name in git(repo, "diff", "--name-only", "-z", "--diff-filter=ACMR", *diff_args(scope)).split("\0") if name] + if not names: + return {} + listing = git(repo, "ls-files", "-s", "-z", "--", *names) if scope.head is None else git(repo, "ls-tree", "-r", "-z", scope.head, "--", *names) + blobs = {} + for entry in listing.split("\0"): + if not entry: + continue + meta, path = entry.split("\t", 1) + fields = meta.split() + blobs[path] = fields[1] if scope.head is None else fields[2] + return blobs + + +def patch_id(repo: Path, scope: Scope) -> str: + patch = git_bytes(repo, ["diff", *diff_args(scope)], None) + if not patch.strip(): + return "" + return git_bytes(repo, ["patch-id", "--stable"], patch).decode().split()[0] + + +def hunks(repo: Path, scope: Scope, paths: list[str]) -> str: + return git(repo, "diff", "-U3", *diff_args(scope), "--", *paths) if paths else "" + + +def line_text(repo: Path, blob: str, line: int | None) -> str: + if line is None or line < 1: + return "" + lines = git_bytes(repo, ["cat-file", "blob", blob], None).decode("utf-8", "replace").splitlines() + return lines[line - 1].strip() if line <= len(lines) else "" + + +def tree(repo: Path) -> str: + return git(repo, "rev-parse", "HEAD^{tree}").strip() + + +def dirty(repo: Path) -> bool: + return bool(git(repo, "status", "--porcelain", "--untracked-files=no").strip()) + + +def common_dir(repo: Path) -> Path: + return Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir").strip()) + + +def push_base(repo: Path) -> str | None: + """Returns: + The commit a push starts from: the upstream, or without one the + merge base with the default branch; None when neither exists. + """ + pushed = upstream(repo) + if pushed is not None: + return pushed + default = default_branch(repo) + return None if default is None else git(repo, "merge-base", default, "HEAD").strip() diff --git a/skills/kvb-code-review/scripts/review_stamp.py b/skills/kvb-code-review/scripts/review_stamp.py new file mode 100644 index 0000000..7b80d4e --- /dev/null +++ b/skills/kvb-code-review/scripts/review_stamp.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +import datetime +import json +import shlex +from pathlib import Path + +import review_memory +import review_scope +from review_lenses import BLOCKING, SEVERITIES + +CLEAN = "clean" +BLOCKED = "blocked" +PENDING = "pending" +WAIVED = "waived" +MISSING = "missing" +CONFIRMED = "confirmed" +REFUTED = "refuted" +WAIVE = "Waive" +KEEP = "Keep blocked" +HUB_SECONDS = 10 +OPERATORS = ("&&", "||", ";", "|") +PUSHED = "pushed:" +FLAGS = ("--check", "--dir", "--command") +PUSH_TOOLS = ("gipsn", "git-sign-push") +PUSH_WORDS = ("push", "gipsn") +COLUMNS = ("Severity", "Lens", "File:line", "Finding", "Skeptic", "Evidence") +PORT_KEY = "KVB_ORCHESTRATOR_PORT=" +QUOTES = "'\"" + + +class Refused(Exception): + pass + + +def skeptic(entry: dict, verdicts: dict) -> str: + """Returns: + CONFIRMED or REFUTED once the lens skeptic, and for a critical or + high finding also its own skeptic, judged it; PENDING before. + """ + roles = ("lens", "blocker") if entry["severity"] in BLOCKING else ("lens",) + found = [verdicts.get(f"{entry['key']}:{role}") for role in roles] + if any(item is not None and item["verdict"] == REFUTED for item in found): + return REFUTED + return PENDING if None in found else CONFIRMED + + +def decide(findings: list[dict], verdicts: dict, unreviewed: list[str]) -> str: + states = [(entry, skeptic(entry, verdicts)) for entry in findings] + if any(entry["severity"] in BLOCKING and state == CONFIRMED for entry, state in states): + return BLOCKED + return PENDING if unreviewed or any(state == PENDING for _, state in states) else CLEAN + + +def cell(text: object) -> str: + return " ".join(str(text).split()).replace("|", "\\|") + + +def table(findings: list[dict], verdicts: dict) -> str: + ranked = sorted(findings, key=lambda entry: (SEVERITIES.index(entry["severity"]), entry["lens"], entry["path"], entry["line"] or 0)) + rows = [f"| {' | '.join(COLUMNS)} |", f"| {' | '.join('---' for _ in COLUMNS)} |"] + for entry in ranked: + state = skeptic(entry, verdicts) + proof = verdicts.get(f"{entry['key']}:lens", {}).get("evidence") or entry["evidence"] + place = entry["path"] if entry["line"] is None else f"{entry['path']}:{entry['line']}" + rows.append(f"| {' | '.join(cell(item) for item in (entry['severity'], entry['lens'], place, entry['message'], state, proof))} |") + return "\n".join(rows) + + +def stamps(repo: Path) -> Path: + return review_scope.common_dir(repo) / review_memory.STAMPS + + +def now() -> str: + return datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds") + + +def stamp(repo: Path, scope: review_scope.Scope, verdict: str, versions: dict[str, str]) -> str: + """Returns: + The stamped tree; Refused when the tracked tree is dirty, the review + is pending, or its target is not everything the push sends. + """ + if review_scope.dirty(repo): + raise Refused("the tracked tree is dirty; commit or drop the changes first") + head = review_scope.commit(repo, "HEAD") + base = review_scope.push_base(repo) + if scope.head != head or base is None or scope.base != base: + raise Refused(f"the target must be everything the push sends: range {base or ' '}..HEAD, not {scope.spec}") + if verdict == PENDING: + raise Refused("the review is pending: a lens or a skeptic has not answered") + tree = review_scope.tree(repo) + with review_memory.held(stamps(repo)) as data: + data[tree] = {"verdict": verdict, "target": scope.spec, "base": base, "head": head, "stamped": now(), "lenses": versions} + return tree + + +def entry_of(repo: Path) -> tuple[str, dict | None]: + tree = review_scope.tree(repo) + return tree, review_memory.read(stamps(repo)).get(tree) + + +def question(repo: Path) -> str: + return f"Waive the review for the push of tree {review_scope.tree(repo)} in {repo}?" + + +def hub_port() -> int: + """Returns: + The port the installed hub publishes, KVB_ORCHESTRATOR_PORT of the + .env the operator's install writes outside every agent's sandbox; + Refused when no hub is installed. + """ + # Trip-wire: never take the port from argv or the stamp file; an agent writes both and could aim verify at its own listener. + env = Path.home() / ".local" / "share" / "kvb-orchestrator" / ".env" + try: + lines = env.read_text(encoding="utf-8").splitlines() + except OSError as error: + raise Refused(f"no installed hub: {error}") from error + for line in lines: + value = line.removeprefix(PORT_KEY) + if value != line and value.isdigit(): + return int(value) + raise Refused(f"{env} names no {PORT_KEY.rstrip('=')}") + + +def operator_message(port: int, message: str, answer: str, agent: str) -> dict: + import urllib.request + + body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "operator_message", "arguments": {"id": message, "text": answer, "to": agent}}} + request = urllib.request.Request(f"http://127.0.0.1:{port}/mcp", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST") + try: + with urllib.request.urlopen(request, timeout=HUB_SECONDS) as reply: + data = json.load(reply) + except (OSError, ValueError) as error: + raise Refused(f"the hub on port {port} did not answer: {error}") from error + result = data.get("result") if isinstance(data, dict) else None + if not isinstance(result, dict) or result.get("isError") or not isinstance(result.get("structuredContent"), dict): + content = result.get("content") if isinstance(result, dict) else None + raise Refused(f"the hub refused the waiver: {content[0].get('text') if content else data}") + return result["structuredContent"] + + +def verify(message: str, answer: str, agent: str, tree: str) -> None: + signed = operator_message(hub_port(), message, answer, agent) + if signed.get("match") is not True or " ".join(str(signed.get("text")).split()) != " ".join(answer.split()): + raise Refused("the signed text differs from the waiver") + if f"tree {tree}" not in answer or not answer.endswith(f"): {WAIVE}"): + raise Refused(f"the signed answer does not waive tree {tree}") + + +def waive(repo: Path, message: str, answer: str, agent: str) -> str: + tree = review_scope.tree(repo) + verify(message, answer, agent, tree) + with review_memory.held(stamps(repo)) as data: + data[tree] = {"verdict": WAIVED, "message": message, "answer": answer, "agent": agent, "waived": now()} + return tree + + +def options(tokens: list[str]) -> dict[str, str]: + """Args: + tokens: the shell words after `operator.py add`. + + Returns: + The last value of --check, --dir and --command up to the first shell + operator, as `--flag value` or `--flag=value`. + """ + found = {} + for position, item in enumerate(tokens): + if item in OPERATORS: + break + name, joined, value = item.partition("=") + if joined and name in FLAGS: + found[name] = value + elif item in FLAGS and position + 1 < len(tokens): + found[item] = tokens[position + 1] + return found + + +def pushes(command: str) -> bool: + try: + words = [Path(word.strip(QUOTES)).name for part in shlex.split(command) for word in part.split()] + except ValueError: + return any(word in command for word in PUSH_WORDS) + return any(word in PUSH_TOOLS for word in words) or any(word == "git" and "push" in words[position + 1:] for position, word in enumerate(words)) + + +def target(found: dict[str, str]) -> str | None: + check = found.get("--check") + if check is not None and check.startswith(PUSHED): + return check.removeprefix(PUSHED) + if "--command" in found and "--dir" in found and pushes(found["--command"]): + return found["--dir"] + return None + + +def adds(tokens: list[str]) -> list[int]: + return [start + 2 for start, token in enumerate(tokens[:-1]) if Path(token).name == "operator.py" and tokens[start + 1] == "add"] + + +def pushed_dirs(command: str) -> list[str]: + """Returns: + The directory of every push row in the shell command, in order: each + `operator.py add` with `--check pushed: `, or whose --command + runs git push, gipsn or git-sign-push in its --dir. + """ + if "operator.py" not in command or not any(word in command for word in PUSH_WORDS): + return [] + try: + tokens = shlex.split(command) + except ValueError: + return [] + return [directory for start in adds(tokens) if (directory := target(options(tokens[start:]))) is not None] + + +def refusal(directory: str) -> str | None: + """Returns: + Why a push row for the directory may not be added, or None when its + HEAD tree carries a clean stamp or a waiver the hub verifies again. + """ + repo = Path(directory) + try: + tree, entry = entry_of(repo) + except (review_scope.ScopeError, ValueError, TypeError, OSError) as error: + return f"no clean review: {error}" + if entry is None or entry.get("verdict") not in (CLEAN, WAIVED): + return f"no clean review for tree {tree}" + if entry["verdict"] == WAIVED: + try: + verify(entry["message"], entry["answer"], entry["agent"], tree) + except (Refused, KeyError) as error: + return f"no clean review for tree {tree}: the waiver did not verify ({error})" + return None diff --git a/skills/kvb-git-push/SKILL.md b/skills/kvb-git-push/SKILL.md index 91bcddf..9f25394 100644 --- a/skills/kvb-git-push/SKILL.md +++ b/skills/kvb-git-push/SKILL.md @@ -42,7 +42,11 @@ hands over, `kvb-git-pr-create`, `kvb-git-update-branches` and 6. **Red**: fix every failure at its root cause, commit the fix by the project's commit rules, and rerun the full gate from step 2, never only the failed targets. No push command is handed over until it is green. -7. **Hand over** through the `kvb-org-operator` skill the push command the +7. **Review**: `${CLAUDE_SKILL_DIR}/../kvb-code-review/scripts/review.py + status --repo ` prints `review: clean` or `review: waived` for the + gated tree; otherwise run the `kvb-code-review` skill on everything the + push sends first. The pre-bash hook refuses the push row anyway. +8. **Hand over** through the `kvb-org-operator` skill the push command the repository's agent rules name (for example the operator's `gipsn` alias), with the gated tree hash, the log path and the gate's result line verbatim. diff --git a/skills/kvb-org-organize/scripts/hooks.py b/skills/kvb-org-organize/scripts/hooks.py index f9d0a94..2ee5a7c 100755 --- a/skills/kvb-org-organize/scripts/hooks.py +++ b/skills/kvb-org-organize/scripts/hooks.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Run the skills' Bash hooks in one interpreter. -pre-bash radio.py block, watch.py block, queue.py block, graph.py hook +pre-bash radio.py block, watch.py block, queue.py block, graph.py hook, review_hook.py post-bash watch.py watch, log.py persist Every handler reads the same hook event; exit 2 of any handler blocks with the @@ -26,6 +26,7 @@ HANDLERS = { ("kvb-org-organize/scripts/watch.py", "block"), ("kvb-org-queue/scripts/queue.py", "block"), ("kvb-agent-optimize/scripts/graph.py", "hook"), + ("kvb-code-review/scripts/review_hook.py", "hook"), ), "post-bash": ( ("kvb-org-organize/scripts/watch.py", "watch"), diff --git a/tests/review_support.py b/tests/review_support.py new file mode 100644 index 0000000..79127e4 --- /dev/null +++ b/tests/review_support.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import contextlib +import http.server +import json +import os +import shutil +import subprocess +import threading +from collections.abc import Iterator +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +SKILL = REPO_ROOT / "skills" / "kvb-code-review" +LENS_SCRIPTS = { + "security": "kvb-check-security/scripts/security.py", + "principles": "kvb-check-principles/scripts/principles.py", + "performance": "kvb-check-efficiency/scripts/measure.py", + "queue": "kvb-org-queue/scripts/queue.py", +} +OUTPUTS = {"security": {"security": 100, "findings": []}, "principles": [], "performance": {"efficiency": 90, "speed": 95}, "quality": {"findings": []}} +FAKE = """import json, os, subprocess, sys, time +NAME = {name!r} +with open(os.environ["REVIEW_LOG"], "a", encoding="utf-8") as log: + log.write(json.dumps([NAME, time.time(), sys.argv[1:]]) + "\\n") +if NAME == "queue": + done = subprocess.run(sys.argv[sys.argv.index("--") + 1:], check=False) + sys.exit(done.returncode) +if NAME == "quality" and sys.argv[1:] == ["--version"]: + print("quality 0.3.0") + sys.exit(0) +plan = json.loads(os.environ.get("REVIEW_FAKE", "{{}}")).get(NAME, {{}}) +time.sleep(plan.get("sleep", 0)) +print(json.dumps(plan.get("out", {default!r}))) +sys.exit(plan.get("exit", 0)) +""" +GH = """import json, os, sys +print(os.environ.get("GH_PR", "")) +sys.exit(0 if os.environ.get("GH_PR") else 1) +""" +STANDARDS = { + "AGENTS.md": "# Agents\n\nThe whole agents body sentence that a brief must never carry.\n\n## Comments\n\nNo comments.\n", + "CONTRIBUTING.md": "# Contributing\n\nRead the docs.\n", + "docs/contributing/style.md": "# Style\n\n## Names\n\nNames say what a thing is.\n", + "roles/web-app-x/AGENTS.md": "# Role x\n\nKeep the role small.\n", +} +GIT_ENV = {"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1", "GIT_AUTHOR_NAME": "Test", "GIT_AUTHOR_EMAIL": "test@example.org", + "GIT_COMMITTER_NAME": "Test", "GIT_COMMITTER_EMAIL": "test@example.org"} + + +def git(repo: Path, *args: str) -> str: + return subprocess.run(["git", *args], cwd=repo, env={**os.environ, **GIT_ENV}, capture_output=True, text=True, check=True).stdout + + +def install(root: Path, with_quality: bool) -> dict[str, str]: + """Args: + root: a scratch folder that becomes a skills root and a bin folder. + with_quality: whether a fake quality CLI is on PATH. + + Returns: + The environment review.py runs in: PATH with the fake gh, the log + every fake lens appends its start to, and the fake plan variable. + """ + shutil.copytree(SKILL, root / "skills" / "kvb-code-review", ignore=shutil.ignore_patterns("__pycache__")) + for name, script in LENS_SCRIPTS.items(): + path = root / "skills" / script + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(FAKE.format(name=name, default=OUTPUTS.get(name, {})), encoding="utf-8") + (root / "skills" / "kvb-check-legal").mkdir(parents=True, exist_ok=True) + (root / "skills" / "kvb-check-legal" / "checks.md").write_text("# Legal checks\n\n## Licences\n\nCheck them.\n", encoding="utf-8") + bin_dir = root / "bin" + bin_dir.mkdir() + (bin_dir / "gh").write_text(f"#!/usr/bin/python3\n{GH}", encoding="utf-8") + if with_quality: + (bin_dir / "quality").write_text(f"#!/usr/bin/python3\n{FAKE.format(name='quality', default=OUTPUTS['quality'])}", encoding="utf-8") + for tool in bin_dir.iterdir(): + tool.chmod(0o755) + return {**os.environ, **GIT_ENV, "PATH": f"{bin_dir}:/usr/bin:/bin", "REVIEW_LOG": str(root / "lens.log"), "REVIEW_FAKE": "{}"} + + +def hub_home(root: Path, env: dict[str, str], port: int) -> dict[str, str]: + """Returns: + The environment with HOME at a folder whose installed hub .env + publishes the port, as review_stamp.hub_port() reads it. + """ + hub_env = root / "home" / ".local" / "share" / "kvb-orchestrator" / ".env" + hub_env.parent.mkdir(parents=True, exist_ok=True) + hub_env.write_text(f"KVB_ORCHESTRATOR_UID=1000\nKVB_ORCHESTRATOR_PORT={port}\n", encoding="utf-8") + return {**env, "HOME": str(root / "home")} + + +def fixture(root: Path) -> Path: + """Returns: + A repository on master whose upstream origin/master holds the + standards and src/app.py, with one unpushed commit that changes + src/app.py and adds roles/web-app-x/tasks.yml. + """ + remote, repo = root / "remote.git", root / "repo" + subprocess.run(["git", "init", "--bare", "-b", "master", str(remote)], env={**os.environ, **GIT_ENV}, capture_output=True, check=True) + repo.mkdir() + git(repo, "init", "-b", "master") + for name, text in {**STANDARDS, "src/app.py": "VALUE = 1\nNAME = 'app'\n"}.items(): + (repo / name).parent.mkdir(parents=True, exist_ok=True) + (repo / name).write_text(text, encoding="utf-8") + git(repo, "add", "-A") + git(repo, "commit", "-m", "base") + git(repo, "remote", "add", "origin", str(remote)) + git(repo, "push", "-u", "origin", "master") + change(repo, {"src/app.py": "VALUE = 2\nNAME = 'app'\n", "roles/web-app-x/tasks.yml": "- name: x\n"}, "change") + return repo + + +def change(repo: Path, files: dict[str, str], message: str) -> None: + for name, text in files.items(): + (repo / name).parent.mkdir(parents=True, exist_ok=True) + (repo / name).write_text(text, encoding="utf-8") + git(repo, "add", "-A") + git(repo, "commit", "-m", message) + + +def review(root: Path, env: dict[str, str], *args: str) -> subprocess.CompletedProcess: + script = root / "skills" / "kvb-code-review" / "scripts" / "review.py" + return subprocess.run(["/usr/bin/python3", "-I", str(script), *args], env=env, capture_output=True, text=True, timeout=120, check=False) + + +def starts(root: Path) -> list[list]: + log = root / "lens.log" + return [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.exists() else [] + + +@contextlib.contextmanager +def hub(signed: dict[str, tuple[str, str]]) -> Iterator[int]: + """Args: + signed: per message id the text the operator signed and its agent. + + Returns: + The port of a fake hub whose operator_message answers match for + exactly those messages, as the real hub's tools/call does. + """ + + class Handler(http.server.BaseHTTPRequestHandler): + def do_POST(self): + request = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + arguments = request["params"]["arguments"] + known = signed.get(arguments["id"]) + if known is not None and known == (arguments["text"], arguments["to"]): + payload = {"match": True, "id": arguments["id"], "to": arguments["to"], "class": "call", "text": arguments["text"]} + result = {"content": [{"type": "text", "text": json.dumps(payload)}], "structuredContent": payload, "isError": False} + else: + result = {"content": [{"type": "text", "text": "no match"}], "isError": True} + body = json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_args): + return + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server.server_address[1] + finally: + server.shutdown() + server.server_close() diff --git a/tests/test_code_review.py b/tests/test_code_review.py new file mode 100644 index 0000000..105e6ad --- /dev/null +++ b/tests/test_code_review.py @@ -0,0 +1,306 @@ +from __future__ import annotations + +import json +import re +import tempfile +import time +import unittest +from pathlib import Path + +from review_support import ( + SKILL, + change, + fixture, + git, + hub, + hub_home, + install, + review, + starts, +) + +HIGH = {"rule": "AGENTS.md:5", "severity": "high", "path": "src/app.py", "line": 1, "message": "comment rule broken", "evidence": "line 1"} +MEDIUM = {**HIGH, "severity": "medium"} + + +class ReviewCase(unittest.TestCase): + with_quality = False + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.env = install(self.root, self.with_quality) + self.repo = fixture(self.root) + self.base = git(self.repo, "rev-parse", "@{u}").strip() + self.target = f"range {self.base}..HEAD" + + def call(self, *args: str): + return review(self.root, self.env, *args) + + def ok(self, *args: str) -> str: + done = self.call(*args) + self.assertEqual(done.returncode, 0, done.stderr) + return done.stdout + + def plan(self) -> dict: + return json.loads(self.ok("plan", "--repo", str(self.repo), "--target", self.target)) + + def record(self, lens: str, findings: list[dict]) -> None: + path = self.root / f"{lens}.json" + path.write_text(json.dumps(findings), encoding="utf-8") + self.ok("record", "--repo", str(self.repo), "--target", self.target, "--lens", lens, "--findings", str(path)) + + def judge(self, verdicts: list[dict]) -> None: + path = self.root / "verdicts.json" + path.write_text(json.dumps(verdicts), encoding="utf-8") + self.ok("judge", "--repo", str(self.repo), "--target", self.target, "--verdicts", str(path)) + + def reviewed(self, findings: list[dict]) -> None: + self.ok("run", "--repo", str(self.repo), "--target", self.target) + self.record("standards", findings) + self.record("legal", []) + + def lens(self, name: str) -> dict: + return next(item for item in self.plan()["lenses"] if item["lens"] == name) + + +class TestTarget(ReviewCase): + def test_staged_changes_come_first(self): + (self.repo / "src" / "app.py").write_text("VALUE = 3\n", encoding="utf-8") + git(self.repo, "add", "src/app.py") + self.assertEqual(self.ok("target", "--repo", str(self.repo)).strip(), "staged") + + def test_an_open_pull_request_comes_before_the_branch(self): + self.env["GH_PR"] = json.dumps({"number": 7, "state": "OPEN", "baseRefName": "master", "headRefOid": "x"}) + self.assertEqual(self.ok("target", "--repo", str(self.repo)).strip(), "pr 7") + + def test_commits_ahead_of_the_default_branch_name_the_branch(self): + git(self.repo, "switch", "-c", "feature") + change(self.repo, {"src/new.py": "X = 1\n"}, "feature work") + self.assertEqual(self.ok("target", "--repo", str(self.repo)).strip(), "branch master") + + def test_unpushed_commits_on_the_default_branch_name_the_push_range(self): + self.assertEqual(self.ok("target", "--repo", str(self.repo)).strip(), f"range {self.base}..HEAD") + + def test_nothing_detected_leaves_the_range_to_the_operator(self): + git(self.repo, "push") + self.assertEqual(self.ok("target", "--repo", str(self.repo)).strip(), "range") + + def test_the_first_question_lists_the_four_targets_with_the_detected_one_recommended(self): + text = (SKILL / "SKILL.md").read_text(encoding="utf-8") + first = text.index("## Step 1") + self.assertLess(first, text.index("## Step 2")) + self.assertIn("the detected one first and marked `(Recommended)`", text) + labels = [text.index(label, first) for label in ("**Staged changes**", "**Pull request**", "**Branch against the default branch**", "**Commit range**")] + self.assertEqual(labels, sorted(labels)) + + +class TestLenses(ReviewCase): + def test_the_standards_lens_names_every_standards_file_and_the_touched_role(self): + self.reviewed([]) + out = self.call("verdict", "--repo", str(self.repo), "--target", self.target).stdout + self.assertIn("standards: AGENTS.md, CONTRIBUTING.md, docs/contributing/style.md, roles/web-app-x/AGENTS.md", out) + + def test_every_script_lens_runs_or_is_listed_skipped_with_its_reason(self): + report = json.loads(self.ok("run", "--repo", str(self.repo), "--target", self.target)) + self.assertEqual(report["quality"]["status"], "skipped") + self.assertIn("quality is not installed", report["quality"]["reason"]) + self.assertEqual(report["performance"]["status"], "skipped") + self.assertEqual({report[name]["status"] for name in ("security", "principles")}, {"ran"}) + out = self.call("verdict", "--repo", str(self.repo), "--target", self.target).stdout + self.assertIn("skipped: quality: quality is not installed", out) + self.assertIn("skipped: performance: no runnable code to measure", out) + + def test_each_of_the_seven_check_skills_runs_is_skipped_or_feeds_the_score_block(self): + self.reviewed([]) + out = self.call("verdict", "--repo", str(self.repo), "--target", self.target).stdout + for shown in ("security (kvb-check-security) ran", "principles (kvb-check-principles) ran", "performance (kvb-check-efficiency) skipped", "legal (kvb-check-legal) ran", "quality skipped", "standards ran"): + self.assertIn(shown, out) + self.assertIn("score block (step 5): kvb-check-break-risk, kvb-check-confidence, kvb-check-score", out) + + def test_without_harness_skills_the_verdict_says_harness_none_and_the_own_lenses_still_count(self): + self.reviewed([]) + out = self.call("verdict", "--repo", str(self.repo), "--target", self.target).stdout + self.assertIn("harness: none", out) + self.assertIn("verdict: clean", out) + + def test_listed_harness_skills_are_lenses_the_verdict_waits_for(self): + self.reviewed([]) + harness = ["--harness", "code-review", "--harness", "security-review"] + pending = self.call("verdict", "--repo", str(self.repo), "--target", self.target, *harness) + self.assertEqual(pending.returncode, 1) + self.assertIn("unreviewed: harness:code-review", pending.stdout) + for name in ("code-review", "security-review"): + path = self.root / f"{name}.json" + path.write_text("[]", encoding="utf-8") + self.ok("record", "--repo", str(self.repo), "--target", self.target, "--lens", f"harness:{name}", "--findings", str(path), *harness) + self.assertIn("harness: code-review, security-review", self.ok("verdict", "--repo", str(self.repo), "--target", self.target, *harness)) + + +class TestQualityLens(ReviewCase): + with_quality = True + + def test_quality_check_runs_with_the_base_of_a_range_and_staged_for_staged_changes(self): + self.ok("run", "--repo", str(self.repo), "--target", self.target) + quality = [entry for entry in starts(self.root) if entry[0] == "quality"] + self.assertEqual(quality[-1][2], ["check", "--base", self.base, "--json"]) + (self.repo / "src" / "app.py").write_text("VALUE = 4\n", encoding="utf-8") + git(self.repo, "add", "src/app.py") + self.ok("run", "--repo", str(self.repo), "--target", "staged") + quality = [entry for entry in starts(self.root) if entry[0] == "quality"] + self.assertEqual(quality[-1][2], ["check", "--staged", "--json"]) + + +class TestMemory(ReviewCase): + def test_lenses_start_together_and_heavy_ones_wait_in_the_queue(self): + self.env["REVIEW_FAKE"] = json.dumps({name: {"sleep": 1} for name in ("security", "principles")}) + self.ok("run", "--repo", str(self.repo), "--target", self.target, "--task", "work/review") + started = {name: at for name, at, _ in starts(self.root) if name in ("security", "principles")} + self.assertLess(abs(started["security"] - started["principles"]), 1.0) + queued = [argv for name, _, argv in starts(self.root) if name == "queue"] + self.assertEqual(len(queued), 1) + self.assertIn("security.py", " ".join(queued[0])) + + def test_an_unchanged_tree_starts_no_lens_and_answers_from_memory_within_five_seconds(self): + self.reviewed([MEDIUM]) + self.judge([{"key": self.plan()["skeptics"][0]["key"], "role": "lens", "verdict": "confirmed", "evidence": "read"}]) + (self.root / "lens.log").unlink() + began = time.monotonic() + self.ok("run", "--repo", str(self.repo), "--target", self.target) + out = self.ok("verdict", "--repo", str(self.repo), "--target", self.target) + self.assertLess(time.monotonic() - began, 5.0) + self.assertEqual(starts(self.root), []) + self.assertEqual(self.plan()["skeptics"], []) + self.assertIn("comment rule broken", out) + + def test_one_changed_file_reruns_the_file_lens_on_it_alone_and_every_diff_lens(self): + self.reviewed([]) + change(self.repo, {"src/app.py": "VALUE = 5\nNAME = 'app'\n"}, "again") + self.assertEqual(self.lens("standards")["missing"], ["src/app.py"]) + self.assertEqual(self.lens("security")["status"], "run") + + def test_a_changed_standards_file_reruns_the_standards_lens_on_every_file(self): + self.reviewed([]) + change(self.repo, {"CONTRIBUTING.md": "# Contributing\n\nRead the docs twice.\n"}, "rules") + self.assertEqual(sorted(self.lens("standards")["missing"]), ["CONTRIBUTING.md", "roles/web-app-x/tasks.yml", "src/app.py"]) + self.assertEqual(self.lens("legal")["missing"], ["CONTRIBUTING.md"]) + + def test_a_skeptic_verdict_holds_for_the_same_finding_and_never_for_a_changed_flagged_line(self): + self.reviewed([MEDIUM]) + self.judge([{"key": self.plan()["skeptics"][0]["key"], "role": "lens", "verdict": "confirmed", "evidence": "read"}]) + change(self.repo, {"docs/contributing/style.md": "# Style\n\n## Names\n\nNames say what a thing is, always.\n"}, "rules") + self.record("standards", [MEDIUM]) + self.assertEqual(self.plan()["skeptics"], []) + change(self.repo, {"src/app.py": "VALUE = 9\nNAME = 'app'\n"}, "line") + self.record("standards", [MEDIUM]) + self.assertEqual([item["roles"] for item in self.plan()["skeptics"]], [["lens"]]) + + def test_a_brief_holds_the_hunks_and_the_section_index_never_a_whole_standards_file(self): + text = self.ok("brief", "--repo", str(self.repo), "--target", self.target, "--lens", "standards") + self.assertIn("+VALUE = 2", text) + self.assertIn("AGENTS.md:1 # Agents", text) + self.assertNotIn("The whole agents body sentence", text) + self.assertNotIn("Read the docs.", text) + + +class TestVerdictAndStamp(ReviewCase): + def confirm(self, roles: tuple[str, ...]) -> None: + key = self.plan()["skeptics"][0]["key"] + self.judge([{"key": key, "role": role, "verdict": "confirmed", "evidence": "reproduced"} for role in roles]) + + def test_a_confirmed_high_finding_blocks(self): + self.reviewed([HIGH]) + self.assertEqual(self.plan()["skeptics"][0]["roles"], ["lens", "blocker"]) + self.confirm(("lens",)) + self.assertIn("verdict: pending", self.call("verdict", "--repo", str(self.repo), "--target", self.target).stdout) + self.confirm(("blocker",)) + done = self.call("verdict", "--repo", str(self.repo), "--target", self.target) + self.assertEqual(done.returncode, 1) + self.assertIn("verdict: blocked", done.stdout) + self.assertRegex(done.stdout, re.compile(r"\| high \| standards \| src/app\.py:1 \| comment rule broken \| confirmed \|")) + + def test_only_medium_and_low_confirmed_is_clean(self): + self.reviewed([MEDIUM, {**MEDIUM, "severity": "low", "line": 2, "message": "name"}]) + self.judge([{"key": item["key"], "role": "lens", "verdict": "confirmed", "evidence": "read"} for item in self.plan()["skeptics"]]) + self.assertIn("verdict: clean", self.ok("verdict", "--repo", str(self.repo), "--target", self.target)) + + def test_a_refuted_finding_stays_in_the_table_and_does_not_block(self): + self.reviewed([HIGH]) + key = self.plan()["skeptics"][0]["key"] + self.judge([{"key": key, "role": "lens", "verdict": "refuted", "evidence": "the rule allows it"}]) + out = self.ok("verdict", "--repo", str(self.repo), "--target", self.target) + self.assertIn("| refuted | the rule allows it |", out) + self.assertIn("verdict: clean", out) + + def test_the_stamp_refuses_a_dirty_tree_and_a_target_short_of_the_push(self): + self.reviewed([]) + (self.repo / "src" / "app.py").write_text("dirty\n", encoding="utf-8") + dirty = self.call("stamp", "--repo", str(self.repo), "--target", self.target) + self.assertEqual((dirty.returncode, "dirty" in dirty.stderr), (2, True)) + git(self.repo, "checkout", "--", "src/app.py") + change(self.repo, {"src/more.py": "M = 1\n"}, "more") + short = self.call("stamp", "--repo", str(self.repo), "--target", "range HEAD~1..HEAD") + self.assertEqual((short.returncode, "everything the push sends" in short.stderr), (2, True)) + + def test_status_follows_the_tree_and_survives_a_signing_only_rewrite(self): + self.assertEqual(self.call("status", "--repo", str(self.repo)).stdout.strip(), "review: missing") + self.reviewed([]) + self.ok("stamp", "--repo", str(self.repo), "--target", self.target) + self.assertEqual(self.ok("status", "--repo", str(self.repo)).strip(), "review: clean") + git(self.repo, "commit", "--amend", "--no-edit", "--date", "2020-01-01T00:00:00") + self.assertEqual(self.ok("status", "--repo", str(self.repo)).strip(), "review: clean") + change(self.repo, {"src/app.py": "VALUE = 7\n"}, "new") + done = self.call("status", "--repo", str(self.repo)) + self.assertEqual((done.returncode, done.stdout.strip()), (1, "review: missing")) + + def test_a_planted_high_finding_ends_blocked_and_the_same_run_again_starts_no_lens(self): + planted = {"security": 40, "findings": [{"severity": "high", "rule": "SEC-1", "path": "src/app.py", "line": 1, "sha1": "x", "context": None}]} + self.env["REVIEW_FAKE"] = json.dumps({"security": {"out": planted}}) + self.reviewed([]) + key = next(item["key"] for item in self.plan()["skeptics"] if item["lens"] == "security") + self.judge([{"key": key, "role": role, "verdict": "confirmed", "evidence": "exploit"} for role in ("lens", "blocker")]) + self.assertIn("verdict: blocked", self.call("verdict", "--repo", str(self.repo), "--target", self.target).stdout) + (self.root / "lens.log").unlink() + self.ok("run", "--repo", str(self.repo), "--target", self.target) + self.assertEqual(starts(self.root), []) + self.ok("stamp", "--repo", str(self.repo), "--target", self.target) + status = self.call("status", "--repo", str(self.repo)) + self.assertEqual((status.returncode, status.stdout.strip()), (1, "review: blocked")) + + +class TestPushStep(unittest.TestCase): + def test_kvb_git_push_hands_no_push_row_before_a_clean_or_waived_review(self): + text = " ".join((SKILL.parent / "kvb-git-push" / "SKILL.md").read_text(encoding="utf-8").split()) + self.assertIn("kvb-code-review/scripts/review.py status --repo ` prints `review: clean` or `review: waived` for the gated tree", text) + self.assertLess(text.index("**Review**"), text.index("**Hand over**")) + + +class TestWaiver(ReviewCase): + def answer(self) -> str: + question = json.loads(self.ok("question", "--repo", str(self.repo)))["question"] + return f"Choice for decision d1 ({question}): Waive" + + def test_a_signed_waiver_records_and_status_says_waived(self): + answer = self.answer() + with hub({"m1": (answer, "Skills")}) as port: + self.env = hub_home(self.root, self.env, port) + self.ok("waive", "--repo", str(self.repo), "--message", "m1", "--answer", answer, "--agent", "Skills") + self.assertEqual(self.ok("status", "--repo", str(self.repo)).strip(), "review: waived") + + def test_an_unsigned_or_foreign_answer_and_an_unreachable_hub_refuse(self): + answer = self.answer() + with hub({"m1": (answer, "Skills")}) as port: + self.env = hub_home(self.root, self.env, port) + forged = self.call("waive", "--repo", str(self.repo), "--message", "m1", "--answer", answer, "--agent", "Other") + kept = self.call("waive", "--repo", str(self.repo), "--message", "m2", "--answer", answer.replace(": Waive", ": Keep blocked"), "--agent", "Skills") + gone = self.call("waive", "--repo", str(self.repo), "--message", "m1", "--answer", answer, "--agent", "Skills") + self.assertEqual([forged.returncode, kept.returncode, gone.returncode], [2, 2, 2]) + self.assertIn("the hub refused the waiver", forged.stderr) + self.assertIn("the hub refused the waiver", kept.stderr) + self.assertIn("did not answer", gone.stderr) + self.assertEqual(self.call("status", "--repo", str(self.repo)).stdout.strip(), "review: missing") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 61e0323..de54c1e 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -2,12 +2,15 @@ from __future__ import annotations import json import os +import shlex import shutil import subprocess import tempfile import unittest from pathlib import Path +from review_support import change, fixture, git, hub, hub_home, install, review + REPO_ROOT = Path(__file__).resolve().parents[1] DISPATCHER = REPO_ROOT / "skills" / "kvb-org-organize" / "scripts" / "hooks.py" SCRIPTS = { @@ -15,8 +18,10 @@ SCRIPTS = { "watch": "kvb-org-organize/scripts/watch.py", "queue": "kvb-org-queue/scripts/queue.py", "graph": "kvb-agent-optimize/scripts/graph.py", + "review": "kvb-code-review/scripts/review_hook.py", "log": "kvb-org-perform/scripts/log.py", } +PRE_BASH = ["radio", "watch", "queue", "graph", "review"] FAKE = """import json, os, sys NAME = {name!r} @@ -64,21 +69,21 @@ class TestHooks(unittest.TestCase): def test_each_event_runs_its_handlers_in_order_with_the_same_event_and_their_own_subcommand(self): self.assertEqual(self.dispatch("pre-bash", {}).returncode, 0) - self.assertEqual(self.ran(), [["radio", ["block"], "make test"], ["watch", ["block"], "make test"], ["queue", ["block"], "make test"], ["graph", ["hook"], "make test"]]) + self.assertEqual(self.ran(), [["radio", ["block"], "make test"], ["watch", ["block"], "make test"], ["queue", ["block"], "make test"], ["graph", ["hook"], "make test"], ["review", ["hook"], "make test"]]) self.assertEqual(self.dispatch("post-bash", {}).returncode, 0) self.assertEqual(self.ran(), [["watch", ["watch"], "make test"], ["log", ["persist"], "make test"]]) def test_exit_two_blocks_with_the_text_of_every_blocking_handler_after_all_ran(self): done = self.dispatch("pre-bash", {"watch": {"code": 2, "err": "watch: disk full"}, "queue": {"exit": 2, "err": "queue: through the queue"}, "graph": {"out": json.dumps({"systemMessage": "graph"})}}) self.assertEqual((done.returncode, done.stdout, done.stderr), (2, "", "watch: disk full\nqueue: through the queue\n")) - self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "queue", "graph"]) + self.assertEqual([name for name, _, _ in self.ran()], PRE_BASH) def test_a_crash_leaves_the_other_handlers_running_and_their_answers_merged(self): context = {"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": "watch: alert"}} done = self.dispatch("pre-bash", {"radio": {"crash": True}, "watch": {"out": json.dumps(context)}, "queue": {"out": json.dumps(ASK)}, "graph": {"out": json.dumps({"systemMessage": "graph: notice"})}}) self.assertEqual(done.returncode, 0, done.stderr) self.assertIn("RuntimeError: radio broke", done.stderr) - self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "queue", "graph"]) + self.assertEqual([name for name, _, _ in self.ran()], PRE_BASH) self.assertEqual(json.loads(done.stdout), { "hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": "watch: alert", "permissionDecision": "ask", "permissionDecisionReason": "held command meets an ask rule"}, "systemMessage": "graph: notice", @@ -92,11 +97,111 @@ class TestHooks(unittest.TestCase): def test_a_missing_handler_is_skipped_and_an_unknown_event_is_refused(self): (self.root / SCRIPTS["queue"]).unlink() self.assertEqual(self.dispatch("pre-bash", {}).returncode, 0) - self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "graph"]) + self.assertEqual([name for name, _, _ in self.ran()], ["radio", "watch", "graph", "review"]) refused = self.dispatch("stop", {}) self.assertEqual(refused.returncode, 1) self.assertIn("usage: hooks.py pre-bash|post-bash", refused.stderr) +class TestReviewHook(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.env = install(self.root, with_quality=False) + shutil.rmtree(self.root / "skills" / "kvb-org-queue") + target = self.root / "skills" / "kvb-org-organize" / "scripts" / "hooks.py" + target.parent.mkdir(parents=True) + shutil.copy(DISPATCHER, target) + self.repo = fixture(self.root) + self.target = f"range {git(self.repo, 'rev-parse', '@{u}').strip()}..HEAD" + + def dispatch(self, command: str) -> subprocess.CompletedProcess: + event = json.dumps({"session_id": "s", "hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": {"command": command}}) + hooks = self.root / "skills" / "kvb-org-organize" / "scripts" / "hooks.py" + return subprocess.run(["/usr/bin/python3", "-I", str(hooks), "pre-bash"], input=event, env=self.env, capture_output=True, text=True, timeout=60, check=False) + + def push_row(self, check: str, command: str = "gipsn") -> str: + return f"/x/kvb-org-operator/scripts/operator.py add skills-push --dir {self.repo} --command {shlex.quote(command)} --reason 'push it' --check {check}" + + def ok(self, *args: str) -> str: + done = review(self.root, self.env, *args) + self.assertEqual(done.returncode, 0, done.stderr) + return done.stdout + + def stamp_clean(self) -> None: + self.ok("run", "--repo", str(self.repo), "--target", self.target) + empty = self.root / "empty.json" + empty.write_text("[]", encoding="utf-8") + for lens in ("standards", "legal"): + self.ok("record", "--repo", str(self.repo), "--target", self.target, "--lens", lens, "--findings", str(empty)) + self.ok("stamp", "--repo", str(self.repo), "--target", self.target) + + def test_a_push_row_without_a_clean_stamp_is_refused(self): + done = self.dispatch(self.push_row(f"pushed:{self.repo}")) + self.assertEqual(done.returncode, 2) + self.assertIn("kvb-code-review: no clean review for tree", done.stderr) + + def test_a_clean_stamp_lets_the_push_row_through_until_the_tree_changes(self): + self.stamp_clean() + self.assertEqual(self.dispatch(self.push_row(f"pushed:{self.repo}")).returncode, 0) + change(self.repo, {"src/app.py": "VALUE = 8\n"}, "later") + self.assertEqual(self.dispatch(self.push_row(f"pushed:{self.repo}")).returncode, 2) + + def test_a_stamp_file_that_holds_no_object_refuses_instead_of_crashing_open(self): + self.stamp_clean() + (self.repo / ".git" / "kvb-review.json").write_text("[]", encoding="utf-8") + done = self.dispatch(self.push_row(f"pushed:{self.repo}")) + self.assertEqual(done.returncode, 2) + self.assertIn("holds no JSON object", done.stderr) + + def test_other_commands_and_other_rows_pass_untouched(self): + for command in ("git status", self.push_row("manual", "make install"), f"echo pushed:{self.repo}", "git push origin master"): + self.assertEqual(self.dispatch(command).returncode, 0, command) + + def test_a_row_whose_command_pushes_needs_the_stamp_whatever_its_check(self): + commands = ("gipsn", "git push --no-verify origin HEAD:refs/heads/x", "git -c x=y push", "/usr/bin/git-sign-push", 'sh -c "git push"', "bash -c 'cd x && sh -c \"git push\"'") + rows = [self.push_row("manual", command) for command in commands] + for row in rows: + done = self.dispatch(row) + self.assertEqual(done.returncode, 2, row) + self.assertIn("no clean review for tree", done.stderr) + self.stamp_clean() + for row in rows: + self.assertEqual(self.dispatch(row).returncode, 0, row) + + def waiver(self) -> str: + question = json.loads(self.ok("question", "--repo", str(self.repo)))["question"] + return f"Choice for decision d1 ({question}): Waive" + + def test_a_waiver_passes_only_while_the_hub_verifies_it(self): + answer = self.waiver() + with hub({"m1": (answer, "Skills")}) as port: + self.env = hub_home(self.root, self.env, port) + self.ok("waive", "--repo", str(self.repo), "--message", "m1", "--answer", answer, "--agent", "Skills") + self.assertEqual(self.dispatch(self.push_row(f"pushed:{self.repo}")).returncode, 0) + gone = self.dispatch(self.push_row(f"pushed:{self.repo}")) + self.assertEqual(gone.returncode, 2) + self.assertIn("the waiver did not verify", gone.stderr) + + def test_a_waiver_aimed_at_another_listener_never_verifies(self): + answer = self.waiver() + with hub({}) as installed, hub({"m1": (answer, "Skills")}) as forged: + self.env = hub_home(self.root, self.env, installed) + refused = review(self.root, self.env, "waive", "--repo", str(self.repo), "--message", "m1", "--answer", answer, "--agent", "Skills", "--port", str(forged)) + self.assertEqual(refused.returncode, 2) + stamps = self.repo / ".git" / "kvb-review.json" + tree = git(self.repo, "rev-parse", "HEAD^{tree}").strip() + stamps.write_text(json.dumps({tree: {"verdict": "waived", "message": "m1", "answer": answer, "agent": "Skills", "port": forged}}), encoding="utf-8") + done = self.dispatch(self.push_row(f"pushed:{self.repo}")) + self.assertEqual(done.returncode, 2) + self.assertIn("the waiver did not verify", done.stderr) + + def test_a_waiver_without_an_installed_hub_is_refused(self): + done = review(self.root, {**self.env, "HOME": str(self.root / "no-home")}, "waive", "--repo", str(self.repo), "--message", "m1", "--answer", self.waiver(), "--agent", "Skills") + self.assertEqual(done.returncode, 2) + self.assertIn("no installed hub", done.stderr) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_hub_review_waiver.py b/tests/test_hub_review_waiver.py new file mode 100644 index 0000000..2ae48ce --- /dev/null +++ b/tests/test_hub_review_waiver.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from hub_case import HubCase +from kvb_orchestrator import batches +from review_support import fixture, hub_home, install, review + + +class TestHubReviewWaiver(HubCase): + def setUp(self): + super().setUp() + self.claim("s2", "Stage") + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.env = hub_home(self.root, install(self.root, with_quality=False), self.port) + self.repo = fixture(self.root) + + def review(self, *args: str) -> subprocess.CompletedProcess: + return review(self.root, self.env, *args) + + def signed_choice(self, label: str) -> dict: + card = json.loads(self.review("question", "--repo", str(self.repo)).stdout) + result = self.tool("decision_request", {"question": card["question"], "options": card["options"], "agent": "Stage", "recommended": card["recommended"]}) + self.assertFalse(result["isError"], result) + decision_id = result["structuredContent"]["id"] + entry = self.entry("decision", decision_id, label, "") + with mock.patch.object(batches, "UNDO", 0.05): + self.assertEqual(self.approve([entry], self.signed([entry], self.pin()))[0], 202) + self.settle(lambda: self.choice(decision_id) == label) + return self.tool("decision_wait", {"id": decision_id, "timeout_seconds": 0})["structuredContent"] + + def waive(self, state: dict, agent: str) -> subprocess.CompletedProcess: + return self.review("waive", "--repo", str(self.repo), "--message", state["message"], "--answer", state["answer"], "--agent", agent) + + def status(self) -> str: + return self.review("status", "--repo", str(self.repo)).stdout.strip() + + def hook(self) -> subprocess.CompletedProcess: + command = f"operator.py add skills-push --dir {self.repo} --command gipsn --reason push --check pushed:{self.repo}" + script = self.root / "skills" / "kvb-code-review" / "scripts" / "review.py" + event = json.dumps({"tool_name": "Bash", "tool_input": {"command": command}}) + return subprocess.run(["/usr/bin/python3", "-I", str(script), "hook"], input=event, env=self.env, capture_output=True, text=True, timeout=60, check=False) + + def test_a_waiver_the_operator_signed_with_the_passkey_lets_the_push_row_through(self): + state = self.signed_choice("Waive") + self.assertTrue(state["answer"].endswith("): Waive"), state) + self.assertEqual(self.waive(state, "Skills").returncode, 2) + done = self.waive(state, "Stage") + self.assertEqual(done.returncode, 0, done.stderr) + self.assertEqual(self.status(), "review: waived") + self.assertEqual(self.hook().returncode, 0) + + def test_a_signed_keep_blocked_answer_waives_nothing_and_the_push_row_stays_refused(self): + done = self.waive(self.signed_choice("Keep blocked"), "Stage") + self.assertEqual(done.returncode, 2) + self.assertIn("does not waive tree", done.stderr) + self.assertEqual(self.status(), "review: missing") + refused = self.hook() + self.assertEqual(refused.returncode, 2) + self.assertIn("no clean review for tree", refused.stderr) + + +if __name__ == "__main__": + unittest.main()