diff --git a/.github/fork-pr-queue.json b/.github/fork-pr-queue.json index 2f90c5879bfa6..9e74fac4ad122 100644 --- a/.github/fork-pr-queue.json +++ b/.github/fork-pr-queue.json @@ -32,8 +32,8 @@ ".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-review-kit.json", ".github/fork-secret-sweep-gone-tips.txt", ".github/fork-tests-upstream.json", ".github/fork-upstream.json", diff --git a/.github/scripts/fork-contracts.test.py b/.github/scripts/fork-contracts.test.py index ac6e29ff97e38..9f4e004e64af8 100644 --- a/.github/scripts/fork-contracts.test.py +++ b/.github/scripts/fork-contracts.test.py @@ -80,6 +80,10 @@ case: the checkout's timeout, the wait cap (or the script's git calls, if longer) and one last poll, from the script's own limits, with a minute to spare for the job's set-up. + review-kit the review kit (fork-kit/review) reads the fork's kit settings + (.github/fork-review-kit.json, given with --settings) and through them the fork's queue + config in enforce; without --settings its plan names that file. + python3 .github/scripts/fork-contracts.test.py Needs PyYAML, git and bash. Each check prints ok/FAIL; any FAIL exits 1. @@ -4884,6 +4888,25 @@ def policy_mutant(mutate, limits=POLICY_LIMITS): }.items(): check(f"policies: {label} fails", *policy_mutant(lambda p, w, t: None, {**POLICY_LIMITS, **change})) +# --- review-kit (#957) --------------------------------------------------------------------------- +# The fork keeps its kit settings under its own name, so the general kit's tests do not name them (#957 item 5). + + +def review_plan(*args): + changes = work / "review-kit-changes.bin" + changes.write_bytes(b"M\0fork-kit/review/SKILL.md\0") + r = subprocess.run([sys.executable, "-I", "-B", str(root / "fork-kit/review/lib/review_kit.py"), "plan", "--root", + str(root), *args, "--changes", str(changes)], capture_output=True, text=True, timeout=120) + return r.returncode, r.stdout, r.stderr + + +code, out, err = review_plan("--settings", ".github/fork-review-kit.json") +check("review-kit: the fork's settings point the kit at the fork's queue config, in enforce, with no note", + (code, err) == (0, "") and "note:" not in out and "weight: critical" in out, out + err) +code, out, err = review_plan() +check("review-kit: without --settings the plan names the fork's settings file", + code == 0 and "pass --settings .github/fork-review-kit.json" in out, out + err) + shutil.rmtree(work, ignore_errors=True) if failures: print(f"{len(failures)} failed") diff --git a/docs/fork/agent-rules.md b/docs/fork/agent-rules.md index 77800cc25444a..d57af8276c7c2 100644 --- a/docs/fork/agent-rules.md +++ b/docs/fork/agent-rules.md @@ -55,7 +55,8 @@ Where a tool enforces a rule, the tool is the authority. - Never update pull request branches by hand when a merge queue does it. _Why: it restarts every CI at once._ - Reports, handoffs and review notes go in the pull request or an issue. _Why: the repository holds current text._ - Reviews follow the [review skill](../../fork-kit/review/SKILL.md) (weights, the state question, round limit); - never restate it. _Why: one source._ + never restate it; its `plan` and `check` take `--settings .github/fork-review-kit.json` here. _Why: one source; + without it the kit reads no queue config and plans one lens._ - No `git stash`; edit tracked files in place. _Why: worktrees share the stash; a move drops `+x`._ - In a fork: build on upstream's mechanisms, check upstream first, never push, comment or open anything upstream. _Why: thin forks rebase cleanly; upstream is the owner's._ diff --git a/fork-kit/review/COMMENTS.md b/fork-kit/review/COMMENTS.md index 00730c761e1fb..56ee904f5813e 100644 --- a/fork-kit/review/COMMENTS.md +++ b/fork-kit/review/COMMENTS.md @@ -9,7 +9,8 @@ page shows the format with examples. The rules themselves are the gate's code an Every example below is checked: `tests/comments.test.py` feeds each one through the gate's own parser (`lens.py`, `review_judge.py`) and fails when the gate reads it differently from what the line above it says. To check a comment -of your own before posting it: `python3 -I fork-kit/review/lib/review_kit.py check --head comment.md`. +of your own before posting it: `python3 -I fork-kit/review/lib/review_kit.py check [--settings ] --head +comment.md` (`--settings` when the project's kit settings are not at `.github/review-kit.json`). The examples use the override prefix `tool ready --head`. A project's prefix is `override.prefix` in its queue config. diff --git a/fork-kit/review/REVIEW.md b/fork-kit/review/REVIEW.md index b295b6a7743c3..c645dd00a0dfa 100644 --- a/fork-kit/review/REVIEW.md +++ b/fork-kit/review/REVIEW.md @@ -68,8 +68,8 @@ Optional: `.github/review-kit.json`. No file means the defaults. Every key is op [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. 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`. +the file under another name gives it with `--settings ` to every `plan` and `check`; without it, a plan that +finds no queue config names any `.github/*review-kit*.json` it sees as the likely missing `--settings`. **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 diff --git a/fork-kit/review/SKILL.md b/fork-kit/review/SKILL.md index 26db256416057..e5805f2d1d4f5 100644 --- a/fork-kit/review/SKILL.md +++ b/fork-kit/review/SKILL.md @@ -35,7 +35,7 @@ A project with its own tier names maps them onto these three in its rules (for e critical). A project with **no CI** (no queue config) has no gate: every change is normal with one lens, by hand. ``` -python3 -I fork-kit/review/lib/review_kit.py plan --root --base origin/main +python3 -I fork-kit/review/lib/review_kit.py plan --root [--settings ] --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 @@ -155,8 +155,9 @@ A lens with no prompt file of its own (the fallback lens `review`) uses this tex > full and what they call into. Find bugs at their root: the unhappy branch of every `if`, error paths, empty and > bounds, and where else the same pattern occurs. Answer the state question on a `state:` line: __ > Every finding needs file:line and inputs or state leading to the wrong result. Post one comment in the format of -> §6, the header first. Check it with `review_kit.py check --head ` before posting (a blocker or major exits 1 by -> design: post it as found, never softened); never edit a posted comment (post a new one). +> §6, the header first. Check it with `review_kit.py check [--settings ] --head ` before posting (a +> blocker or major exits 1 by design: post it as found, never softened); never edit a posted comment (post a new +> one). ## 5. Who runs what @@ -189,7 +190,7 @@ but every report keeps the `state:` line. The sha is `git rev-parse HEAD` of the Templates in briefs write ``, never a real one. Check before posting: ``` -python3 -I fork-kit/review/lib/review_kit.py check --root --head comment.md +python3 -I fork-kit/review/lib/review_kit.py check --root [--settings ] --head comment.md ``` Exit 0 only for a read of that head with a findings section, no blocker or major, and a state line; otherwise exit 1, diff --git a/fork-kit/review/eval/README.md b/fork-kit/review/eval/README.md index f908cd855acd9..849d9b2e3d96c 100644 --- a/fork-kit/review/eval/README.md +++ b/fork-kit/review/eval/README.md @@ -55,8 +55,11 @@ is a small sample, and 1-2 bugs between settings is noise, but three results sha 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. 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 + sub-agent has its transcript under `/subagents/` or `/subagents/workflows/wf_*/` (the example + config globs those too). The sub-agents a run starts count toward that run: for a run that is the session, every + transcript under `/subagents/`; for a run that is a sub-agent, those whose `agent-.meta.json` names + it (or one of them) as `parentAgentId`. Each message is priced at its own model, so a sub-agent on another model + needs that model under `prices` too. `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 f642064dea645..750481a8623e7 100644 --- a/fork-kit/review/eval/eval.example.json +++ b/fork-kit/review/eval/eval.example.json @@ -4,7 +4,11 @@ "repo": "../model-eval/repo.git", "truth": "truth.json", "briefs": "briefs", - "transcripts": ["~/.claude/projects/*/*.jsonl", "~/.claude/projects/*/*/subagents/*.jsonl"], + "transcripts": [ + "~/.claude/projects/*/*.jsonl", + "~/.claude/projects/*/*/subagents/*.jsonl", + "~/.claude/projects/*/*/subagents/workflows/*/*.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 c3297e1aa793c..c71b7180165a5 100644 --- a/fork-kit/review/lib/review_eval.py +++ b/fork-kit/review/lib/review_eval.py @@ -306,6 +306,52 @@ def _stamp(s): return datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp() +def _meta(f): + """A sub-agent transcript's meta file (agent-.meta.json beside it) as a dict, or {}.""" + try: + with open(f[:-len('.jsonl')] + '.meta.json', encoding='utf-8') as fh: + m = json.load(fh) + return m if isinstance(m, dict) else {} + except (OSError, ValueError): + return {} + + +def _own_files(f): + """The run's transcript `f` and every sub-agent transcript that is its cost, each once. Claude Code keeps every + sub-agent of a session in /subagents/, flat whatever its depth (workflow agents under + subagents/workflows/wf_*/), each with agent-.meta.json naming its parentAgentId when a sub-agent started it. + A run that is the session: every one of them. A run that is itself a sub-agent: those whose parentAgentId is the + run's agent id or one of theirs, at any depth.""" + if not f.endswith('.jsonl'): + return [f] + if 'subagents' not in os.path.normpath(f).split(os.sep)[:-1]: # the session file: .jsonl + tree = os.path.join(f[:-len('.jsonl')], 'subagents') + return [f, *sorted(glob.glob(os.path.join(glob.escape(tree), '**', '*.jsonl'), recursive=True))] + tree = os.path.dirname(f) + while os.path.basename(tree) != 'subagents': # the session's subagents/ folder, above workflows/wf_*/ + tree = os.path.dirname(tree) + agents = {os.path.basename(g)[len('agent-'):-len('.jsonl')]: g + for g in sorted(glob.glob(os.path.join(glob.escape(tree), '**', 'agent-*.jsonl'), recursive=True))} + own, ids, grew = [f], {os.path.basename(f)[len('agent-'):-len('.jsonl')]}, True + while grew: + grew = False + for aid, g in agents.items(): + if aid not in ids and _meta(g).get('parentAgentId') in ids: + ids.add(aid) + own.append(g) + grew = True + return own + + +def _usage_tokens(u): + """One message's usage as the PRICE_KEYS token counts.""" + cc = u.get('cache_creation') or {} + return {'input': u.get('input_tokens', 0), 'output': u.get('output_tokens', 0), + 'cache_read': u.get('cache_read_input_tokens', 0), + 'cache_write_5m': cc.get('ephemeral_5m_input_tokens', 0) if cc else u.get('cache_creation_input_tokens', 0), + 'cache_write_1h': cc.get('ephemeral_1h_input_tokens', 0) if cc else 0} + + def cost(c, out): runs = {r['id']: r for r in read_runs(c)} files = {} @@ -313,13 +359,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: - # ... 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 [])]: + # ... and the sub-agents it started are its cost too (_own_files). Each file once, however many + # patterns find it. + for g in _own_files(f): if g not in files.setdefault(m.group(1), []): files[m.group(1)].append(g) - result = {} + result, unpriced = {}, set() for rid, fs in sorted(files.items()): usage, times, model = {}, [], None for f in fs: @@ -338,32 +383,33 @@ def cost(c, out): pass m = e.get('message') if e.get('type') == 'assistant' and isinstance(m, dict) and isinstance(m.get('usage'), dict): - model = m.get('model') or model - usage[m.get('id') or e.get('requestId') or len(usage)] = m['usage'] - t = dict.fromkeys(('input', 'output', 'cache_write_5m', 'cache_write_1h', 'cache_read'), 0) - for u in usage.values(): - t['input'] += u.get('input_tokens', 0) - t['output'] += u.get('output_tokens', 0) - t['cache_read'] += u.get('cache_read_input_tokens', 0) - cc = u.get('cache_creation') or {} - if cc: - t['cache_write_5m'] += cc.get('ephemeral_5m_input_tokens', 0) - t['cache_write_1h'] += cc.get('ephemeral_1h_input_tokens', 0) - else: - t['cache_write_5m'] += u.get('cache_creation_input_tokens', 0) + # the run's own model: from its own file, never a sub-agent's or a message's + if f == fs[0] and any(_usage_tokens(m['usage']).values()): + model = m.get('model') or model + usage[m.get('id') or e.get('requestId') or len(usage)] = (m.get('model'), m['usage']) + t, usd = dict.fromkeys(PRICE_KEYS, 0), 0 + for msg_model, u in usage.values(): + ut = _usage_tokens(u) + for k in PRICE_KEYS: + t[k] += ut[k] + if not any(ut.values()): + continue # nothing to price (Claude Code's own messages) + p = c['prices'].get(msg_model or runs[rid]['model']) # each message at its own model's price + if p and usd is not None: + usd += sum(ut[k] * p[k] for k in PRICE_KEYS) + elif not p: + usd = None + unpriced.add(msg_model or runs[rid]['model']) times.sort() gap = c['idle_gap_seconds'] active = sum(b - a for a, b in zip(times, times[1:]) if b - a <= gap) - p = c['prices'].get(runs[rid]['model']) - usd = round(sum(t[k] * p[k] for k in PRICE_KEYS) / 1e6, 3) if p else None - result[rid] = {**t, 'usd': usd, 'active_min': round(active / 60, 1), 'calls': len(usage), - 'model_seen': model, 'files': len(fs)} + result[rid] = {**t, 'usd': None if usd is None else round(usd / 1e6, 3), 'active_min': round(active / 60, 1), + 'calls': len(usage), 'model_seen': model, 'files': len(fs)} write(gt(c, 'cost.json'), dump(result)) missing = sorted(set(runs) - set(result)) - unpriced = sorted({runs[r]['model'] for r in result if result[r]['usd'] is None}) print(f'{len(result)} runs costed; no transcript: {", ".join(missing) or "none"}', file=out) if unpriced: - print(f'no price for {", ".join(unpriced)}: add it under prices', file=out) + print(f'no price for {", ".join(sorted(unpriced))}: add it under prices', file=out) # --- analyze ----------------------------------------------------------------------------------------------------- diff --git a/fork-kit/review/lib/review_kit.py b/fork-kit/review/lib/review_kit.py index 734e18940996d..aa91684c97ebb 100644 --- a/fork-kit/review/lib/review_kit.py +++ b/fork-kit/review/lib/review_kit.py @@ -16,6 +16,7 @@ No state: every run reads the files again, so the same input gives the same output. A missing, empty, old or broken file gives a plain message and exit 2, never a traceback. """ +import glob import json import os import re @@ -140,15 +141,43 @@ def commit_of(root, ref): return sha +def _git_said(r): + return os.fsdecode(r.stderr or b'').strip()[:200] or f'exit {r.returncode}' + + +def base_file(root, base, rel): + """The bytes of `rel` in the commit `base` (a full sha), or None only when its tree has no such entry. Any other + git failure (a missing tree or blob, a partial clone offline) is a Problem: the file is there, so judging as if it + were not would advise fewer lenses than the gate asks.""" + path = head_check.repo_path(rel) + r = subprocess.run(['git', '-C', root, 'ls-tree', '-z', '--full-tree', base, '--', path], capture_output=True) + if r.returncode != 0: + raise Problem(f'git cannot read the tree of {base[:12]} in {root} to find {rel}: {_git_said(r)}') + if not r.stdout: + return None + r = subprocess.run(['git', '-C', root, 'show', f'{base}:{path}'], capture_output=True) + if r.returncode != 0: + raise Problem(f'{rel} is in {base[:12]} but git cannot read it: {_git_said(r)}; fetch the missing objects ' + f'(or run from a full clone) and plan again') + return r.stdout + + +def other_settings(root): + """Files in `.github` named like kit settings under another name (the fork's `fork-review-kit.json`): the plan + names them when it found no settings and no queue config, as the likely missing --settings.""" + found = glob.glob(os.path.join(glob.escape(os.path.join(root, '.github')), '*review-kit*.json')) + return sorted(os.path.relpath(f, root) for f in found if os.path.relpath(f, root) != SETTINGS) + + def load_queue_config(root, settings, base=None): """(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.""" + judges. Problem for an empty or invalid config (the gate would refuse it too), and for a base config git cannot + read (base_file).""" rel = settings['queue_config'] if base: - r = subprocess.run(['git', '-C', root, 'show', f'{base}:{rel}'], capture_output=True) - text = r.stdout if r.returncode == 0 else None + text = base_file(root, base, rel) else: text = read_text(os.path.join(root, rel), 'the queue config') where = f'{rel} at {base}' if base else rel @@ -168,7 +197,10 @@ def load_queue_config(root, settings, base=None): def git_dir(root): - r = subprocess.run(['git', '-C', root, 'rev-parse', '--absolute-git-dir'], capture_output=True) + """The repository's common git folder (a linked worktree's too): where its objects, `shallow` and `info/grafts` + are.""" + r = subprocess.run(['git', '-C', root, 'rev-parse', '--path-format=absolute', '--git-common-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')) @@ -176,11 +208,17 @@ def git_dir(root): def changes_from(root, base=None, changes=None): """[(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.""" + `base` to HEAD (every merge base, git's safe flags and no global config), after the gate's own Checkout.problem() + (a repository whose grafts, shallow file, alternates or attributes change what git reads is refused, as the gate + refuses it): never fewer paths than the gate sees. Else a file of `git diff --name-status -z -M` output.""" if base: head = commit_of(root, 'HEAD') - found, why = head_check.changed_paths(head_check.Checkout(git_dir(root), bare=(base, head)), base, head) + checkout = head_check.Checkout(git_dir(root), bare=(base, head)) + why = checkout.problem() + if why: + raise Problem(f'the repository at {root} cannot be read as the gate reads it ({why}): its paths could differ ' + f'from the gate\'s; plan from a full clone without it, or give the changes with --changes') + found, why = head_check.changed_paths(checkout, base, head) if found is None: raise Problem(why) return found @@ -395,6 +433,10 @@ def main(argv, out=sys.stdout): settings, note = load_settings(root, opts.get('--settings')) base = commit_of(root, opts['--base']) if '--base' in opts else None cfg, cfg_note = load_queue_config(root, settings, base) + others = other_settings(root) if cfg is None and note else [] + if others: + cfg_note += (f'; {", ".join(others)} looks like kit settings under another name: if it is this project\'s, ' + f'pass --settings {others[0]}') if cmd == 'check': if not rest: raise Problem('check needs the comment: a file, or - for stdin') diff --git a/fork-kit/review/tests/eval.test.py b/fork-kit/review/tests/eval.test.py index 4f68bb3b4950a..e23f8229859c9 100644 --- a/fork-kit/review/tests/eval.test.py +++ b/fork-kit/review/tests/eval.test.py @@ -263,8 +263,13 @@ def transcript(first, entries): return '\n'.join(lines) + '\n' -def turn(mid, at, **usage): - return {'type': 'assistant', 'timestamp': at, 'message': {'id': mid, 'model': 'model-a', 'usage': usage}} +def turn(mid, at, model='model-a', **usage): + return {'type': 'assistant', 'timestamp': at, 'message': {'id': mid, 'model': model, 'usage': usage}} + + +def meta(parent=None, depth=1): + return json.dumps({'agentType': 'general-purpose', 'spawnDepth': depth, + **({'parentAgentId': parent} if parent else {})}) class Cost(Fixture): @@ -280,7 +285,7 @@ def test_tokens_dollars_and_minutes(self): turn('m2', '2026-01-01T00:02:00Z', input_tokens=0, output_tokens=900, cache_creation_input_tokens=500), turn('m3', '2026-01-01T03:00:00Z', output_tokens=0)])) # after a long idle gap: not active self.put('transcripts/two.jsonl', transcript([{'type': 'text', 'text': f'RUN-ID: {b["id"]}'}], [ - turn('n1', '2026-01-01T00:00:30Z', output_tokens=1)])) + turn('n1', '2026-01-01T00:00:30Z', 'model-b', output_tokens=1)])) self.put('transcripts/parent.jsonl', transcript(f'start the runs; RUN-ID: {a["id"]}', [ turn('p1', '2026-01-01T00:00:30Z', output_tokens=10 ** 6)])) # mentions a run, is none self.put('transcripts/broken.jsonl', '{not json\n') @@ -331,12 +336,70 @@ def test_the_example_config_finds_sub_agent_transcripts(self): # #797 item 6 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'): + for rel in ('.claude/projects/p/s.jsonl', '.claude/projects/p/s/subagents/agent-a1.jsonl', + '.claude/projects/p/s/subagents/workflows/wf_1/agent-a2.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}') + def test_sub_agents_at_every_depth_and_in_workflows_count(self): # #957 item 3 + """Claude Code keeps every sub-agent of a session flat in /subagents/ (workflow agents under + subagents/workflows/wf_*/), each with a meta file naming its parentAgentId. A run that is the session counts + all of them; a run that is a sub-agent counts its own descendants only, never its siblings.""" + self.cfg['transcripts'] = ['../transcripts/*.jsonl', '../transcripts/*/subagents/*.jsonl', + '../transcripts/*/subagents/workflows/*/*.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\nreview', [ + turn('m1', '2026-01-01T00:01:00Z', output_tokens=100)])) + self.put('transcripts/one/subagents/workflows/wf_1/agent-w1.jsonl', transcript('a workflow step', [ + turn('w1', '2026-01-01T00:01:10Z', output_tokens=30)])) + self.put('transcripts/one/subagents/workflows/wf_1/agent-w1.meta.json', meta()) + # the orchestrator starts run b as a sub-agent (y); y starts z, z starts zz (and a workflow agent wz); + # x is y's sibling (another run's work): not b's cost + self.put('transcripts/orch.jsonl', transcript('start the eval runs', [ + turn('o1', '2026-01-01T00:00:10Z', output_tokens=10 ** 6)])) + for name, parent, out_tokens, depth, folder in (('y', None, 7, 1, ''), ('z', 'y', 11, 2, ''), + ('zz', 'z', 13, 3, ''), ('wz', 'z', 17, 3, 'workflows/wf_2/'), + ('x', None, 1000, 1, ''), ('xc', 'x', 1000, 2, '')): + first = f'RUN-ID: {b["id"]}\n\nreview' if name == 'y' else f'work of {name}' + self.put(f'transcripts/orch/subagents/{folder}agent-{name}.jsonl', transcript(first, [ + turn(f'{name}1', '2026-01-01T00:00:20Z', 'model-b', output_tokens=out_tokens)])) + self.put(f'transcripts/orch/subagents/{folder}agent-{name}.meta.json', meta(parent, depth)) + out = self.ok('cost') + 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']), (130, 2)) + self.assertEqual((cost[b['id']]['output'], cost[b['id']]['files']), (7 + 11 + 13 + 17, 4)) + self.assertEqual(self.ok('cost'), out) + + def test_each_message_is_priced_at_its_own_model(self): # #957 item 3 + """A sub-agent on another model is priced at that model, and model_seen is the run's own model.""" + self.cfg['prices'] = {'model-a': PRICE, 'model-c': {k: v * 10 for k, v in PRICE.items()}} + 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') + self.put('transcripts/one.jsonl', transcript(f'RUN-ID: {a["id"]}\n\nreview', [ + turn('m1', '2026-01-01T00:01:00Z', output_tokens=1000), + turn('m0', '2026-01-01T00:01:01Z', '', output_tokens=0)])) # nothing to price + self.put('transcripts/one/subagents/agent-s.jsonl', transcript('help', [ + turn('s1', '2026-01-01T00:01:30Z', 'model-c', output_tokens=1000)])) + out = self.ok('cost') + self.assertNotIn('no price', out) + with open(os.path.join(self.work, 'gt', 'cost.json')) as f: + ca = json.load(f)[a['id']] + self.assertEqual(ca['usd'], round((1000 * 20 + 1000 * 200) / 1e6, 3)) + self.assertEqual(ca['model_seen'], 'model-a') + self.put('transcripts/one/subagents/agent-s.jsonl', transcript('help', [ + turn('s1', '2026-01-01T00:01:30Z', 'model-d', output_tokens=1000)])) + out = self.ok('cost') + self.assertIn('no price for model-d: add it under prices', out) + with open(os.path.join(self.work, 'gt', 'cost.json')) as f: + self.assertIsNone(json.load(f)[a['id']]['usd']) + class Analyze(Fixture): def scores(self, case, found): @@ -489,14 +552,26 @@ 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')", + "a run's own sub-agents count": ("tree = os.path.join(f[:-len('.jsonl')], 'subagents')", + "tree = os.path.join(f[:-len('.jsonl')], 'none')", (Cost, 'test_sub_agent_transcripts_count')), + "workflow agents count": ("glob.glob(os.path.join(glob.escape(tree), '**', '*.jsonl'), recursive=True)", + "glob.glob(os.path.join(glob.escape(tree), '*.jsonl'))", + (Cost, 'test_sub_agents_at_every_depth_and_in_workflows_count')), + "a sub-agent run's own descendants count": ("_meta(g).get('parentAgentId') in ids", 'False', + (Cost, 'test_sub_agents_at_every_depth_and_in_workflows_count')), + "a sub-agent run's siblings do not count": (' return own\n', ' return [f, *(g for g in agents.values() if g != f)]\n', + (Cost, 'test_sub_agents_at_every_depth_and_in_workflows_count')), + 'each message at its own price': ("p = c['prices'].get(msg_model or runs[rid]['model'])", + "p = c['prices'].get(runs[rid]['model'])", + (Cost, 'test_each_message_is_priced_at_its_own_model')), + "the run's own model is seen": ("if f == fs[0] and any(_usage_tokens(m['usage']).values()):", 'if True:', + (Cost, 'test_each_message_is_priced_at_its_own_model')), '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')), + 'a message is counted once': ("usage[m.get('id') or e.get('requestId') or len(usage)] = (m.get('model'), m['usage'])", + "usage[len(usage)] = (m.get('model'), m['usage'])", (Cost, 'test_tokens_dollars_and_minutes')), 'idle gaps are not active': ('if b - a <= gap)', ')', (Cost, 'test_tokens_dollars_and_minutes')), 'a case without blocker/major has no recall': ("'bm_recall': len(found & bm) / len(bm) if bm else None", "'bm_recall': len(found & bm) / len(bm)", diff --git a/fork-kit/review/tests/plan.test.py b/fork-kit/review/tests/plan.test.py index f67fd31a43c41..b5db28bf8daf3 100644 --- a/fork-kit/review/tests/plan.test.py +++ b/fork-kit/review/tests/plan.test.py @@ -234,6 +234,59 @@ def test_base_reads_paths_whatever_the_repository_git_settings(self): # #797 i self.assertIn('2 changed paths', out.getvalue()) self.assertIn('weight: critical', out.getvalue()) + def base_repo(self): + """A repository with the config on main and one more commit on topic (checked out).""" + self.config() + self.git('init', '-q') + self.commit('base', 'src/app.ts') + self.git('checkout', '-q', '-b', 'topic') + self.commit('change', 'src/storage/wallet.ts') + + def test_a_base_without_the_config_falls_back(self): + self.git('init', '-q') + self.commit('base', 'src/app.ts') + self.git('checkout', '-q', '-b', 'topic') + self.commit('change', 'src/storage/wallet.ts') + code, out, err = self.run_plan('--base', 'main') + self.assertEqual((code, err), (0, ''), out) + self.assertIn('no queue config .github/pr-queue.json at ', out) + self.assertIn('weight: normal\nlenses: review (one read-only agent)', out) + + def test_a_base_config_git_cannot_read_is_a_problem(self): # #957 item 1 + self.base_repo() + blob = subprocess.run([*GIT, '-C', self.dir, 'rev-parse', 'main:.github/pr-queue.json'], capture_output=True, + text=True, env=self.env, check=True).stdout.strip() + os.remove(os.path.join(self.dir, '.git', 'objects', blob[:2], blob[2:])) # as a partial clone offline + err = self.plain(self.run_plan('--base', 'main')) + self.assertIn('.github/pr-queue.json is in ', err) + self.assertIn('git cannot read it', err) + + def test_a_repository_the_gate_would_refuse_is_refused(self): # #957 item 2: grafts change merge bases + self.base_repo() + for name in ('info/grafts', 'objects/info/alternates', 'shallow'): + with self.subTest(name=name): + path = os.path.join(self.dir, '.git', name) + with open(path, 'w', encoding='utf-8') as f: + f.write('') + err = self.plain(self.run_plan('--base', 'main')) + self.assertIn(f'cannot be read as the gate reads it', err) + self.assertIn(name, err) + os.remove(path) + self.assertEqual(self.run_plan('--base', 'main')[0], 0) + + def test_a_linked_worktree_is_checked_in_the_common_git_folder(self): # #957 item 2 + self.base_repo() + wt = os.path.join(self.dir, 'wt') + self.git('worktree', 'add', '-q', '--detach', wt, 'topic') + out, err = io.StringIO(), io.StringIO() + self.assertEqual(self.m.run(['plan', '--root', wt, '--base', 'main'], out, err), 0, err.getvalue()) + self.assertIn('weight: critical', out.getvalue()) + with open(os.path.join(self.dir, '.git', 'info', 'grafts'), 'w', encoding='utf-8') as f: + f.write('') + out, err = io.StringIO(), io.StringIO() + self.assertEqual(self.m.run(['plan', '--root', wt, '--base', 'main'], out, err), 2, out.getvalue()) + self.assertIn('info/grafts', err.getvalue()) + class States(Project): """The files the plan reads, in every state they can be in.""" @@ -245,6 +298,26 @@ def test_no_queue_config(self): self.assertIn('weight: normal\nlenses: review (one read-only agent)\n', out) self.assertIn('SKILL.md, "Lens prompt"', out) + def test_no_queue_config_names_settings_under_another_name(self): # #957 item 4 + self.put('.github/fork-review-kit.json', {'version': 1, 'queue_config': '.github/fork-pr-queue.json'}) + self.config(rel='.github/fork-pr-queue.json') + code, out, err = self.plan(changes(('M', 'src/storage/wallet.ts'))) + self.assertEqual((code, err), (0, '')) + self.assertIn('no queue config .github/pr-queue.json', out) + self.assertIn('.github/fork-review-kit.json looks like kit settings under another name: if it is this ' + 'project\'s, pass --settings .github/fork-review-kit.json', out) + code, out, err = self.plan(changes(('M', 'src/storage/wallet.ts')), '--settings', '.github/fork-review-kit.json') + self.assertEqual((code, err), (0, '')) + self.assertNotIn('looks like kit settings', out) + self.assertIn('weight: critical', out) + + def test_the_hint_only_when_no_settings_were_read(self): # #957 item 4 + self.put('.github/fork-review-kit.json', {'version': 1}) + self.put('.github/review-kit.json', {'version': 1}) # the project's own settings: nothing missing + out = self.plan(changes(('M', 'a')))[1] + self.assertIn('no queue config', out) + self.assertNotIn('looks like kit settings', out) + def test_an_old_config_without_a_review_block(self): self.config(review=None) code, out, err = self.plan(changes(('M', 'src/app.ts'))) @@ -330,24 +403,6 @@ 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', @@ -375,16 +430,30 @@ def test_the_fork_settings_point_the_kit_at_the_forks_queue_config(self): # #9 (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", + 'a base config is read as bytes': (' return r.stdout\n', " return r.stdout.decode('utf-8', 'replace')\n", (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)', + 'a base config git cannot read is a problem': (" raise Problem(f'{rel} is in {base[:12]} but git cannot read it", + " return None\n raise Problem(f'{rel} is in {base[:12]} " + "but git cannot read it", (Plan, 'test_a_base_config_git_cannot_read_is_a_problem')), + 'a base without the config falls back': (' if not r.stdout:\n return None\n', + " if not r.stdout:\n raise Problem('no config')\n", + (Plan, 'test_a_base_without_the_config_falls_back')), + "the gate's repository check": (' if why:\n raise Problem(f\'the repository at {root} cannot be read', + ' if False:\n raise Problem(f\'the repository at {root} cannot be read', + (Plan, 'test_a_repository_the_gate_would_refuse_is_refused')), + 'the common git folder': ("'--git-common-dir'", "'--absolute-git-dir'", + (Plan, 'test_a_linked_worktree_is_checked_in_the_common_git_folder')), + 'the settings hint': (' if others:\n cfg_note +=', ' if False:\n cfg_note +=', + (States, 'test_no_queue_config_names_settings_under_another_name')), + 'the hint only without settings': ("others = other_settings(root) if cfg is None and note else []", + "others = other_settings(root) if cfg is None else []", + (States, 'test_the_hint_only_when_no_settings_were_read')), + 'the gate\'s changed paths': ('found, why = head_check.changed_paths(checkout, 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']", + 'the config is read from the base': ("['git', '-C', root, 'show', f'{base}:{path}']", "['false']", (Plan, 'test_base_reads_the_config_and_changes_from_git')), }