feat(kvb-code-review): review every push and refuse unreviewed push rows
Requirement 064. New skill kvb-code-review: review.py target, plan, run,
brief, record, judge, verdict, stamp, status, question, waive and hook.
It reviews a change against the repository's standards and lenses
(MEDUSA, principles, efficiency, legal, quality), remembers reviewed
blobs and stamps a clean verdict for HEAD^{tree} in kvb-review.json.
The pre-bash hook of hooks.py refuses every push row (--check pushed:
or a --command running git push, gipsn or git-sign-push, also nested
in sh -c) while the tree has neither a clean stamp nor an operator
waiver that operator_message of the installed hub verifies. The hub
port comes only from the hub's .env, never from argv or the stamp.
kvb-git-push gains the review step.
🎯 Fix: 92 %
💥 Break: 3 %
💸 Tokens: 113 %
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 79
🚦 Gate: ⚠️ tokens 113 % > 100: operator approved the commit
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
db3dee02cd
commit
0f8cb32198
15 files changed
+1924
-6
No files matched your search
@@ -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 <root>` and, from step 2 on, `--target <spec>`.
|
||||
|
||||
## Step 1: target
|
||||
|
||||
Run `review.py target --repo <root>`, then ask one `AskUserQuestion` with
|
||||
the four targets, the detected one first and marked `(Recommended)`:
|
||||
|
||||
1. **Staged changes** (`staged`).
|
||||
2. **Pull request** (`pr <n>`; HEAD must be its head).
|
||||
3. **Branch against the default branch** (`branch <main|master>`).
|
||||
4. **Commit range** (`range <a>..<b>`; `range <upstream>..HEAD` is what a
|
||||
push sends).
|
||||
|
||||
## Step 2: plan from memory
|
||||
|
||||
`review.py plan --target <spec> --harness <name> ...` 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 <spec> --task <register task>
|
||||
[--measure "<command>"]` 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 <name>` prints, on
|
||||
the model the `kvb-org-perform` skill picks; its JSON answer goes to a
|
||||
scratch file and into `review.py record --lens <name> --findings <file>`.
|
||||
- **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:<name> --harness <name>`.
|
||||
|
||||
## 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 <file>`.
|
||||
|
||||
## Step 5: verdict
|
||||
|
||||
Show `review.py verdict --target <spec> --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 <spec> --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:<dir>`, 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 <message>
|
||||
--answer <answer> --agent <name>` records it after the hub's
|
||||
`operator_message` matches. Never type a waiver for the operator.
|
||||
Executable
+363
@@ -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 <root>: prints the recommended target: staged, pr <n>,
|
||||
branch <default>, range <a>..<b>, or range for the operator to name.
|
||||
plan --repo <root> --target <spec> [--harness <name>]...: 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 <root> --target <spec> [--task <register task>]
|
||||
[--measure <command>]: 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 <root> --target <spec> --lens <name>: prints the brief of
|
||||
a judging lens's subagent for the files the memory lacks.
|
||||
record --repo <root> --target <spec> --lens <name> --findings <file>
|
||||
[--harness <name>]...: records a judging or harness lens's JSON
|
||||
array of findings.
|
||||
judge --repo <root> --target <spec> --verdicts <file>: records skeptic
|
||||
verdicts, a JSON array of {key, role: lens|blocker, verdict:
|
||||
confirmed|refuted, evidence}.
|
||||
verdict --repo <root> --target <spec> [--harness <name>]...: prints the
|
||||
ranked table, the standards read, every skipped or unreviewed lens,
|
||||
the harness lenses and `verdict: clean|blocked|pending`.
|
||||
stamp --repo <root> --target <spec> [--harness <name>]...: records that
|
||||
verdict for HEAD^{tree} in kvb-review.json of the git common dir.
|
||||
status --repo <root>: prints `review: clean|blocked|waived|missing` for
|
||||
HEAD^{tree}.
|
||||
question --repo <root>: prints the waiver card's question, options and
|
||||
recommended option as JSON for the hub's decision_request.
|
||||
waive --repo <root> --message <id> --answer <text> --agent <name>:
|
||||
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:<dir>` 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())
|
||||
+33
@@ -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())
|
||||
@@ -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 <command> 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": "<file:line of the cited rule>", "severity": "critical|high|medium|low", '
|
||||
'"path": "<file>", "line": <number>, "message": "<one line>", "evidence": "<quote or command>"}; [] when nothing holds.'),
|
||||
])
|
||||
@@ -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
|
||||
@@ -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 <n>`
|
||||
for an open pull request of the branch, else `branch <default>`
|
||||
with commits ahead of the default branch, else `range <upstream>..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 <n>, branch <name> or range <a>..<b>, 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()
|
||||
@@ -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 '<upstream>'}..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:<dir>`, 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
|
||||
@@ -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 <root>` 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.
|
||||
|
||||
@@ -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"),
|
||||
|
||||
Reference in new issue
Block a user