cluster_review.py

scripts/cluster_review.py

THE POST-RELEASE REVIEW'S FIRST THREE STEPS, as a command rather than as a habit.

cell_shape

tuple[float, int, int, int, int] cluster_review.cell_shape(Path adir, str stem)

One cell's score, answer length, call count and failed weight.

scripts/cluster_review.py:84

Show on the map →

Called by rank, test_a_missing_meta_yields_unknown_and_not_zero, test_failed_weight_de_duplicates_by_mark_text

Calls none

Source · 27 lines
def cell_shape(adir: Path, stem: str) -> tuple[float, int, int, int, int]:
    """FAILED WEIGHT IS DE-DUPLICATED BY MARK TEXT, because replicates repeat every decision and
    summing them counts one mark three times. A mark that any replicate HIT is counted as hit —
    the pessimistic direction would make a flaky judge look like a capability gap.

    `-1` IS RETURNED FOR AN ABSENT MEASUREMENT, never 0, for the reason the vocabulary states
    about `tool_calls`: unknown must not be counted as none.

    @brief Read one cell's shape from its sidecars.
    @return The tuple.
    @version 1
    """
    grade = json.loads((adir / f"{stem}.grade.json").read_text("utf-8"))
    by_mark: dict[str, bool] = {}
    for d in grade.get("decisions", []):
        by_mark[d["mark"]] = by_mark.get(d["mark"], False) or bool(d.get("hit"))
    weights = {d["mark"]: d.get("weight", 1) for d in grade.get("decisions", [])}
    failed = sum(w for m, w in weights.items() if not by_mark.get(m))
    md = adir / f"{stem}.md"
    meta = adir / f"{stem}.meta.json"
    chars = len(md.read_text("utf-8")) if md.exists() else -1
    calls = -1
    if meta.exists():
        calls = json.loads(meta.read_text("utf-8")).get("tool_calls", -1)
    return grade["score"] * 100, chars, calls, failed, sum(weights.values())

Activity · 13 steps
lines 96–96grade = json.loads((adir / f"{stem}.grade.json").read_text("utf-8"))lines 97–97by_mark: dict[str, bool] = {}lines 98–98◇ for d in grade.get("decisions", [])lines 99–99by_mark[d["mark"]] = by_mark.get(d["mark"], False) or bool(d.get("hit"))lines 100–100weights = {d["mark"]: d.get("weight", 1) for d in grade.get("decisions", [])}lines 101–101failed = sum(w for m, w in weights.items() if not by_mark.get(m))lines 102–102md = adir / f"{stem}.md"lines 103–103meta = adir / f"{stem}.meta.json"lines 104–104chars = len(md.read_text("utf-8")) if md.exists() else -1lines 105–105calls = -1lines 106–106◇ if meta.exists()lines 107–107calls = json.loads(meta.read_text("utf-8")).get("tool_calls", -1)lines 108–108return grade["score"] * 100, chars, calls, failed, sum(weights.values())

Flows

main

int cluster_review.main(list[str] argv)

Dispatch a subcommand.

scripts/cluster_review.py:241

Show on the map →

Called by none

Calls rank, trace

Source · 13 lines
def main(argv: list[str]) -> int:
    """@brief Route `rank` / `trace`.
    @return The subcommand's status, or 1 on a usage error.
    @version 1
    """
    if len(argv) >= 2 and argv[0] == "rank":
        return rank(Path(argv[1]))
    if len(argv) >= 4 and argv[0] == "trace":
        return trace(Path(argv[1]), argv[2], argv[3])
    print(__doc__)
    return 1

Activity · 6 steps
lines 246–246◇ if len(argv) >= 2 and argv[0] == "rank"lines 247–247return rank(Path(argv[1]))lines 248–248◇ if len(argv) >= 4 and argv[0] == "trace"lines 249–249return trace(Path(argv[1]), argv[2], argv[3])lines 250–250print(__doc__)lines 251–251return 1

Flows

rank

int cluster_review.rank(Path run)

Rank every cluster by the primary arm's gap against baseline.

scripts/cluster_review.py:116

Show on the map →

Called by main, test_a_run_with_nothing_to_pair_refuses, test_an_unpaired_cluster_is_named_rather_than_ranked, test_the_ranking_is_by_gap_and_not_by_raw_score

Calls cell_shape, targets_of

Source · 72 lines
def rank(run: Path) -> int:
    """STEP 1 OF THE PROCEDURE, with the paired shape beside it. See the module docstring for why
    the pairing is the point rather than a decoration.

    A cluster with no baseline arm is SKIPPED AND NAMED, not ranked against nothing: a gap needs
    both halves, and ranking a one-armed cluster at its raw score is the "cluster every arm fails"
    error the step exists to avoid.

    @brief Print the gap-ranked cluster table.
    @return 0, or 2 when no cluster could be paired.
    @version 1
    """
    shapes: dict[tuple[str, str, str], list[tuple[float, int, int, int, int]]] = defaultdict(list)
    for target in targets_of(run):
        adir = run / target / "answers"
        for grade in sorted(adir.glob("*.grade.json")):
            stem = grade.name[: -len(".grade.json")]
            m = CELL.match(stem)
            if not m:
                continue
            q, _model, arm, _rep = m.groups()
            shapes[(target, q, arm)].append(cell_shape(adir, stem))

    rows = []
    unpaired = []
    for (target, q, arm), vals in shapes.items():
        if arm != PRIMARY_ARM:
            continue
        base = shapes.get((target, q, "baseline"))
        if not base:
            unpaired.append(f"{target} {q}")
            continue
        mean = lambda vs, i: statistics.mean(v[i] for v in vs)  # noqa: E731
        rows.append(
            (
                mean(vals, 0) - mean(base, 0),
                target,
                q,
                mean(vals, 0),
                mean(base, 0),
                mean(vals, 2),
                mean(base, 2),
                mean(vals, 1),
                mean(base, 1),
                mean(vals, 3),
                mean(vals, 4),
            )
        )
    if not rows:
        print(f"no cluster in {run} has both {PRIMARY_ARM} and baseline cells")
        return 2
    rows.sort()
    print(f"run: {run}   primary arm: {PRIMARY_ARM}   clusters: {len(rows)}\n")
    print(
        f"{'gap':>7}  {'cluster':<14} {'score':>12}  {'tool calls':>12}  "
        f"{'answer chars':>14}  {'failed wt':>10}"
    )
    print(f"{'':>7}  {'':<14} {'idx':>5}{'base':>7}  {'idx':>5}{'base':>7}  {'idx':>6}{'base':>8}")
    for gap, target, q, io, b0, ic, bc, ich, bch, fw, tw in rows:
        print(
            f"{gap:+7.2f}  {target + ' ' + q:<14} {io:5.1f}{b0:7.1f}  "
            f"{ic:5.1f}{bc:7.1f}  {ich:6.0f}{bch:8.0f}  {fw:4.0f}/{tw:<5.0f}"
        )
    ## NAMED, NOT SUMMARISED. A cluster left out of a ranking is a cluster the review did not
    ## cover, and "25 clusters ranked" beside a silent omission is the flattering reading.
    if unpaired:
        print(f"\nunpaired (no baseline arm, NOT ranked): {len(unpaired)}")
        for name in unpaired:
            print(f"  {name}")
    return 0

Activity · 35 steps
lines 128–128shapes: dict[tuple[str, str, str], list[tuple[float, int, int, int, int]]] = defaultdict(list)lines 129–129◇ for target in targets_of(run)lines 130–130adir = run / target / "answers"lines 131–131◇ for grade in sorted(adir.glob("*.grade.json"))lines 132–132stem = grade.name[: -len(".grade.json")]lines 133–133m = CELL.match(stem)lines 134–134◇ if not mlines 135–135continuelines 136–136q, _model, arm, _rep = m.groups()lines 137–137shapes[(target, q, arm)].append(cell_shape(adir, stem))lines 139–139rows = []lines 140–140unpaired = []lines 141–141◇ for (target, q, arm), vals in shapes.items()lines 142–142◇ if arm != PRIMARY_ARMlines 143–143continuelines 144–144base = shapes.get((target, q, "baseline"))lines 145–145◇ if not baselines 146–146unpaired.append(f"{target} {q}")lines 147–147continuelines 148–148mean = lambda vs, i: statistics.mean(v[i] for v in vs)lines 149–163rows.append( ( mean(vals, 0) - mean(base, 0), target, q, mean(vals, 0), mean(base, 0), mean(vals, 2), mean(base, 2), mean(vals, 1), mean(base, 1), mean(vals, 3), mean(vals, 4), ) )lines 164–164◇ if not rowslines 165–165print(f"no cluster in {run} has both {PRIMARY_ARM} and baseline cells")lines 166–166return 2lines 167–167rows.sort()lines 168–168print(f"run: {run} primary arm: {PRIMARY_ARM} clusters: {len(rows)}\n")lines 169–172print( f"{'gap':>7} {'cluster':<14} {'score':>12} {'tool calls':>12} " f"{'answer chars':>14} {'failed wt':>10}" )lines 173–173print(f"{'':>7} {'':<14} {'idx':>5}{'base':>7} {'idx':>5}{'base':>7} {'idx':>6}{'base':>8}")lines 174–174◇ for gap, target, q, io, b0, ic, bc, ich, bch, fw, tw in rowslines 175–178print( f"{gap:+7.2f} {target + ' ' + q:<14} {io:5.1f}{b0:7.1f} " f"{ic:5.1f}{bc:7.1f} {ich:6.0f}{bch:8.0f} {fw:4.0f}/{tw:<5.0f}" )lines 181–181◇ if unpairedlines 182–182print(f"\nunpaired (no baseline arm, NOT ranked): {len(unpaired)}")lines 183–183◇ for name in unpairedlines 184–184print(f" {name}")lines 185–185return 0

Flows

targets_of

list[str] cluster_review.targets_of(Path run)

Every target directory of a run that holds answers.

scripts/cluster_review.py:70

Show on the map →

Called by rank

Calls none

Source · 8 lines
def targets_of(run: Path) -> list[str]:
    """@brief List a run's answer-bearing targets.
    @return The target names.
    @version 1
    """
    return sorted(p.name for p in run.iterdir() if (p / "answers").is_dir())

Activity · 1 steps
lines 75–75return sorted(p.name for p in run.iterdir() if (p / "answers").is_dir())

Flows

trace

int cluster_review.trace(Path run, str target, str question)

Print one cluster's call-and-reply trace, per replicate.

scripts/cluster_review.py:195

Show on the map →

Called by main

Calls none

Source · 42 lines
def trace(run: Path, target: str, question: str) -> int:
    """STEP 3 OF THE PROCEDURE. Paired by `tool_use` id through `selector_waste._blocks`, so a
    transcript that repeats a row shows one call — the inflation that put 157 in a draft where
    `selector_waste.py` counts 92.

    THE REPLY IS SIZED AND FLAGGED RATHER THAN PRINTED WHOLE. A single cell's replies run to 54 KB
    and the thing a reviewer needs first is the SHAPE: which calls came back empty, and how big the
    one before the agent stopped was. Reading a specific reply in full is then a one-line jq away,
    and the trace names the transcript so it can be.

    @brief Trace one cluster's calls and replies.
    @return 0, or 2 when no transcript resolves.
    @version 1
    """
    adir = run / target / "answers"
    raws = sorted(adir.glob(f"{question}_*{PRIMARY_ARM}*.raw.json"))
    if not raws:
        print(f"no {PRIMARY_ARM} cells for {target} {question} in {run}")
        return 2
    resolved = 0
    for raw in raws:
        session = json.loads(raw.read_text("utf-8")).get("session_id")
        hits = sorted(PROJECTS.glob(f"*/{session}.jsonl")) if session else []
        stem = raw.name[: -len(".raw.json")]
        if not hits:
            ## A CULLED TRANSCRIPT IS NAMED. It is the artefact a published run does not carry,
            ## so its absence is the expected failure here and must not read as a quiet cell.
            print(f"\n=== {stem}: NO TRANSCRIPT (session {session})")
            continue
        resolved += 1
        uses, results = _blocks(hits[0])
        print(f"\n=== {stem}   calls={len(uses)}   transcript={hits[0].name}")
        for call_id, block in uses.items():
            name = str(block.get("name") or "").replace("mcp__clew__", "")
            args = json.dumps(block.get("input") or {})
            reply = results.get(call_id, "")
            miss = '"found": false' in reply or '"found":false' in reply
            print(f"  CALL  {name}({args[:150]})")
            print(f"  REPLY {len(reply):>7} bytes  {'MISS' if miss else 'hit'}")
    return 0 if resolved else 2

Activity · 24 steps
lines 209–209adir = run / target / "answers"lines 210–210raws = sorted(adir.glob(f"{question}_*{PRIMARY_ARM}*.raw.json"))lines 211–211◇ if not rawslines 212–212print(f"no {PRIMARY_ARM} cells for {target} {question} in {run}")lines 213–213return 2lines 214–214resolved = 0lines 215–215◇ for raw in rawslines 216–216session = json.loads(raw.read_text("utf-8")).get("session_id")lines 217–217hits = sorted(PROJECTS.glob(f"*/{session}.jsonl")) if session else []lines 218–218stem = raw.name[: -len(".raw.json")]lines 219–219◇ if not hitslines 222–222print(f"\n=== {stem}: NO TRANSCRIPT (session {session})")lines 223–223continuelines 224–224resolved += 1lines 225–225uses, results = _blocks(hits[0])lines 226–226print(f"\n=== {stem} calls={len(uses)} transcript={hits[0].name}")lines 227–227◇ for call_id, block in uses.items()lines 228–228name = str(block.get("name") or "").replace("mcp__clew__", "")lines 229–229args = json.dumps(block.get("input") or {})lines 230–230reply = results.get(call_id, "")lines 231–231miss = '"found": false' in reply or '"found":false' in replylines 232–232print(f" CALL {name}({args[:150]})")lines 233–233print(f" REPLY {len(reply):>7} bytes {'MISS' if miss else 'hit'}")lines 234–234return 0 if resolved else 2

Flows