diff --git a/.github/fork-pr-queue.json b/.github/fork-pr-queue.json index b6c06c9f87d12..2f90c5879bfa6 100644 --- a/.github/fork-pr-queue.json +++ b/.github/fork-pr-queue.json @@ -32,6 +32,7 @@ ".github/fork-fleet.json", ".github/fork-owned-paths.txt", ".github/fork-pr-queue.json", + ".github/fork-review-kit.json", ".github/fork-removed-workflows.txt", ".github/fork-secret-sweep-gone-tips.txt", ".github/fork-tests-upstream.json", diff --git a/.github/fork-review-kit.json b/.github/fork-review-kit.json new file mode 100644 index 0000000000000..7940ddef1c336 --- /dev/null +++ b/.github/fork-review-kit.json @@ -0,0 +1,4 @@ +{ + "version": 1, + "queue_config": ".github/fork-pr-queue.json" +} diff --git a/fork-ci/RELEASE-NOTES.md b/fork-ci/RELEASE-NOTES.md index d4dfa92fcc1f1..1cfa9a5482f6d 100644 --- a/fork-ci/RELEASE-NOTES.md +++ b/fork-ci/RELEASE-NOTES.md @@ -13,6 +13,13 @@ nothing. ## After ci/v14 +### pr-queue: what counts as a `state:` line is gate code (#797) + +`review_judge.has_state_line` holds the rule for a lens report's `state:` line (an answer after the colon, outside code +blocks and quotes). The gate still parses `state_line` without enforcing it, so nothing a caller sees changes. The +review kit (fork-kit/review) now imports this rule and the gate's `head_check.changed_paths` instead of its own +copies, so run the kit from a checkout at the release the gate pins (kit README, "Which fork version"). + ### pr-queue and head-check: every rule hit gives its lenses (#82) With a `review` block in `enforce`, the required lenses are now the lenses of every rule a changed path counted for, diff --git a/fork-ci/actions/pr-queue/review_judge.py b/fork-ci/actions/pr-queue/review_judge.py index 3c4bdbfa0da27..27846c55c69a7 100644 --- a/fork-ci/actions/pr-queue/review_judge.py +++ b/fork-ci/actions/pr-queue/review_judge.py @@ -34,6 +34,10 @@ until a person's override for the head, newer than every lens comment, lets it through (it alone is enough: it also waives the approach lens). Owner decision: issue #100. Pure as judge is: the lens comments come in (lens.Review.lens_scan), the verdict goes out. + +has_state_line says what counts as a report's `state:` line (the answer to the state question). The `state_line` +setting is parsed but not enforced yet; the review kit (fork-kit/review, `check`) imports this rule, so the gate and +the kit read one rule when the gate starts enforcing it. """ import html import re @@ -367,6 +371,15 @@ def read_findings(body): return [found[i] for i in sorted(found)], seen >= set(BLOCKING) +STATE_RE = re.compile(r'state\s*:\s*\S', re.I) + + +def has_state_line(body): + """A `state:` line with an answer (anything but blanks after the colon), outside fenced and indented code blocks and + quotes, read as a lens header is (folded, markdown and list markers stripped: `**State:** ok`, `- state: ok`).""" + return any(STATE_RE.match(lens.norm_line(fold(raw))) for raw in lens.plain_lines(body)) + + def findings(body): """[(kind, line)] of the report's blocker and major findings (read_findings).""" return read_findings(body)[0] diff --git a/fork-ci/actions/pr-queue/review_judge.test.py b/fork-ci/actions/pr-queue/review_judge.test.py index 7d11ebb684096..f3590095f0e3f 100644 --- a/fork-ci/actions/pr-queue/review_judge.test.py +++ b/fork-ci/actions/pr-queue/review_judge.test.py @@ -191,6 +191,19 @@ def group(name): return [v for v in FINDINGS if v['group'] == name] +class StateLine(unittest.TestCase): + """has_state_line: what counts as a report's `state:` line (the review kit imports it; the gate parses + `state_line` but does not enforce it yet).""" + + def test_an_answered_state_line_outside_code_and_quotes(self): + for body, said in (('state: a second run does nothing', True), ('**State:** fine', True), + ('- state: fine', True), ('STATE : fine', True), ('state:', False), ('state: ', False), + ('the state is fine', False), ('```\nstate: fine\n```', False), ('> state: fine', False), + (' state: fine', False)): + with self.subTest(body=body): + self.assertIs(rj.has_state_line(f'lens: code\n{body}\nblocker: none\n'), said) + + class Findings(unittest.TestCase): def test_every_shared_findings_vector(self): for v in FINDINGS: diff --git a/fork-kit/review/COMMENTS.md b/fork-kit/review/COMMENTS.md index 4b48bb2ea443d..00730c761e1fb 100644 --- a/fork-kit/review/COMMENTS.md +++ b/fork-kit/review/COMMENTS.md @@ -34,8 +34,9 @@ minor: ; - **Verdict line (optional):** `verdict: safe to merge` or `verdict: not safe to merge`. A `verdict:` line, or the first line under the header, that says NOT SAFE is a blocker whatever the labels say. - **State line:** `state:` and the lens's answer to the state question ("What happens when this runs again, stops - half-way, or meets existing, old or empty state?"). The gate parses the config's `state_line` setting but does not - enforce it yet; the kit's `check` does, and so does every lens prompt the kit writes. + half-way, or meets existing, old or empty state?"). What counts as one is the gate's rule + (`review_judge.has_state_line`); the gate parses the config's `state_line` setting but does not enforce it yet; the + kit's `check` does, and so does every lens prompt the kit writes. - **Round markers:** a re-read after a fix may add `r2`, `r3` to the lens name (`lens: data-1 r2`). The gate counts rounds from the different changes lenses read and from these markers, whichever is higher; the marker is not part of the lens's name (`data-1 r2` is lens `data-1`). @@ -48,19 +49,19 @@ minor: ; Each example says, on the line before it, what the gate reads, as words: -| Words | Meaning | -| --------------------- | ----------------------------------------------------------------------------------------------- | -| `lens ` | a lens header naming this lens (`lens_key`: lowercased, a trailing round marker dropped) | -| `round ` | the header carries round marker `r` | -| `read` | the header names a full sha: this is a read of that head | -| `short sha`, `no sha` | the header's sha is short or missing: no read | -| `clean` | a findings section with no blocker and no major | -| `blocker`, `major` | an open blocker or major: the gate holds the head until a new read on a fixed head, or a person | -| `no findings section` | no blocker and major labels: with `findings` on, the gate does not take the read | -| `state`, `no state` | a `state:` line with an answer, or none | -| `reads nothing` | looks like a lens report but is not one valid read: the gate counts it as a blocking problem | -| `not a lens` | not a lens report at all (a plain comment, or one that opts out with `not a lens:`): ignored | -| `override` | an override comment for that sha (counts only from the configured author association) | +| Words | Meaning | +| --------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `lens ` | a lens header naming this lens (`lens_key`: lowercased, a trailing round marker dropped) | +| `round ` | the header carries round marker `r` | +| `read` | the header names a full sha: this is a read of that head | +| `short sha`, `no sha` | the header's sha is short or missing: no read | +| `clean` | a findings section with no blocker and no major | +| `blocker`, `major` | an open blocker or major: the gate holds the head until a new read on a fixed head, or a person | +| `no findings section` | no blocker and major labels: with `findings` on, the gate does not take the read | +| `state`, `no state` | a `state:` line with an answer, or none | +| `reads nothing` | looks like a lens report but is not one valid read: the gate counts it as a blocking problem | +| `not a lens` | not a lens report at all (a plain comment, or one that opts out with `not a lens:`): ignored | +| `override` | an override comment for that sha (counts only from the configured author association, never edited and not hidden) | ## Good reports diff --git a/fork-kit/review/README.md b/fork-kit/review/README.md index c322bb0031135..d7717af6784cd 100644 --- a/fork-kit/review/README.md +++ b/fork-kit/review/README.md @@ -17,8 +17,15 @@ checkout of the fork. The kit holds no project facts: which paths are critical and which lenses they need are the project's `review` block (read by the gate), and who runs a lens is the project's kit settings. The kit imports the gate's own parser -(`config.py`, `lens.py`, `review_judge.py`), so it cannot read a comment or a path differently from the gate; it needs -the fork's `fork-ci/` folder beside it. +(`config.py`, `lens.py`, `review_judge.py`, `head_check.py`), so it cannot read a comment or a path differently from +the gate; it needs the fork's `fork-ci/` folder beside it. + +## Which fork version + +The kit imports the gate's code from the fork checkout it runs in, not from the release the project's gate pins. A +newer checkout can read comments, paths or the config differently from the pinned gate (a new rule, a new config +key). So run the kit from a checkout at the pinned release: `git -C checkout ` (the gate's pin is in the project's workflow, gate README "Use it"), and move it when the pin moves. Tests (no network, no host changes): diff --git a/fork-kit/review/REVIEW.md b/fork-kit/review/REVIEW.md index cfe59792f97ee..b295b6a7743c3 100644 --- a/fork-kit/review/REVIEW.md +++ b/fork-kit/review/REVIEW.md @@ -20,7 +20,8 @@ then only reports what it would ask for. Start from the gate's - `min_lenses`: at least 2 for critical, 1 for normal, 0 for light. - `rounds`: the gate's own cap. Keep `max` at or above the kit's `lens_rounds` (the plan warns otherwise). - `findings: true`: the gate holds a head while a lens's newest read has an open blocker or major. -- `state_line: true`: the gate parses it but does not enforce it yet; the kit's `check` does. +- `state_line: true`: the gate parses it but does not enforce it yet; the kit's `check` does, with the gate's own + rule for what counts as a `state:` line (`review_judge.has_state_line`). Also set the queue config's `lens_format_doc` (a text the gate only quotes in its comments) to where agents read the format: the kit's [COMMENTS.md](COMMENTS.md) at the fork tag the project pins, or the project's adapter skill @@ -28,7 +29,8 @@ if it links there. Check it: `python3 -I fork-kit/review/lib/review_kit.py plan --root . --changes ` with a `git diff --name-status -z -M` output, or `--base origin/main` on a branch. A config the gate refuses gives a plain -message and exit 2. +message and exit 2. Run the kit from a fork checkout at the release the project's gate pins (README.md, "Which fork +version"). ## 2. Lens prompt files @@ -65,7 +67,16 @@ Optional: `.github/review-kit.json`. No file means the defaults. Every key is op | `state_question` | _What happens when this runs again, stops half-way, or meets existing, old or empty state?_ | [review-kit.example.json](review-kit.example.json) shows one. An empty file, an unknown key or a wrong value is -refused with a plain message naming every problem, so a typo never turns into a silent default. +refused with a plain message naming every problem, so a typo never turns into a silent default. A project that keeps +the file under another name (the fork: `.github/fork-review-kit.json`, beside its `.github/fork-pr-queue.json`) gives +it with `--settings ` to every `plan` and `check`. + +**This file or T3's review rules setting:** T3 has a per-machine setting for the same runners (`server.reviewRules` +and `projectOverride.reviewRules`, docs/fork/README.md). Nothing in T3 reads it yet, so today this file decides. Once +T3 starts lenses itself, each decides what it starts: T3's setting the lenses T3 starts on that machine (the +machine's half: which provider and model it has), this file every lens an agent starts by hand from the skill and +what `plan` prints. Keep the two the same; the gate does not read either, so a difference changes cost and recall, +never what passes. ## 5. Enforce diff --git a/fork-kit/review/SKILL.md b/fork-kit/review/SKILL.md index b51925f6006a5..26db256416057 100644 --- a/fork-kit/review/SKILL.md +++ b/fork-kit/review/SKILL.md @@ -38,6 +38,9 @@ critical). A project with **no CI** (no queue config) has no gate: every change python3 -I fork-kit/review/lib/review_kit.py plan --root --base origin/main ``` +Run the kit from a fork checkout at the release the project's gate pins (README.md, "Which fork version"). A project +whose kit settings are not at `.github/review-kit.json` adds `--settings ` to every `plan` and `check`. + The plan judges the change with the gate's own rules and prints the tier, the lenses (each with its prompt file and its runner), why, the state question, the round limit and the minors rule. Do what it says; never pick fewer lenses by hand. Unsure, or a path the rules do not cover: take the heavier tier. Two independent reads miss different bugs; @@ -86,7 +89,8 @@ Each step is done by another agent than the author. past `rounds.max` it fails the head (in `enforce`; `shadow` only reports both). - **Which head passes:** the gate passes a head only when every lens's newest read names that head, or an override comment newer than a lens's read covers it (` : `, - COMMENTS.md; it counts only from the account with the queue config's `override.author_association`). So after a + COMMENTS.md; it counts only from the configured author association, the queue config's + `override.author_association`, and only while it is never edited and not hidden). So after a fix the lenses of the last round still name the old head, and the fix head passes only when every lens reads it again (a new round) or the orchestrator posts the override for it (no new round). - **Nit-only fix:** a fix diff that touches only tests, docs, comments, message text or names (judged by the diff, @@ -103,8 +107,11 @@ Each step is done by another agent than the author. author is in the review block's `override_authors` (empty by default). An orchestrator's override never replaces the approach lens. - A note between rounds that is no lens report starts with `not a lens:` (COMMENTS.md). - - **No round past the limit.** A pull request still stuck (a blocker or major left) gets one audit by the - `audit_runner` ("good enough to merge, or what next"), posted as a `not a lens:` comment; then a person decides. + - **No round past the limit.** A fix after the last lens round (`lens_rounds` used up) that is not nit-only, for + example a minor of the last round fixed in code with `minors: same-round`, gets no new lens round: the + orchestrator checks that fix diff itself and posts the override for the fix head. A blocker or major left over + counts as stuck. A pull request still stuck gets one audit by the `audit_runner` ("good enough to merge, or what + next"), posted as a `not a lens:` comment; then a person decides. 8. **Minors** (`minors`, default `issue`): minors and anything left when the pull request stops go into **one** follow-up issue, with the project's labels, linked on the pull request. With `same-round`, minors are fixed in the round that found them and any left at the last round are listed in the pull request description with a reason diff --git a/fork-kit/review/eval/README.md b/fork-kit/review/eval/README.md index e4c313f3a329a..f908cd855acd9 100644 --- a/fork-kit/review/eval/README.md +++ b/fork-kit/review/eval/README.md @@ -54,7 +54,9 @@ is a small sample, and 1-2 bugs between settings is noise, but three results sha mechanism. 5. **Scores:** `review_eval.py cost` reads tokens, $ (from `prices`, $ per million tokens; check the current price list) and active minutes (gaps over `idle_gap_seconds` dropped) from the transcripts that `transcripts` globs - find, matching each to its run by the `RUN-ID:` first line of the session's first message. `review_eval.py + find, matching each to its run by the `RUN-ID:` first line of the session's first message. A run started as a + sub-agent has its transcript under `/subagents/` (the example config globs those too), and the + sub-agents a run starts itself (`/subagents/*.jsonl`) count toward that run. `review_eval.py analyze` gives per config the blocker and major recall (mean and worst run), recall of all findings, false positives, $ and minutes, the union of every pair of configs, and which known bugs each config missed. 6. **Rule:** use the cheapest setting whose worst-case blocker and major recall equals the best setting's. Check it diff --git a/fork-kit/review/eval/eval.example.json b/fork-kit/review/eval/eval.example.json index 43f629a3a5beb..f642064dea645 100644 --- a/fork-kit/review/eval/eval.example.json +++ b/fork-kit/review/eval/eval.example.json @@ -4,7 +4,7 @@ "repo": "../model-eval/repo.git", "truth": "truth.json", "briefs": "briefs", - "transcripts": ["~/.claude/projects/*/*.jsonl"], + "transcripts": ["~/.claude/projects/*/*.jsonl", "~/.claude/projects/*/*/subagents/*.jsonl"], "prices": { "claude-opus-5-5": { "input": 4, diff --git a/fork-kit/review/lib/review_eval.py b/fork-kit/review/lib/review_eval.py index 7e91a58f06bee..c3297e1aa793c 100644 --- a/fork-kit/review/lib/review_eval.py +++ b/fork-kit/review/lib/review_eval.py @@ -313,7 +313,12 @@ def cost(c, out): for f in sorted(glob.glob(pattern)): m = RUN_RE.match(_first_user_text(f).lstrip()) # the run's own session starts with its RUN-ID line if m and m.group(1) in runs: - files.setdefault(m.group(1), []).append(f) + # ... and the sub-agents it started are its cost too: Claude Code keeps them beside the session file, + # in /subagents/*.jsonl. Each file once, however many patterns find it. + subs = os.path.join(glob.escape(f[:-len('.jsonl')]), 'subagents', '*.jsonl') + for g in [f, *(sorted(glob.glob(subs)) if f.endswith('.jsonl') else [])]: + if g not in files.setdefault(m.group(1), []): + files[m.group(1)].append(g) result = {} for rid, fs in sorted(files.items()): usage, times, model = {}, [], None @@ -368,6 +373,36 @@ def mean(xs): return round(statistics.mean(xs), 3) if xs else None +def _list_of(v, ok): + """Left out (or null), or a list whose every item is ok.""" + return v is None or (isinstance(v, list) and all(ok(x) for x in v)) + + +def scores_of(path, name): + """The `reviews` object of a judge's scores.json, each entry checked against the shape judge_prompt.txt asks for: + `found` a list of truth ids, `findings` a list of objects whose `verdict` is text. Problem naming what is wrong + (never a traceback): a hand-edited or half-written file is judged again, not read halfway.""" + s = load_json(path, f'the scores of case {name}') + bad = None + if not isinstance(s, dict) or not isinstance(s.get('reviews'), dict): + bad = 'it is not an object with a "reviews" object' + else: + for review, r in sorted(s['reviews'].items()): + if not isinstance(r, dict): + bad = f'{review} is not an object' + elif not _list_of(r.get('found'), lambda x: isinstance(x, str)): + bad = f'{review}: "found" is not a list of truth ids' + elif not _list_of(r.get('findings'), lambda f: isinstance(f, dict) + and isinstance(f.get('verdict', ''), (str, type(None)))): + bad = f'{review}: "findings" is not a list of objects with a text "verdict"' + if bad: + break + if bad: + raise Problem(f'case {name}: {path} is not in the shape judge_prompt.txt asks for ({bad}): judge the case ' + f'again') + return s['reviews'] + + def analyze(c, cases, out): runmap_ = {r['id']: r for r in read_runs(c)} jpath = gt(c, 'judgemap.json') @@ -380,12 +415,12 @@ def analyze(c, cases, out): if name not in cases or not os.path.exists(p): skipped.append(name) continue - s = load_json(p, f'the scores of case {name}') + reviews = scores_of(p, name) t = ids(cases, name) bm, every = set(t['blocker_major']), set(itertools.chain(*t.values())) judged.append(name) for review, rid in sorted(jm[name].items()): - r = (s.get('reviews') or {}).get(review) + r = reviews.get(review) if not isinstance(r, dict) or rid not in runmap_: raise Problem(f'case {name}: scores.json has no entry for {review} (or the run map lost {rid}): judge ' f'the case again') diff --git a/fork-kit/review/lib/review_kit.py b/fork-kit/review/lib/review_kit.py index 8b5fd6f9ecb30..734e18940996d 100644 --- a/fork-kit/review/lib/review_kit.py +++ b/fork-kit/review/lib/review_kit.py @@ -1,11 +1,13 @@ """The review kit's helpers (../README.md): `plan` says which lenses a change needs and how to run them, `check` says how the gate reads one lens comment, and `doc` checks that every example in COMMENTS.md reads as it says. -Every rule about paths, lens comments, findings and rounds is the gate's own code (fork-ci/actions/pr-queue: config.py, -lens.py, review_config.py, review_judge.py), imported, never copied: the kit cannot read a comment another way than the -gate does. The kit adds only what the gate does not judge: the project's kit settings (who runs a lens, how many lens -rounds, what happens to minors, the state question) and the `state:` line check (the gate parses `state_line` but does -not enforce it yet). +Every rule about paths, lens comments, findings, rounds and the `state:` line is the gate's own code +(fork-ci/actions/pr-queue: config.py, lens.py, review_config.py, review_judge.py; fork-ci/actions/head-check: +head_check.changed_paths), imported, never copied: the kit cannot read a comment or a change another way than the gate +does. It imports that code from the fork checkout it runs in, so run the kit at the release the project's gate pins +(README.md). The kit adds only what the gate does not judge: the project's kit settings (who runs a lens, how many lens +rounds, what happens to minors, the state question) and requiring the `state:` line in `check` (the gate parses +`state_line` but does not enforce it yet; what counts as one is review_judge.has_state_line). python3 -I fork-kit/review/lib/review_kit.py plan [--root DIR] [--settings FILE] (--base REF | --changes FILE|-) python3 -I fork-kit/review/lib/review_kit.py check [--root DIR] [--settings FILE] [--head SHA] FILE|- @@ -25,7 +27,9 @@ KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GATE = os.path.join(os.path.dirname(os.path.dirname(KIT)), 'fork-ci', 'actions', 'pr-queue') sys.path.insert(0, GATE) +sys.path.insert(0, os.path.join(os.path.dirname(GATE), 'head-check')) import config as gate_config # noqa: E402 +import head_check # noqa: E402 import lens # noqa: E402 import review_judge # noqa: E402 @@ -47,7 +51,6 @@ 'same-round': 'minors are fixed in the same round; any left at the last round go into the pull request ' 'description with a reason each'} FALLBACK_LENS = 'review' -STATE_RE = re.compile(r'state\s*:\s*\S', re.I) class Problem(Exception): @@ -127,21 +130,25 @@ def load_settings(root, path=None): return s, None +def commit_of(root, ref): + """The full sha of the commit `ref` names in the repository at `root`; Problem when it names none.""" + r = subprocess.run(['git', '-C', root, 'rev-parse', '--verify', '--quiet', '--end-of-options', f'{ref}^{{commit}}'], + capture_output=True) + sha = r.stdout.decode('ascii', 'replace').strip() + if r.returncode != 0 or not head_check.SHA.fullmatch(sha): + raise Problem(f'{ref} is not a commit in {root}') + return sha + + def load_queue_config(root, settings, base=None): - """(gate Config or None, note). The config is read from `base` with git when given (as the gate reads it, from the - base tip), else from the file. No file, or no `review` block (a config from before the review rules): None, and the - note says how the plan judges. Problem for an empty or invalid config: the gate would refuse it too.""" + """(gate Config or None, note). The config is read from the commit `base` (a full sha) with git when given (as the + gate reads it, from the base tip, as bytes: one that is not UTF-8 is refused as the gate refuses it), else from the + file. No file, or no `review` block (a config from before the review rules): None, and the note says how the plan + judges. Problem for an empty or invalid config: the gate would refuse it too.""" rel = settings['queue_config'] if base: r = subprocess.run(['git', '-C', root, 'show', f'{base}:{rel}'], capture_output=True) - if r.returncode != 0: - exists = subprocess.run(['git', '-C', root, 'rev-parse', '--verify', '--quiet', f'{base}^{{commit}}'], - capture_output=True).returncode == 0 - if not exists: - raise Problem(f'{base} is not a commit in {root}') - text = None - else: - text = r.stdout.decode('utf-8', 'replace') + text = r.stdout if r.returncode == 0 else None else: text = read_text(os.path.join(root, rel), 'the queue config') where = f'{rel} at {base}' if base else rel @@ -160,23 +167,31 @@ def load_queue_config(root, settings, base=None): return cfg, None +def git_dir(root): + r = subprocess.run(['git', '-C', root, 'rev-parse', '--absolute-git-dir'], capture_output=True) + if r.returncode != 0: + raise Problem(f'{root} is not in a git repository: {r.stderr.decode("utf-8", "replace").strip()}') + return os.fsdecode(r.stdout.rstrip(b'\n')) + + def changes_from(root, base=None, changes=None): - """[(status, paths)] as the gate reads them: `git diff --name-status -z -M ...HEAD`, or a file of that output.""" + """[(status, paths)] as the gate reads them: with `base` (a full sha), the gate's own head_check.changed_paths from + `base` to HEAD (every merge base, git's safe flags and no global config: never fewer paths than the gate sees), else + a file of `git diff --name-status -z -M` output.""" if base: - r = subprocess.run(['git', '-C', root, 'diff', '--name-status', '-z', '-M', f'{base}...HEAD'], - capture_output=True) - if r.returncode != 0: - raise Problem(f'git diff {base}...HEAD failed: {r.stderr.decode("utf-8", "replace").strip()}') - text = r.stdout.decode('utf-8', 'surrogateescape') - else: - try: - if changes == '-': - text = sys.stdin.buffer.read().decode('utf-8', 'surrogateescape') - else: - with open(changes, 'rb') as f: - text = f.read().decode('utf-8', 'surrogateescape') - except OSError as e: - raise Problem(f'the changes file {changes} cannot be read: {e.strerror}') from None + head = commit_of(root, 'HEAD') + found, why = head_check.changed_paths(head_check.Checkout(git_dir(root), bare=(base, head)), base, head) + if found is None: + raise Problem(why) + return found + try: + if changes == '-': + text = sys.stdin.buffer.read().decode('utf-8', 'surrogateescape') + else: + with open(changes, 'rb') as f: + text = f.read().decode('utf-8', 'surrogateescape') + except OSError as e: + raise Problem(f'the changes file {changes} cannot be read: {e.strerror}') from None try: return review_judge.parse_name_status(text) except review_judge.JudgeError as e: @@ -238,10 +253,8 @@ def plan(root, settings, cfg, note, changes): # --- one comment, as the gate reads it --------------------------------------------------------------------------- -def has_state_line(body): - """A `state:` line with an answer, outside code blocks and quotes (the kit's check; the gate parses `state_line` - but does not enforce it yet).""" - return any(STATE_RE.match(lens.norm_line(review_judge.fold(raw))) for raw in lens.plain_lines(body)) +# What counts as a `state:` line is the gate's rule; the kit's `check` requires one (the gate does not enforce it yet). +has_state_line = review_judge.has_state_line def reader(override_prefix): @@ -380,7 +393,8 @@ def main(argv, out=sys.stdout): raise Problem('plan needs exactly one of --base REF or --changes FILE (git diff --name-status -z -M output)') root = opts.get('--root', '.') settings, note = load_settings(root, opts.get('--settings')) - cfg, cfg_note = load_queue_config(root, settings, opts.get('--base')) + base = commit_of(root, opts['--base']) if '--base' in opts else None + cfg, cfg_note = load_queue_config(root, settings, base) if cmd == 'check': if not rest: raise Problem('check needs the comment: a file, or - for stdin') @@ -395,7 +409,7 @@ def main(argv, out=sys.stdout): code, text = check(body, cfg.override_prefix if cfg else '\0', opts.get('--head')) print(text, file=out) return code - changes = changes_from(root, opts.get('--base'), opts.get('--changes')) + changes = changes_from(root, base, opts.get('--changes')) for line in plan(root, settings, cfg, '; '.join(x for x in (note, cfg_note) if x), changes): print(line, file=out) return 0 diff --git a/fork-kit/review/tests/comments.test.py b/fork-kit/review/tests/comments.test.py index d5e660a06a839..8a6b81431ab93 100644 --- a/fork-kit/review/tests/comments.test.py +++ b/fork-kit/review/tests/comments.test.py @@ -138,6 +138,15 @@ def test_a_state_line_in_a_code_block_or_quote_is_no_state(self): with self.subTest(wrap=wrap): self.assertIn('no state', self.verdict(body)) + def test_the_state_rule_is_the_gates(self): + """What counts as a state line is gate code (review_judge.has_state_line), not a second copy in the kit, so + the kit and the gate read one rule when the gate starts enforcing `state_line` (#797).""" + self.assertIs(review_kit.has_state_line, review_judge.has_state_line) + for line, answered in (('state: fine', True), ('**State:** fine', True), ('- state: fine', True), + ('state:', False), ('state: ', False), ('the state is fine', False)): + with self.subTest(line=line): + self.assertIs(review_judge.has_state_line(f'lens: code\n{line}\n'), answered) + def test_a_major_fails(self): body = CLEAN.replace('major: none', 'major: x is cut') self.assertEqual(self.m.check(body, 'tool ready --head', SHA)[0], 1) @@ -222,11 +231,6 @@ def test_not_utf8_is_a_plain_message(self): 'ok = GOOD <= set(words)', (Check, 'test_another_head_fails')), 'a state line is needed': ("words.append('state' if has_state_line(body) else 'no state')", "words.append('state')", (Check, 'test_a_missing_state_line_fails')), - 'a state line needs an answer': (r"STATE_RE = re.compile(r'state\s*:\s*\S', re.I)", - r"STATE_RE = re.compile(r'state\s*:', re.I)", - (Check, 'test_an_empty_state_line_is_no_state')), - 'a state line outside code and quotes': ('for raw in lens.plain_lines(body))', 'for raw in body.splitlines())', - (Check, 'test_a_state_line_in_a_code_block_or_quote_is_no_state')), 'a short sha is no read': ("if not lens.FULL_SHA.fullmatch(sha or ''):", 'if not sha:', (Doc, 'test_every_example_reads_as_it_says')), 'the gate flags a looking comment': ('if review.lens_problem(post):', 'if False:', @@ -236,6 +240,17 @@ def test_not_utf8_is_a_plain_message(self): (Check, 'test_the_head_is_matched_whatever_its_case')), } +# rule: (text in the gate's review_judge.py, the text that breaks it, the kit test that must then fail): the kit +# reads these rules from the gate, so a broken gate rule must fail the kit's own tests too. +JUDGE = os.path.join(REPO, 'fork-ci', 'actions', 'pr-queue', 'review_judge.py') +GATE_MUTATIONS = { + 'a state line needs an answer': (r"STATE_RE = re.compile(r'state\s*:\s*\S', re.I)", + r"STATE_RE = re.compile(r'state\s*:', re.I)", + (Check, 'test_an_empty_state_line_is_no_state')), + 'a state line outside code and quotes': ('for raw in lens.plain_lines(body))', 'for raw in body.splitlines())', + (Check, 'test_a_state_line_in_a_code_block_or_quote_is_no_state')), +} + TEMPLATE_DOCS = ('SKILL.md', os.path.join('eval', 'lens.md'), 'COMMENTS.md') FENCE_RE = re.compile(r'^(`{3,})[a-z]*\s*$') @@ -469,6 +484,59 @@ def report(name, sha): comments = ' '.join(kit_text('COMMENTS.md').split()) self.assertIn('on `yes` it still posts the override for the fix head', comments) + def test_the_skill_says_what_happens_to_a_fix_past_the_last_round(self): + """A fix after the last lens round that is not nit-only gets no new round: the orchestrator checks it and + posts the override, and a blocker or major left over counts as stuck (#914).""" + skill = ' '.join(kit_text('SKILL.md').split()) + for words in ('A fix after the last lens round (`lens_rounds` used up) that is not nit-only', + 'gets no new lens round: the orchestrator checks that fix diff itself and posts the override for ' + 'the fix head', + 'A blocker or major left over counts as stuck'): + with self.subTest(says=words): + self.assertIn(words, skill) + + def test_the_docs_say_which_override_counts_as_the_gate_reads_it(self): + """The gate counts an override only from the configured author association, never edited and not hidden + (lens.Review.override_sha); the skill and COMMENTS.md say all three (#914).""" + review = review_kit.reader('tool ready --head') + post = lens_pr(f'tool ready --head {SHA}: read the fix diff and its tests')['comments'][0] + self.assertEqual(review.override_sha(post), SHA) + for name, change in (('edited', {'includesCreatedEdit': True}), ('hidden', {'isMinimized': True}), + ('another association', {'authorAssociation': 'CONTRIBUTOR'})): + with self.subTest(override=name): + self.assertIsNone(review.override_sha({**post, **change})) + skill = ' '.join(kit_text('SKILL.md').split()) + self.assertIn('it counts only from the configured author association, the queue config\'s ' + '`override.author_association`, and only while it is never edited and not hidden', skill) + comments = ' '.join(kit_text('COMMENTS.md').split()) + self.assertIn('counts only from the configured author association, never edited and not hidden', comments) + + def test_the_docs_say_to_run_the_kit_at_the_pinned_release(self): + """The kit imports the gate's code from its own checkout, so the docs say to run it at the release the + project's gate pins (#797).""" + readme = kit_text('README.md') + self.assertIn('\n## Which fork version\n', readme) + self.assertIn('run the kit from a checkout at the pinned release', ' '.join(readme.split())) + for name in ('SKILL.md', 'REVIEW.md'): + with self.subTest(doc=name): + self.assertIn('Run the kit from a fork checkout at the release the project\'s gate pins (README.md, ' + '"Which fork version")', ' '.join(kit_text(name).split())) + + def test_review_md_says_which_decides_the_runner(self): + """REVIEW.md says whether its file or T3's review rules setting decides the runner (#797). It says nothing in + T3 reads the setting yet; when T3's docs stop saying so, this fails and REVIEW.md must be read again.""" + review = ' '.join(kit_text('REVIEW.md').split()) + for words in ("**This file or T3's review rules setting:**", 'Nothing in T3 reads it yet, so today this file ' + 'decides', "T3's setting the lenses T3 starts on that machine", + 'this file every lens an agent starts by hand from the skill and what `plan` prints', + 'the gate does not read either'): + with self.subTest(says=words): + self.assertIn(words, review) + with open(os.path.join(REPO, 'docs', 'fork', 'README.md'), encoding='utf-8') as f: + t3 = ' '.join(f.read().split()) + self.assertIn('`reviewRules`', t3) + self.assertIn('Nothing reads it yet', t3) + def test_the_skill_says_whichever_is_higher(self): """review_round takes the higher of the change count and the round marker, never the sum.""" self.assertEqual(review_judge.review_round([('code', 'a' * 40), ('code r3', 'a' * 40)]), 3) @@ -489,6 +557,22 @@ def test_each_rule_has_a_test_that_fails_without_it(self): cls(test).run(result) self.assertFalse(result.wasSuccessful(), f'{test} still passes with the rule {rule!r} broken') + def test_each_gate_rule_the_kit_reads_has_a_kit_test_that_fails_without_it(self): + with open(JUDGE, encoding='utf-8') as f: + source = f.read() + for rule, (text, broken, (base, test)) in GATE_MUTATIONS.items(): + with self.subTest(rule=rule): + self.assertEqual(source.count(text), 1, f'the red check for {rule!r} no longer matches the gate') + judge = types.ModuleType('review_judge_broken') + judge.__file__ = JUDGE + exec(compile(source.replace(text, broken), JUDGE, 'exec'), judge.__dict__) + kit = load(inspect.getsource(review_kit)) + kit.has_state_line = judge.has_state_line + cls = type('Broken', (base,), {'m': kit}) + result = unittest.TestResult() + cls(test).run(result) + self.assertFalse(result.wasSuccessful(), f'{test} still passes with the gate rule {rule!r} broken') + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/fork-kit/review/tests/eval.test.py b/fork-kit/review/tests/eval.test.py index dcbaea28d098d..4f68bb3b4950a 100644 --- a/fork-kit/review/tests/eval.test.py +++ b/fork-kit/review/tests/eval.test.py @@ -6,7 +6,7 @@ python3 -I -B fork-kit/review/tests/eval.test.py """ -import io, json, os, shutil, socket, subprocess, sys, tempfile, types, unittest +import glob, io, json, os, shutil, socket, subprocess, sys, tempfile, types, unittest from unittest import mock sys.dont_write_bytecode = True # the CI runner has no -B; keep the kit folder free of __pycache__ @@ -302,6 +302,41 @@ def test_no_transcripts(self): self.ok('runs') self.assertIn('0 runs costed', self.ok('cost')) + def test_sub_agent_transcripts_count(self): # #797 item 6 + """A run's own sub-agents (/subagents/*.jsonl) are its cost; a run started as a sub-agent is found by + the sub-agent glob, as in the example config.""" + self.cfg['transcripts'] = ['../transcripts/*.jsonl', '../transcripts/*/subagents/*.jsonl'] + self.put('eval/eval.json', json.dumps(self.cfg)) + self.ok('runs') + a = next(r for r in self.runs() if r['model'] == 'model-a') + b = next(r for r in self.runs() if r['model'] == 'model-b') + self.put('transcripts/one.jsonl', transcript(f'RUN-ID: {a["id"]}\n\nYou are one reviewer', [ + turn('m1', '2026-01-01T00:01:00Z', output_tokens=100)])) + self.put('transcripts/one/subagents/agent-x.jsonl', transcript('read src/store.py and report', [ + turn('s1', '2026-01-01T00:01:30Z', output_tokens=40)])) + self.put('transcripts/orchestrator.jsonl', transcript('start the eval runs', [ + turn('o1', '2026-01-01T00:00:10Z', output_tokens=10 ** 6)])) # starts runs as sub-agents, is none + self.put('transcripts/orchestrator/subagents/agent-y.jsonl', transcript(f'RUN-ID: {b["id"]}\n\nreview', [ + turn('y1', '2026-01-01T00:00:20Z', output_tokens=7)])) + out = self.ok('cost') + self.assertIn('2 runs costed', out) + with open(os.path.join(self.work, 'gt', 'cost.json')) as f: + cost = json.load(f) + self.assertEqual((cost[a['id']]['output'], cost[a['id']]['files']), (140, 2)) + self.assertEqual((cost[b['id']]['output'], cost[b['id']]['files']), (7, 1)) + self.assertEqual(self.ok('cost'), out) + + def test_the_example_config_finds_sub_agent_transcripts(self): # #797 item 6 + with open(os.path.join(KIT, 'eval', 'eval.example.json'), encoding='utf-8') as f: + patterns = json.load(f)['transcripts'] + home = os.path.join(self.dir, 'home') + os.environ['HOME'] = home + for rel in ('.claude/projects/p/s.jsonl', '.claude/projects/p/s/subagents/agent-a1.jsonl'): + self.put(os.path.join('home', rel), '{}\n') + with self.subTest(rel): + self.assertTrue(any(os.path.join(home, rel) in glob.glob(os.path.expanduser(g)) for g in patterns), + f'no pattern of eval.example.json finds {rel}') + class Analyze(Fixture): def scores(self, case, found): @@ -366,6 +401,24 @@ def test_scores_that_miss_a_review_are_a_plain_message(self): self.put('work/judge/A/scores.json', json.dumps({'reviews': {}})) self.assertIn('judge the case again', self.plain(self.ev('analyze'))) + def test_malformed_scores_are_a_plain_message(self): # #797 item 5: never a traceback + self.ok('runs') + self.report_all() + self.ok('judge-prep', 'A') + with open(os.path.join(self.work, 'gt', 'judgemap.json')) as f: + review = sorted(json.load(f)['A'])[0] + good = {'found': ['A-M1'], 'findings': [{'n': 1, 'verdict': 'match'}]} + for scores in ([], 'x', {'reviews': []}, {'reviews': {review: {**good, 'found': 'A-M1'}}}, + {'reviews': {review: {**good, 'found': [1]}}}, + {'reviews': {review: {**good, 'findings': [1]}}}, + {'reviews': {review: {**good, 'findings': {'n': 1}}}}, + {'reviews': {review: {**good, 'findings': [{'verdict': ['fp']}]}}}): + with self.subTest(scores=scores): + self.put('work/judge/A/scores.json', json.dumps(scores)) + said = self.plain(self.ev('analyze')) + self.assertIn('judge the case again', said) + self.assertIn('judge_prompt.txt', said) + class Config(Fixture): def test_missing_empty_old_newer_and_broken(self): @@ -436,6 +489,12 @@ def test_the_command_line(self): (Runs, 'test_runs_again_the_same')), 'only a run\'s own session counts': ('m = RUN_RE.match(_first_user_text(f).lstrip())', 'm = RUN_RE.search(_first_user_text(f))', (Cost, 'test_tokens_dollars_and_minutes')), + "a run's own sub-agents count": ("os.path.join(glob.escape(f[:-len('.jsonl')]), 'subagents', '*.jsonl')", + "os.path.join(glob.escape(f[:-len('.jsonl')]), 'none', '*.jsonl')", + (Cost, 'test_sub_agent_transcripts_count')), + 'malformed scores are refused': (" if bad:\n raise Problem(f'case {name}: {path} is not in the shape", + " if False:\n raise Problem(f'case {name}: {path} is not in the shape", + (Analyze, 'test_malformed_scores_are_a_plain_message')), 'a message is counted once': ("usage[m.get('id') or e.get('requestId') or len(usage)] = m['usage']", "usage[len(usage)] = m['usage']", (Cost, 'test_tokens_dollars_and_minutes')), 'idle gaps are not active': ('if b - a <= gap)', ')', (Cost, 'test_tokens_dollars_and_minutes')), diff --git a/fork-kit/review/tests/plan.test.py b/fork-kit/review/tests/plan.test.py index 3589548f8fe11..f67fd31a43c41 100644 --- a/fork-kit/review/tests/plan.test.py +++ b/fork-kit/review/tests/plan.test.py @@ -178,6 +178,62 @@ def test_a_base_that_is_no_commit(self): self.git('init', '-q') self.assertIn('nosuch is not a commit', self.plain(self.cli('plan', '--base', 'nosuch'))) + def commit(self, message, *paths): + for rel in paths: + self.put(rel, f'{message}\n') + self.git('add', '-A') + self.git('commit', '-q', '-m', message) + + def test_a_base_config_that_is_not_utf8_is_refused_as_the_gate_refuses_it(self): # #797 item 1 + path = self.config() + with open(path, 'rb') as f: + data = f.read().replace(b'docs/review.md', b'docs/r\xe9view.md') # Latin-1, valid JSON otherwise + with open(path, 'wb') as f: + f.write(data) + self.git('init', '-q') + self.commit('base', 'src/app.ts') + self.git('checkout', '-q', '-b', 'topic') + self.commit('change', 'src/x.ts') + with self.assertRaises(review_kit.gate_config.ConfigError): # the gate's reader, on the same bytes + review_kit.gate_config.parse(data, 'config') + self.assertIn('not UTF-8', self.plain(self.run_plan('--base', 'main'))) + self.assertIn('not UTF-8', self.plain(self.cli('plan', '--base', 'main'))) + + def test_base_reads_every_merge_base_as_the_gate_does(self): # #797 item 2: criss-cross merges + self.config() + self.git('init', '-q') + self.commit('root', 'src/app.ts') + self.git('checkout', '-q', '-b', 'x') + self.commit('x', 'src/storage/x.ts') + self.git('checkout', '-q', '-b', 'y', 'main') + self.commit('y', 'src/y.ts') + self.git('checkout', '-q', '-B', 'main', 'x') + self.git('merge', '-q', '--no-ff', '-m', 'main takes y', 'y') + self.git('checkout', '-q', '-b', 'topic', 'y') + self.git('merge', '-q', '--no-ff', '-m', 'topic takes x', 'x') + self.commit('topic', 'src/t.ts') + bases = subprocess.run([*GIT, '-C', self.dir, 'merge-base', '--all', 'main', 'topic'], capture_output=True, + text=True, env=self.env).stdout.split() + self.assertEqual(len(bases), 2, 'the fixture needs two merge bases') + code, out, err = self.cli('plan', '--base', 'main') + self.assertEqual((code, err), (0, ''), out) + # from one merge base git sees two paths (src/t.ts and one of the others); the gate sees all three + self.assertIn('3 changed paths', out) + self.assertIn('weight: critical', out) + + def test_base_reads_paths_whatever_the_repository_git_settings(self): # #797 item 2: unusual git settings + self.config() + self.git('init', '-q') + self.commit('base', 'src/app.ts', 'src/sub/a.ts') + self.git('checkout', '-q', '-b', 'topic') + self.commit('change', 'src/storage/wallet.ts', 'src/sub/a.ts') + self.git('config', 'diff.relative', 'true') # from src/sub, a plain git diff shows only src/sub's paths + out, err = io.StringIO(), io.StringIO() + code = self.m.run(['plan', '--root', os.path.join(self.dir, 'src', 'sub'), '--base', 'main'], out, err) + self.assertEqual((code, err.getvalue()), (0, ''), out.getvalue()) + self.assertIn('2 changed paths', out.getvalue()) + self.assertIn('weight: critical', out.getvalue()) + class States(Project): """The files the plan reads, in every state they can be in.""" @@ -274,6 +330,24 @@ def test_plan_needs_one_source_of_changes(self): self.assertIn('exactly one of', self.plain(self.cli(*args))) +class Fork(unittest.TestCase): + def test_the_fork_settings_point_the_kit_at_the_forks_queue_config(self): # #914 item 3 + settings, note = review_kit.load_settings(REPO, '.github/fork-review-kit.json') + cfg, cfg_note = review_kit.load_queue_config(REPO, settings) + self.assertEqual((settings['queue_config'], note, cfg_note), ('.github/fork-pr-queue.json', None, None)) + self.assertEqual(cfg.review.mode, 'enforce') + out, err = io.StringIO(), io.StringIO() + changes_file = os.path.join(tempfile.mkdtemp(prefix='review-kit-fork-'), 'changes.bin') + self.addCleanup(shutil.rmtree, os.path.dirname(changes_file)) + with open(changes_file, 'w', encoding='utf-8') as f: + f.write('M\0fork-kit/review/SKILL.md\0') + code = review_kit.run(['plan', '--root', REPO, '--settings', '.github/fork-review-kit.json', '--changes', + changes_file], out, err) + self.assertEqual((code, err.getvalue()), (0, ''), out.getvalue()) + self.assertNotIn('note:', out.getvalue()) + self.assertIn('weight: critical', out.getvalue()) + + # rule: (text in lib/review_kit.py, the text that breaks it, (test class, the test that must then fail)) MUTATIONS = { 'an empty settings file is refused': (' if not text.strip():\n raise Problem(f\'the kit settings', @@ -301,6 +375,15 @@ def test_plan_needs_one_source_of_changes(self): (Plan, 'test_the_state_question_is_in_every_plan')), 'two lenses are independent': ("if len(lenses) > 1 else 'one read-only agent')", "if False else 'one read-only agent')", (Plan, 'test_a_critical_path_needs_two_independent_lenses')), + 'a base config is read as bytes': ('text = r.stdout if r.returncode == 0 else None', + "text = r.stdout.decode('utf-8', 'replace') if r.returncode == 0 else None", + (Plan, 'test_a_base_config_that_is_not_utf8_is_refused_as_the_gate_refuses_it')), + 'the gate\'s changed paths': ('found, why = head_check.changed_paths(head_check.Checkout(git_dir(root), ' + 'bare=(base, head)), base, head)', + "found, why = review_judge.parse_name_status(subprocess.run(['git', '-C', root, " + "'diff', '--name-status', '-z', '-M', f'{base}...HEAD'], capture_output=True)" + ".stdout.decode()), None", + (Plan, 'test_base_reads_paths_whatever_the_repository_git_settings')), 'the config is read from the base': ("['git', '-C', root, 'show', f'{base}:{rel}']", "['false']", (Plan, 'test_base_reads_the_config_and_changes_from_git')), }