Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/fork-pr-queue.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
23 changes: 23 additions & 0 deletions .github/scripts/fork-contracts.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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")
Expand Down
3 changes: 2 additions & 1 deletion docs/fork/agent-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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._
Expand Down
3 changes: 2 additions & 1 deletion fork-kit/review/COMMENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <sha> comment.md`.
of your own before posting it: `python3 -I fork-kit/review/lib/review_kit.py check [--settings <file>] --head <sha>
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.

Expand Down
4 changes: 2 additions & 2 deletions fork-kit/review/REVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <file>` to every `plan` and `check`.
the file under another name gives it with `--settings <file>` 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
Expand Down
9 changes: 5 additions & 4 deletions fork-kit/review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <checkout> --base origin/main
python3 -I fork-kit/review/lib/review_kit.py plan --root <checkout> [--settings <file>] --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
Expand Down Expand Up @@ -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: _<state question>_
> 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 <sha>` 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 <file>] --head <sha>` 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

Expand Down Expand Up @@ -189,7 +190,7 @@ but every report keeps the `state:` line. The sha is `git rev-parse HEAD` of the
Templates in briefs write `<sha>`, never a real one. Check before posting:

```
python3 -I fork-kit/review/lib/review_kit.py check --root <checkout> --head <sha> comment.md
python3 -I fork-kit/review/lib/review_kit.py check --root <checkout> [--settings <file>] --head <sha> 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,
Expand Down
7 changes: 5 additions & 2 deletions fork-kit/review/eval/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<session>/subagents/` (the example config globs those too), and the
sub-agents a run starts itself (`<run session>/subagents/*.jsonl`) count toward that run. `review_eval.py
sub-agent has its transcript under `<session>/subagents/` or `<session>/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 `<session>/subagents/`; for a run that is a sub-agent, those whose `agent-<id>.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
Expand Down
6 changes: 5 additions & 1 deletion fork-kit/review/eval/eval.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
94 changes: 70 additions & 24 deletions fork-kit/review/lib/review_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,20 +306,65 @@ def _stamp(s):
return datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp()


def _meta(f):
"""A sub-agent transcript's meta file (agent-<id>.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 <session>/subagents/, flat whatever its depth (workflow agents under
subagents/workflows/wf_*/), each with agent-<id>.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: <session>.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 = {}
for pattern in c['transcripts']:
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 <session>/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:
Expand All @@ -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 <synthetic> 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 <synthetic> 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 -----------------------------------------------------------------------------------------------------
Expand Down
Loading
Loading