diff --git a/README.md b/README.md index 51f0ad5..9dc5dd0 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ flowchart LR code --> code_test[kvb-code-test] code --> code_tune[kvb-code-tune] code --> code_transcend[kvb-code-transcend] + code --> code_review[kvb-code-review] ci --> ci_triage[kvb-ci-triage] ci --> ci_artifacts[kvb-ci-artifacts] ci --> ci_observe[kvb-ci-observe] @@ -151,6 +152,7 @@ flowchart LR test[kvb-code-test] tune[kvb-code-tune] code_transcend[kvb-code-transcend] + code_review[kvb-code-review] end subgraph cat_ci [ci] triage[kvb-ci-triage] @@ -279,6 +281,14 @@ flowchart LR score --> break_risk score --> efficiency efficiency -. heavy commands .-> queue + git_push --> code_review + code_review --> medusa + code_review --> sceptic + code_review --> advocate + code_review --> efficiency + code_review --> score + code_review -. heavy lenses .-> queue + democracy -. push row without a clean stamp .-> code_review gate --> democracy gate --> hotfix triage --> hotfix diff --git a/docs/requirements/064-code-review.md b/docs/requirements/064-code-review.md index 432a825..d186be5 100644 --- a/docs/requirements/064-code-review.md +++ b/docs/requirements/064-code-review.md @@ -208,6 +208,9 @@ flowchart TD - [ ] The hook refuses `operator.py add ... --check pushed:` with exit 2 and the reason `no clean review for tree `; with a clean stamp it allows; other `operator.py add` rows pass untouched. +- [ ] A row whose `--command` runs `git push`, `gipsn` or `git-sign-push` + is a push row for its `--dir` whatever its check (operator + 2026-11-26: `--check manual` push rows are reviewed too). - [ ] A waiver whose signed answer `operator_message` does not match, or an unreachable hub, keeps the row refused. diff --git a/skills/kvb-code-review/SKILL.md b/skills/kvb-code-review/SKILL.md new file mode 100644 index 0000000..d986f1d --- /dev/null +++ b/skills/kvb-code-review/SKILL.md @@ -0,0 +1,82 @@ +--- +name: kvb-code-review +description: > + Review a change against every repo standard, Quality check and harness + review skill, with skeptics, memory and a push stamp. Trigger before a push. +--- + +Read-only: the review never edits, stages, commits or pushes. Its script is +`${CLAUDE_SKILL_DIR}/scripts/review.py`; every +step passes `--repo ` and, from step 2 on, `--target `. + +## Step 1: target + +Run `review.py target --repo `, then ask one `AskUserQuestion` with +the four targets, the detected one first and marked `(Recommended)`: + +1. **Staged changes** (`staged`). +2. **Pull request** (`pr `; HEAD must be its head). +3. **Branch against the default branch** (`branch `). +4. **Commit range** (`range ..`; `range ..HEAD` is what a + push sends). + +## Step 2: plan from memory + +`review.py plan --target --harness ...` with one `--harness` +per read-only review skill the harness lists (Claude Code: `code-review`, +`security-review`); a harness that lists none gets no `--harness`, and the +verdict says `harness: none`. A lens or finding whose key the memory holds +is never run or judged again: only `run` statuses and missing files go on. + +## Step 3: lenses in parallel + +Start everything of this step in one message: + +- **Scripts**: `review.py run --target --task + [--measure ""]` in the background; `--measure` only when the + change touches runnable code. Heavy lenses wait in `queue.py hold`. +- **Judging lenses** (`standards`, `legal`) with missing files: one subagent + each, its brief exactly what `review.py brief --lens ` prints, on + the model the `kvb-org-perform` skill picks; its JSON answer goes to a + scratch file and into `review.py record --lens --findings `. +- **Harness skills**: each listed one, read-only on the same target (never + `--fix` or `--comment`), its findings written as the same JSON array and + recorded with `--lens harness: --harness `. + +## Step 4: skeptics + +`review.py plan` lists every finding with the roles it still needs. In one +message: one skeptic subagent per lens for all its findings (role `lens`) +and one more per critical or high finding (role `blocker`); each gets only +the finding, its hunk and the cited section, defaults to `refuted` on a +concrete hole, and answers `[{"key", "role", "verdict": +"confirmed|refuted", "evidence"}]` for `review.py judge --verdicts `. + +## Step 5: verdict + +Show `review.py verdict --target --harness ...` verbatim: the table +`| Severity | Lens | File:line | Finding | Skeptic | Evidence |`, every +lens with its `kvb-check-*` skill and status, the standards read, skipped +and unreviewed lenses, `verdict: clean|blocked|pending`. +Clean means no confirmed critical or high finding. Below it the commit score +block of `kvb-check-score/scripts/block.py`, its break risk and confidence +judged by the `kvb-check-break-risk` and `kvb-check-confidence` methods. + +## Step 6: stamp + +When the target is everything the push sends and the tracked tree is clean, +`review.py stamp --target --harness ...` records the verdict for +`HEAD^{tree}`; `review.py status` prints it. A new tree voids it; a +signing-only rewrite keeps it. The pre-bash hook of `kvb-org-organize` +refuses every push row (`--check pushed:`, or a `--command` running +`git push`, `gipsn` or `git-sign-push` in `--dir`) while that directory +lacks a clean stamp or a waiver. + +## Step 7: waiver + +Only when the operator wants this push despite the verdict: +`review.py question` prints the question, options and recommended option +for the hub's `decision_request` (your agent name); once `decision_wait` +returns `message` and `answer`, `review.py waive --message +--answer --agent ` records it after the hub's +`operator_message` matches. Never type a waiver for the operator. diff --git a/skills/kvb-code-review/scripts/review.py b/skills/kvb-code-review/scripts/review.py new file mode 100755 index 0000000..956f146 --- /dev/null +++ b/skills/kvb-code-review/scripts/review.py @@ -0,0 +1,363 @@ +#!/usr/bin/env python3 +"""Review a change against every standard and lens, remember what was reviewed, and gate its push. + +Args: + target --repo : prints the recommended target: staged, pr , + branch , range .., or range for the operator to name. + plan --repo --target [--harness ]...: prints as JSON + what the memory holds and what still has to run: per lens its + status, the files a judging lens lacks, and every finding with the + skeptic roles it still needs. + run --repo --target [--task ] + [--measure ]: runs every script lens the memory lacks at + once, heavy ones through queue.py hold when --task names the + register task, records their findings and prints per lens its + start time and outcome as JSON. + brief --repo --target --lens : prints the brief of + a judging lens's subagent for the files the memory lacks. + record --repo --target --lens --findings + [--harness ]...: records a judging or harness lens's JSON + array of findings. + judge --repo --target --verdicts : records skeptic + verdicts, a JSON array of {key, role: lens|blocker, verdict: + confirmed|refuted, evidence}. + verdict --repo --target [--harness ]...: prints the + ranked table, the standards read, every skipped or unreviewed lens, + the harness lenses and `verdict: clean|blocked|pending`. + stamp --repo --target [--harness ]...: records that + verdict for HEAD^{tree} in kvb-review.json of the git common dir. + status --repo : prints `review: clean|blocked|waived|missing` for + HEAD^{tree}. + question --repo : prints the waiver card's question, options and + recommended option as JSON for the hub's decision_request. + waive --repo --message --answer --agent : + records the operator's signed waiver once operator_message of the + installed hub, on the port of its .env, matches it. + hook: the pre-bash handler of kvb-org-organize/scripts/hooks.py: refuses + every push row, `operator.py add ... --check pushed:` or one + whose --command runs git push, gipsn or git-sign-push in --dir, + while that directory's HEAD^{tree} has neither a clean stamp nor a + waiver the hub verifies again. + +Returns: + Exit 0 on success, a clean verdict, or a clean or waived status; 1 for a + blocked or pending verdict, or a blocked or missing status; 2 for a + usage error or a refused stamp, waiver or push row. +""" + +from __future__ import annotations + +import argparse +import json +import shlex +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) + +import review_lenses +import review_memory +import review_scope +import review_stamp + +ROLES = ("lens", "blocker") +OK = 0 +NOT_CLEAN = 1 +REFUSED = 2 + + +def file_state(lens: review_lenses.Lens, version: str, remembered: dict, files: dict[str, str], extra: str) -> dict: + keys = {path: review_memory.file_key(lens.name, version, path, blob, extra) for path, blob in files.items()} + stored = {path: remembered[key] for path, key in keys.items() if key in remembered} + found = [item for entries in stored.values() for item in entries] + return {"lens": lens, "version": version, "keys": keys, "missing": [path for path in keys if path not in stored], "findings": found, "skipped": None} + + +def diff_state(lens: review_lenses.Lens, version: str, key: str, stored: dict | None, files: dict[str, str]) -> dict: + held = stored if stored is not None else {} + missing = sorted(files) if stored is None else [] + return {"lens": lens, "version": version, "key": key, "missing": missing, "findings": held.get("findings", []), "skipped": held.get("skipped")} + + +def lens_state(lens: review_lenses.Lens, data: dict, files: dict[str, str], patch: str, context: str) -> dict: + version = review_lenses.version(lens) + extra = context if lens.standards else "" + if lens.scope == "file": + return file_state(lens, version, data["files"], files, extra) + key = review_memory.diff_key(lens.name, version, patch, extra) + return diff_state(lens, version, key, data["diffs"].get(key), files) + + +def keyed(repo: Path, files: dict[str, str], findings: list[dict]) -> list[dict]: + out = [] + for entry in findings: + blob = files.get(entry["path"], "") + flagged = review_scope.line_text(repo, blob, entry["line"]) if blob else "" + out.append({**entry, "key": review_memory.finding_key(entry, blob, flagged)}) + return out + + +def state(repo: Path, spec: str, harness: list[str]) -> dict: + """Returns: + The change's scope, files, patch id and standards, per lens what the + memory holds, every remembered finding with its key, and the + remembered skeptic verdicts. + """ + scope = review_scope.resolve(repo, spec) + files = review_scope.changed(repo, scope) + patch = review_scope.patch_id(repo, scope) + names = review_lenses.standards(repo, list(files)) + context = review_lenses.standards_digest(repo, names) + data = review_memory.sections(review_memory.read(review_scope.common_dir(repo) / review_memory.CACHE)) + lenses = [lens_state(lens, data, files, patch, context) for lens in review_lenses.every(harness)] + found = keyed(repo, files, [entry for item in lenses for entry in item["findings"]]) + return {"repo": repo, "scope": scope, "files": files, "standards": names, "lenses": lenses, "findings": found, "verdicts": data["verdicts"]} + + +def item_of(found: dict, name: str) -> dict: + matches = [item for item in found["lenses"] if item["lens"].name == name] + if not matches: + raise ValueError(f"no lens {name}; lenses: {', '.join(item['lens'].name for item in found['lenses'])}") + return matches[0] + + +def needed(entry: dict, verdicts: dict) -> list[str]: + roles = ROLES if entry["severity"] in review_lenses.BLOCKING else ROLES[:1] + return [role for role in roles if f"{entry['key']}:{role}" not in verdicts] + + +def cmd_target(args: argparse.Namespace) -> int: + print(review_scope.detect(args.repo)) + return OK + + +def cmd_plan(args: argparse.Namespace) -> int: + found = state(args.repo, args.target, args.harness) + lenses = [{ + "lens": item["lens"].name, "script": item["lens"].script, "version": item["version"], + "status": "skipped" if item["skipped"] else "run" if item["missing"] else "cached", + "missing": item["missing"], **({"reason": item["skipped"]} if item["skipped"] else {}), + } for item in found["lenses"]] + skeptics = [{**{key: entry[key] for key in ("key", "lens", "severity", "path", "line", "message")}, "roles": roles} + for entry in found["findings"] if (roles := needed(entry, found["verdicts"]))] + print(json.dumps({"target": args.target, "files": len(found["files"]), "standards": found["standards"], "lenses": lenses, "skeptics": skeptics}, indent=1)) + return OK + + +def due(item: dict, files: dict[str, str]) -> bool: + return bool(item["lens"].script and files and (item["missing"] or item["skipped"] is not None)) + + +def lens_jobs(found: dict, args: argparse.Namespace) -> tuple[list[tuple[review_lenses.Lens, list[str]]], dict[str, str]]: + """Returns: + The argv of every script lens the memory lacks or skipped before, + heavy ones held in the queue when --task names the register task, + and per lens that cannot run the reason it is skipped. + """ + measure = shlex.split(args.measure) if args.measure else [] + jobs, skipped = [], {} + for item in (entry for entry in found["lenses"] if due(entry, found["files"])): + lens = item["lens"] + argv = review_lenses.command(lens, args.repo, found["scope"], sorted(found["files"]), measure) + if isinstance(argv, str): + skipped[lens.name] = argv + continue + jobs.append((lens, review_lenses.queued(argv, args.task) if lens.heavy and args.task else argv)) + return jobs, skipped + + +def ran(name: str, result: dict) -> tuple[dict, dict]: + findings, problem = review_lenses.parsed(name, result) + if problem: + return {"skipped": f"failed: {problem}"}, {"status": "failed", "started": result["started"], "findings": 0, "reason": problem} + return {"findings": findings}, {"status": "ran", "started": result["started"], "findings": len(findings)} + + +def recorded(data: dict, found: dict, skipped: dict[str, str], results: dict[str, dict]) -> dict: + report = {} + for item in found["lenses"]: + name = item["lens"].name + if name in skipped: + data["diffs"][item["key"]], report[name] = {"skipped": skipped[name]}, {"status": "skipped", "reason": skipped[name]} + elif name in results: + data["diffs"][item["key"]], report[name] = ran(name, results[name]) + elif item["lens"].script: + report[name] = {"status": "cached"} + return report + + +def cmd_run(args: argparse.Namespace) -> int: + found = state(args.repo, args.target, []) + jobs, skipped = lens_jobs(found, args) + results = review_lenses.run_all(args.repo, jobs) + with review_memory.cache(review_scope.common_dir(args.repo)) as data: + report = recorded(review_memory.sections(data), found, skipped, results) + print(json.dumps(report, indent=1)) + return OK + + +def cmd_brief(args: argparse.Namespace) -> int: + found = state(args.repo, args.target, []) + item = item_of(found, args.lens) + if item["lens"].script: + raise ValueError(f"{args.lens} is a script lens: run it with review.py run") + print(review_lenses.brief(item["lens"], args.repo, found["scope"], item["missing"], found["standards"])) + return OK + + +def loaded(path: Path) -> list[dict]: + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, list) or not all(isinstance(entry, dict) for entry in data): + raise ValueError(f"{path} must hold a JSON array of objects") + return data + + +def cmd_record(args: argparse.Namespace) -> int: + found = state(args.repo, args.target, args.harness) + item = item_of(found, args.lens) + if item["lens"].script: + raise ValueError(f"{args.lens} is a script lens: review.py run records it") + entries = [{**review_lenses.finding(args.lens, entry, str(entry.get("severity", "")).lower(), str(entry.get("rule") or ""), str(entry.get("message") or "")), "evidence": str(entry.get("evidence") or "")} + for entry in loaded(args.findings)] + with review_memory.cache(review_scope.common_dir(args.repo)) as data: + review_memory.sections(data) + if item["lens"].scope == "file": + for path in item["missing"]: + data["files"][item["keys"][path]] = [entry for entry in entries if entry["path"] == path] + else: + data["diffs"][item["key"]] = {"findings": entries} + print(f"recorded {len(entries)} finding(s) of {args.lens}") + return OK + + +def cmd_judge(args: argparse.Namespace) -> int: + entries = loaded(args.verdicts) + for entry in entries: + if entry.get("role") not in ROLES or entry.get("verdict") not in (review_stamp.CONFIRMED, review_stamp.REFUTED) or not isinstance(entry.get("key"), str): + raise ValueError(f"a verdict needs key, role lens|blocker and verdict confirmed|refuted: {entry}") + with review_memory.cache(review_scope.common_dir(args.repo)) as data: + review_memory.sections(data) + for entry in entries: + data["verdicts"][f"{entry['key']}:{entry['role']}"] = {"verdict": entry["verdict"], "evidence": str(entry.get("evidence") or "")} + print(f"recorded {len(entries)} verdict(s)") + return OK + + +def shown(item: dict) -> str: + name = item["lens"].name + status = "skipped" if item["skipped"] else "unreviewed" if item["missing"] else "ran" + return f"{name} ({review_lenses.CHECKS[name]}) {status}" if name in review_lenses.CHECKS else f"{name} {status}" + + +def summary(found: dict, harness: list[str]) -> tuple[str, str]: + unreviewed = [item["lens"].name for item in found["lenses"] if item["missing"]] + verdict = review_stamp.decide(found["findings"], found["verdicts"], unreviewed) + lines = [ + review_stamp.table(found["findings"], found["verdicts"]), + "", + f"lenses: {', '.join(shown(item) for item in found['lenses'])}", + f"score block (step 5): {', '.join(review_lenses.SCORE_BLOCK)}", + f"standards: {', '.join(found['standards']) or 'none'}", + *(f"skipped: {item['lens'].name}: {item['skipped']}" for item in found["lenses"] if item["skipped"]), + *(f"unreviewed: {name}" for name in unreviewed), + f"harness: {', '.join(harness) or 'none'}", + f"verdict: {verdict}", + ] + return verdict, "\n".join(lines) + + +def cmd_verdict(args: argparse.Namespace) -> int: + verdict, text = summary(state(args.repo, args.target, args.harness), args.harness) + print(text) + return OK if verdict == review_stamp.CLEAN else NOT_CLEAN + + +def cmd_stamp(args: argparse.Namespace) -> int: + found = state(args.repo, args.target, args.harness) + verdict, _ = summary(found, args.harness) + tree = review_stamp.stamp(args.repo, found["scope"], verdict, {item["lens"].name: item["version"] for item in found["lenses"]}) + print(f"stamped {verdict} for tree {tree}") + return OK + + +def cmd_status(args: argparse.Namespace) -> int: + _, entry = review_stamp.entry_of(args.repo) + verdict = entry["verdict"] if entry else review_stamp.MISSING + print(f"review: {verdict}") + return OK if verdict in (review_stamp.CLEAN, review_stamp.WAIVED) else NOT_CLEAN + + +def cmd_question(args: argparse.Namespace) -> int: + options = [ + {"label": review_stamp.KEEP, "description": "The push waits for a clean review."}, + {"label": review_stamp.WAIVE, "description": "This one push goes ahead without a clean review; the hook lets its row through."}, + ] + print(json.dumps({"question": review_stamp.question(args.repo), "options": options, "recommended": review_stamp.KEEP}, indent=1)) + return OK + + +def cmd_waive(args: argparse.Namespace) -> int: + print(f"waived tree {review_stamp.waive(args.repo, args.message, args.answer, args.agent)}") + return OK + + +def cmd_hook(_args: argparse.Namespace) -> int: + try: + event = json.load(sys.stdin) + except ValueError: + return OK + tool_input = event.get("tool_input") if isinstance(event, dict) else None + command = tool_input.get("command") if isinstance(tool_input, dict) else None + for directory in review_stamp.pushed_dirs(command if isinstance(command, str) else ""): + reason = review_stamp.refusal(directory) + if reason is not None: + print(f"kvb-code-review: {reason}; review {directory} with kvb-code-review or get the operator's signed waiver first", file=sys.stderr) + return REFUSED + return OK + + +def repository(value: str) -> Path: + path = Path(value).resolve() + if not path.is_dir(): + raise argparse.ArgumentTypeError(f"{value} is no directory") + return path + + +def parser() -> argparse.ArgumentParser: + main_parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = main_parser.add_subparsers(dest="cmd", required=True) + for name, func, flags in ( + ("target", cmd_target, ()), ("plan", cmd_plan, ("target", "harness")), ("run", cmd_run, ("target", "task", "measure")), + ("brief", cmd_brief, ("target", "lens")), ("record", cmd_record, ("target", "lens", "findings", "harness")), + ("judge", cmd_judge, ("target", "verdicts")), ("verdict", cmd_verdict, ("target", "harness")), + ("stamp", cmd_stamp, ("target", "harness")), ("status", cmd_status, ()), ("question", cmd_question, ()), + ("waive", cmd_waive, ("message", "answer", "agent")), + ): + command = sub.add_parser(name) + command.add_argument("--repo", type=repository, required=True) + for flag in flags: + if flag == "harness": + command.add_argument("--harness", action="append", default=[]) + elif flag in ("task", "measure"): + command.add_argument(f"--{flag}", default="") + elif flag in ("findings", "verdicts"): + command.add_argument(f"--{flag}", type=Path, required=True) + else: + command.add_argument(f"--{flag}", required=True) + command.set_defaults(func=func) + sub.add_parser("hook").set_defaults(func=cmd_hook) + return main_parser + + +def main() -> int: + args = parser().parse_args() + try: + return args.func(args) + except (review_stamp.Refused, review_scope.ScopeError, ValueError, TypeError, OSError) as error: + print(f"review: {error}", file=sys.stderr) + return REFUSED + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/kvb-code-review/scripts/review_hook.py b/skills/kvb-code-review/scripts/review_hook.py new file mode 100755 index 0000000..097a2a4 --- /dev/null +++ b/skills/kvb-code-review/scripts/review_hook.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""Pre-bash entry of kvb-code-review for hooks.py. + +Returns: + 0 at once for every command that names no operator.py row with a push + word; otherwise review.py's hook verdict on the same event. +""" + +from __future__ import annotations + +import importlib.util +import io +import sys +from pathlib import Path + +REVIEW = Path(__file__).resolve().with_name("review.py") +ROW = "operator.py" +PUSH_WORDS = ("push", "gipsn") + + +def main() -> int: + raw = sys.stdin.read() + if ROW not in raw or not any(word in raw for word in PUSH_WORDS): + return 0 + spec = importlib.util.spec_from_file_location("kvb_review_hook_full", REVIEW) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + sys.stdin, sys.argv = io.StringIO(raw), [str(REVIEW), "hook"] + return module.main() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/kvb-code-review/scripts/review_lenses.py b/skills/kvb-code-review/scripts/review_lenses.py new file mode 100644 index 0000000..471f23b --- /dev/null +++ b/skills/kvb-code-review/scripts/review_lenses.py @@ -0,0 +1,237 @@ +from __future__ import annotations + +import concurrent.futures +import hashlib +import json +import re +import shutil +import subprocess +import sys +import time +from dataclasses import dataclass +from pathlib import Path + +import review_scope + +SKILLS = Path(__file__).resolve().parents[2] +SKILL = Path(__file__).resolve().parents[1] / "SKILL.md" +SECURITY = SKILLS / "kvb-check-security" / "scripts" / "security.py" +PRINCIPLES = SKILLS / "kvb-check-principles" / "scripts" / "principles.py" +MEASURE = SKILLS / "kvb-check-efficiency" / "scripts" / "measure.py" +QUEUE = SKILLS / "kvb-org-queue" / "scripts" / "queue.py" +LEGAL = SKILLS / "kvb-check-legal" / "checks.md" +PRINCIPLE_LIMITS = ("--ccn", "10", "--nloc", "50", "--params", "5", "--min-tokens", "50") +SEVERITIES = ("critical", "high", "medium", "low", "info") +BLOCKING = ("critical", "high") +LIMIT = 100 +LENS_SECONDS = 3600 +TAIL = 2000 +STANDARD_FILES = ("AGENTS.md", "CONTRIBUTING.md") +STANDARD_DIRS = ("docs/contributing/",) +ROLE = re.compile(r"^roles/([^/]+)/") +HEADING = re.compile(r"^#{1,6}\s+\S") +HARNESS = "harness:" +QUEUE_KIND = "test" + + +@dataclass(frozen=True) +class Lens: + """Args: + name: the lens name findings carry. + scope: "file" for a lens keyed per file, "diff" for one keyed by the + whole change's patch id. + script: whether review.py runs it as a process; else a subagent or + a harness skill judges and review.py records its answer. + heavy: whether it runs through queue.py hold when a task is given. + standards: whether its key carries the standards digest. + """ + + name: str + scope: str + script: bool + heavy: bool + standards: bool + + +LENSES = ( + Lens("quality", "diff", True, True, False), + Lens("security", "diff", True, True, False), + Lens("principles", "diff", True, False, False), + Lens("performance", "diff", True, True, False), + Lens("standards", "file", False, False, True), + Lens("legal", "file", False, False, False), +) +SOURCES = {"security": SECURITY, "principles": PRINCIPLES, "performance": MEASURE, "standards": SKILL, "legal": LEGAL} +CHECKS = {"security": "kvb-check-security", "principles": "kvb-check-principles", "performance": "kvb-check-efficiency", "legal": "kvb-check-legal"} +SCORE_BLOCK = ("kvb-check-break-risk", "kvb-check-confidence", "kvb-check-score") + + +def every(harness: list[str]) -> list[Lens]: + return [*LENSES, *(Lens(f"{HARNESS}{name}", "diff", False, False, False) for name in harness)] + + +def file_digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest()[:16] if path.is_file() else "absent" + + +def version(lens: Lens) -> str: + if lens.name == "quality": + binary = shutil.which("quality") + if binary is None: + return "absent" + done = subprocess.run([binary, "--version"], capture_output=True, text=True, check=False) + return " ".join(done.stdout.split()) or f"exit {done.returncode}" + if lens.name.startswith(HARNESS): + return file_digest(SKILL) + return file_digest(SOURCES[lens.name]) + + +def quality_command(scope: review_scope.Scope) -> list[str] | str: + binary = shutil.which("quality") + if binary is None: + return "quality is not installed; quality 003 brings it with kvb-quality-review" + return [binary, "check", *(["--staged"] if scope.head is None else ["--base", scope.base]), "--json"] + + +def principles_command(repo: Path, scope: review_scope.Scope, files: list[str]) -> list[str] | str: + chosen = ["--staged"] if scope.head is None else [item for path in files for item in ("--file", path)] + if not chosen: + return "no changed file" + return [sys.executable, "-I", str(PRINCIPLES), "--repo", str(repo), *chosen, *PRINCIPLE_LIMITS, "--json"] + + +def performance_command(scope: review_scope.Scope, measure: list[str]) -> list[str] | str: + if not measure: + return "no runnable code to measure: pass --measure for a change to runnable code" + return [sys.executable, "-I", str(MEASURE), "--base", scope.base, "--json", "--", *measure] + + +def command(lens: Lens, repo: Path, scope: review_scope.Scope, files: list[str], measure: list[str]) -> list[str] | str: + """Returns: + The argv of a script lens for this change, or the reason it cannot + run, which the review lists in place of its findings. + """ + if lens.name == "quality": + return quality_command(scope) + if lens.name == "security": + return [sys.executable, "-I", str(SECURITY), "--repo", str(repo), "--base", scope.base, "--json"] + if lens.name == "principles": + return principles_command(repo, scope, files) + return performance_command(scope, measure) + + +def queued(argv: list[str], task: str) -> list[str]: + return [sys.executable, "-I", str(QUEUE), "hold", "--kind", QUEUE_KIND, "--task", task, "--", *argv] + + +def run_one(repo: Path, item: tuple[Lens, list[str]]) -> tuple[str, dict]: + lens, argv = item + started = time.time() + try: + done = subprocess.run(argv, cwd=repo, capture_output=True, text=True, check=False, timeout=LENS_SECONDS) + except (OSError, subprocess.TimeoutExpired) as error: + return lens.name, {"started": started, "problem": str(error)} + return lens.name, {"started": started, "code": done.returncode, "stdout": done.stdout, "stderr": done.stderr[-TAIL:]} + + +def run_all(repo: Path, jobs: list[tuple[Lens, list[str]]]) -> dict[str, dict]: + """Returns: + Per lens name its start time and exit code, stdout and stderr tail, + or the problem that kept it from running; every job starts at once. + """ + if not jobs: + return {} + with concurrent.futures.ThreadPoolExecutor(max_workers=len(jobs)) as pool: + return dict(pool.map(lambda job: run_one(repo, job), jobs)) + + +def finding(lens: str, entry: dict, severity: str, rule: str, message: str) -> dict: + line = entry.get("line") + return { + "lens": lens, "rule": rule, "severity": severity if severity in SEVERITIES else "medium", + "path": str(entry.get("path") or entry.get("file") or "-"), "line": line if isinstance(line, int) else None, + "message": message, "evidence": "", + } + + +def security_findings(data: object) -> tuple[list[dict], str | None]: + if not isinstance(data, dict): + return [], "unreadable report" + if data.get("security") is None: + return [], str(data.get("problem")) + return [finding("security", entry, entry["severity"], entry.get("rule") or "", f"MEDUSA {entry.get('rule') or 'finding'}") for entry in data.get("findings", [])], None + + +def principle_findings(data: list[dict]) -> tuple[list[dict], str | None]: + return [finding("principles", entry, "medium", f"{entry['tool']}:{entry['lens']}", entry["message"]) for entry in data], None + + +def performance_findings(data: dict) -> tuple[list[dict], str | None]: + return [finding("performance", {}, "medium", key, f"{key} {data[key]} % of the base") for key in ("efficiency", "speed") if data.get(key, 0) > LIMIT], None + + +def quality_findings(data: object) -> tuple[list[dict], str | None]: + entries = data.get("findings", []) if isinstance(data, dict) else data if isinstance(data, list) else [] + return [finding("quality", entry, str(entry.get("severity", "")).lower(), str(entry.get("rule") or entry.get("rule_id") or ""), str(entry.get("message") or "")) for entry in entries if isinstance(entry, dict)], None + + +PARSERS = {"quality": quality_findings, "security": security_findings, "principles": principle_findings, "performance": performance_findings} + + +def parsed(lens: str, result: dict) -> tuple[list[dict], str | None]: + """Returns: + The findings a script lens printed, or the problem that makes its + output unusable. + """ + if "problem" in result: + return [], result["problem"] + try: + data = json.loads(result["stdout"]) + except ValueError: + return [], f"exit {result['code']} without JSON: {result['stderr'].strip()[-300:]}" + return PARSERS[lens](data) + + +def standards(repo: Path, paths: list[str]) -> list[str]: + tracked = set(review_scope.git(repo, "ls-files", "-z").split("\0")) + picked = {name for name in tracked if name in STANDARD_FILES or name.startswith(STANDARD_DIRS)} + roles = {match.group(1) for path in paths if (match := ROLE.match(path))} + picked |= {f"roles/{role}/AGENTS.md" for role in roles} & tracked + return sorted(picked) + + +def standards_digest(repo: Path, names: list[str]) -> str: + return hashlib.sha256("\0".join(f"{name}\0{file_digest(repo / name)}" for name in names).encode()).hexdigest() + + +def index(root: Path, names: list[str]) -> str: + rows = [] + for name in names: + path = root / name + if path.is_file(): + rows += [f"{name}:{number} {text.strip()}" for number, text in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1) if HEADING.match(text)] + return "\n".join(rows) + + +def brief(lens: Lens, repo: Path, scope: review_scope.Scope, paths: list[str], names: list[str]) -> str: + """Args: + paths: the files this subagent reviews, the ones the memory lacks. + names: the standards files of the change. + + Returns: + The subagent's brief: only the hunks of its files and the index of + the sections it may cite, never a whole standards document. + """ + sections = index(LEGAL.parent, [LEGAL.name]) if lens.name == "legal" else index(repo, names) + source = f"{LEGAL}" if lens.name == "legal" else str(repo) + return "\n".join([ + "task-class: judgement", + f"Lens {lens.name} of kvb-code-review on {scope.spec}; read-only: never edit, stage, commit or push.", + f"Files: {', '.join(paths) or 'none'}", + f"Sections you may cite (read only those a hunk touches, by file:line under {source}):", + sections or "none", + "Hunks:", + review_scope.hunks(repo, scope, paths) or "none", + ('Answer one JSON array and nothing else: per finding {"rule": "", "severity": "critical|high|medium|low", ' + '"path": "", "line": , "message": "", "evidence": ""}; [] 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()