Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| df8c20d4e6 | |||
| 8e8128f56f | |||
| e66df83a3a | |||
| c082bfe6ca | |||
| fea9dde5b6 | |||
| 0490233e24 | |||
| 6494a4bee6 | |||
| 2b86540183 | |||
| d282a90804 | |||
| fbd2e62e41 | |||
| babe339430 | |||
| f0ff379251 | |||
| 0c93614f4a | |||
| 0b77d12cb2 | |||
| 4ab3648cb4 | |||
| 50b18efc05 | |||
| 8e64d30fd8 | |||
| 690a7d4454 | |||
| ed72e284ca | |||
| 134a200fba | |||
| 717ee9e24e | |||
| 193ea2bb55 | |||
| 4a0de10690 | |||
| e1651179ee | |||
| 7ddcf4fe5a | |||
| c042551aaf | |||
| 064ce09dcc | |||
| d18ceec249 | |||
| 1a5cf15a60 | |||
| ff354a90a8 | |||
| 98653923ed | |||
| 7823c4374c | |||
| c424fa66ae | |||
| 62d57344d8 | |||
| 9d4d7ddc94 | |||
| af589aea9a | |||
| df510e967f | |||
| 4172e4024f | |||
| 767ebad8c9 | |||
| 90727721ea | |||
| 86e6c50195 | |||
| ed7f3eb949 | |||
| 2321f4930d | |||
| e2aca90c9c | |||
| b948064511 | |||
| f134c6dede | |||
| 0bdea65030 | |||
| 10dd5fb527 | |||
| db993f159e | |||
| 51f5f3be29 | |||
| f6e96da675 | |||
| 29b986ca42 |
@@ -7,6 +7,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
- deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
|
||||
- deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's
|
||||
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
|
||||
- loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- This setup's own plan now ranks items by `Score = 100 * V / (2**S + 32)`, up from 8: F, a chunk's fixed cost, is 32, about one size-5 change, fitted to ten finished chunks' tokens, so small items rank lower against large ones. `docs/decisions.md` holds the fit.
|
||||
- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. The two markdown files hold what they held before. From them, loop-claude now reads only a `Reset` line in `routing-calls-raised.md`, which still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once. If the figures still make a call raised since the latest reset, it puts that call to you once more.
|
||||
- `loop-claude` and the routing figures no longer read a `Worker:` line written as a sentence, as versions before 0.4.0 archived. A rerun routes a chunk whose archive still ends in one afresh, and the figures leave it out of the routed chunks and charge its dollars to a row named by the sentence.
|
||||
|
||||
## 0.6.0
|
||||
|
||||
- `deploy-release --cut`, run in `~/code/claude-config`, now cuts a release. Once the next release holds no item in `todo.md` and its release review has landed, it renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request: it opens the pull request, waits for its checks and merges it fast-forward only. Then it tags the merged commit, pushes the tag and moves `~/.claude` to it. Where a step fails it stops with git's or the forge's reason, and a rerun continues. Nobody can push to `main` on the remote any more, so the old manual steps under README → Release no longer work. Cut 0.6.0 itself from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0.
|
||||
- The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none.
|
||||
- In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut.
|
||||
- `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file.
|
||||
|
||||
@@ -81,14 +81,20 @@ It refuses while a file `~/.claude` tracks has an uncommitted change, such as a
|
||||
|
||||
## Release
|
||||
|
||||
In `~/code/claude-config`, rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit `v<version>`, and push both. Then run `bin/deploy-release` there, which moves this machine's `~/.claude` to the release: the cut isn't done until it has. Each other machine takes the release with Update.
|
||||
Once the next release holds no item in `todo.md` and its release review has landed, cut it from `~/code/claude-config`:
|
||||
|
||||
```sh
|
||||
bin/deploy-release --cut
|
||||
```
|
||||
|
||||
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
|
||||
|
||||
## Tools
|
||||
|
||||
Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`.
|
||||
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `deploy-release [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says.
|
||||
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
@@ -122,6 +128,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. The non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool.
|
||||
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
|
||||
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_standing.py`, which says whether the next release is ready to cut.
|
||||
- `judge_replay` imports `loop_claude`'s judge.
|
||||
- `larv_review` imports `rank_todo.py`'s ranking.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
|
||||
@@ -21,8 +21,8 @@ MID = "Mid A"
|
||||
PLACE = re.compile(r"`([^`\s]*):\d+`(?: `(\w+)`)?")
|
||||
RESTRUCTURE_FIRST = "would restructure first"
|
||||
RULING = re.compile(r"^Ruling: (better|same|worse)$", re.M)
|
||||
RULED_PLACES = re.compile(rf"^.+, {DECIDED_BY}:$")
|
||||
SCORED_PLACES = re.compile(rf"^.+, ({HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
|
||||
# A seat's label over its bullets: its name, then the listing's kind.
|
||||
LABEL = re.compile(rf"^(.+), ({DECIDED_BY}|{HARDEST_FIRST}|{RESTRUCTURE_FIRST}):$")
|
||||
SENIOR = "Maintainability senior"
|
||||
TITLE = "# Comprehension history\n"
|
||||
|
||||
@@ -40,22 +40,52 @@ class Place:
|
||||
name: str | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listing:
|
||||
"""The bullets a seat lists under one label of an entry, each with its indented continuation lines. `kind` is what the label ends in: DECIDED_BY, HARDEST_FIRST or RESTRUCTURE_FIRST."""
|
||||
label: str
|
||||
seat: str
|
||||
kind: str
|
||||
bullets: list[str]
|
||||
|
||||
@property
|
||||
def places(self) -> list[Place]:
|
||||
"""The places on the first line of each bullet."""
|
||||
return [place for bullet in self.bullets for place in bullet_places(bullet.splitlines()[0])]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Entry:
|
||||
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither. The places under a scoring seat's label are scored_places; a ruling recorded before PR #255 may hold them too."""
|
||||
"""One paired ruling, which names the commit it was against and its ruling, or one scoring run, which names neither.
|
||||
|
||||
`score_rows` holds the rows of the table with a Mean row, and `vote_rows` those of any other table: each row's cells after the first, keyed by the first, without the header. `ruled_listings` holds the decided-by listings, and `scored_listings` the hardest-first and would-restructure-first ones."""
|
||||
heading: str
|
||||
time: str
|
||||
commit: str
|
||||
against: str | None
|
||||
ruling: str | None
|
||||
ruled_places: list[Place]
|
||||
scored_places: list[Place]
|
||||
body: str
|
||||
vote_rows: dict[str, list[str]]
|
||||
score_rows: dict[str, list[str]]
|
||||
ruled_listings: list[Listing]
|
||||
scored_listings: list[Listing]
|
||||
|
||||
@property
|
||||
def paired(self) -> bool:
|
||||
return self.against is not None
|
||||
|
||||
@property
|
||||
def scored(self) -> bool:
|
||||
"""Whether the entry scores the project: a scoring run, or a ruling that lists scoring seats' places, as a ruling from before PR #255 may, beside their table."""
|
||||
return not self.paired or bool(self.scored_places)
|
||||
|
||||
@property
|
||||
def ruled_places(self) -> list[Place]:
|
||||
return [place for listing in self.ruled_listings for place in listing.places]
|
||||
|
||||
@property
|
||||
def scored_places(self) -> list[Place]:
|
||||
return [place for listing in self.scored_listings for place in listing.places]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HistoryChange:
|
||||
@@ -101,25 +131,33 @@ def entries(history: str) -> list[Entry]:
|
||||
if named := HEADING.match(heading):
|
||||
body = "\n".join(bodies)
|
||||
ruling = RULING.search(body)
|
||||
found.append(Entry(heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None, seat_places(body, RULED_PLACES), seat_places(body, SCORED_PLACES), body))
|
||||
tables = table_rows(body)
|
||||
listed = listings(body)
|
||||
found.append(Entry(
|
||||
heading, named.group(1), named.group(3), named.group(4), ruling.group(1) if ruling else None,
|
||||
vote_rows={name: cells for table in tables if MEAN not in table for name, cells in table.items()},
|
||||
score_rows={name: cells for table in tables if MEAN in table for name, cells in table.items()},
|
||||
ruled_listings=[listing for listing in listed if listing.kind == DECIDED_BY],
|
||||
scored_listings=[listing for listing in listed if listing.kind != DECIDED_BY],
|
||||
))
|
||||
return found
|
||||
|
||||
|
||||
def latest_places(history: str) -> str | None:
|
||||
"""The places seats found hard since the newest scored commit, under each entry's heading, oldest first; None when no place counts.
|
||||
|
||||
They start at the first of newest_scored's entries, so a rerun of one head adds to the run before it. Where no entry counts as scoring the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
|
||||
They start at the first entry that scores that commit, so a rerun of one head adds to the run before it. Where no entry scores the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
|
||||
found = by_time(entries(history))
|
||||
newest = newest_scored(found)
|
||||
newest = newest_commit_runs(found)
|
||||
start = found.index(newest[0]) if newest else 0
|
||||
parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[start:]]
|
||||
parts = [placed(entry, worse_places(entry) + entry.scored_listings) for entry in found[start:]]
|
||||
return "\n".join(part for part in parts if part) or None
|
||||
|
||||
|
||||
def latest_overall(history: str) -> decimal.Decimal | Failure | None:
|
||||
"""The mean of the overall means of newest_scored's entries, since a rerun of one head measures it again; None where no entry counts as scoring the project."""
|
||||
"""The mean of the overall means of the entries that score the newest scored commit, since a rerun of one head measures it again; None where no entry scores the project."""
|
||||
overalls = []
|
||||
for entry in newest_scored(by_time(entries(history))):
|
||||
for entry in newest_commit_runs(by_time(entries(history))):
|
||||
overall = run_overall(entry)
|
||||
if isinstance(overall, Failure):
|
||||
return overall
|
||||
@@ -127,65 +165,65 @@ def latest_overall(history: str) -> decimal.Decimal | Failure | None:
|
||||
return sum(overalls, decimal.Decimal(0)) / len(overalls) if overalls else None
|
||||
|
||||
|
||||
def newest_scored(found: list[Entry]) -> list[Entry]:
|
||||
"""In found's order, the entries that count as scoring the project on the newest scored commit, the commit of the last such entry; empty where none counts. A commit matches by prefix, since a heading may write it at any length from 7 characters."""
|
||||
scoring = [entry for entry in found if scored(entry)]
|
||||
return [entry for entry in scoring if entry.commit.startswith(scoring[-1].commit) or scoring[-1].commit.startswith(entry.commit)] if scoring else []
|
||||
def newest_commit_runs(found: list[Entry]) -> list[Entry]:
|
||||
"""The entries that score the commit of the last entry that scores the project, in found's order; empty where none does. Commits match by prefix, since a heading may write one at any length from 7 characters."""
|
||||
scored = [entry for entry in found if entry.scored]
|
||||
if not scored:
|
||||
return []
|
||||
newest = scored[-1].commit
|
||||
return [entry for entry in scored if entry.commit.startswith(newest) or newest.startswith(entry.commit)]
|
||||
|
||||
|
||||
def run_overall(run: Entry) -> decimal.Decimal | Failure:
|
||||
"""The overall cell of the Mean row of an entry that counts as scoring the project."""
|
||||
"""The overall cell of the Mean row of an entry that scores the project."""
|
||||
try:
|
||||
overall = decimal.Decimal(overall_cells(run).get(MEAN, ""))
|
||||
overall = decimal.Decimal(last_cells(run.score_rows).get(MEAN, ""))
|
||||
except decimal.InvalidOperation:
|
||||
overall = None
|
||||
return overall if overall is not None and overall.is_finite() else Failure(f"{HISTORY}'s scoring run {run.heading} has no Mean row ending in its overall, which sets code health's weight")
|
||||
|
||||
|
||||
def overall_cells(entry: Entry) -> dict[str, str]:
|
||||
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score, or the Mean row's, in a scoring table."""
|
||||
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
|
||||
|
||||
|
||||
def scoring_runs(found: list[Entry]) -> list[Entry]:
|
||||
"""The scoring runs among the entries, oldest first. Unlike scored, it leaves out a ruling from before PR #255 that holds scoring seats' places: there overall_cells reads each voting seat's vote, not its score."""
|
||||
return [entry for entry in by_time(found) if not entry.paired]
|
||||
def last_cells(rows: dict[str, list[str]]) -> dict[str, str]:
|
||||
"""Each row's last cell, by its first cell, leaving out a row whose last cell is empty: a seat's overall vote in an entry's `vote_rows`, or its overall score, or the Mean row's, in its `score_rows`."""
|
||||
return {name: cells[-1] for name, cells in rows.items() if cells and cells[-1]}
|
||||
|
||||
|
||||
def by_time(found: list[Entry]) -> list[Entry]:
|
||||
return sorted(found, key=lambda entry: entry.time)
|
||||
|
||||
|
||||
def scored(entry: Entry) -> bool:
|
||||
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
|
||||
return not entry.paired or bool(entry.scored_places)
|
||||
def worse_places(entry: Entry) -> list[Listing]:
|
||||
"""Each of a ruling's decided-by listings, cut to the bullets that open with a dimension its seat's vote counted as worse."""
|
||||
cut = []
|
||||
for listing in entry.ruled_listings:
|
||||
worse = worse_dimensions(entry.vote_rows.get(listing.seat, []))
|
||||
kept = [bullet for bullet in listing.bullets if worse.intersection(place_dimensions(bullet.removeprefix("- ")))]
|
||||
cut.append(dataclasses.replace(listing, bullets=kept))
|
||||
return cut
|
||||
|
||||
|
||||
def worse_places(entry: Entry) -> list[tuple[str, list[str]]]:
|
||||
"""Under each of a ruling's seat labels, the bullets that open with a dimension that seat's vote counted as worse; Overall counts as one."""
|
||||
worse = worse_votes(entry.body)
|
||||
return [(label, [bullet for bullet in bullets if worse.get(label.split(",")[0], set()) & set(place_dimensions(bullet.removeprefix("- ")))]) for label, bullets in labelled_bullets(entry.body, RULED_PLACES)]
|
||||
|
||||
|
||||
def placed(entry: Entry, labelled: list[tuple[str, list[str]]]) -> str:
|
||||
"""The entry's heading, then each label with bullets and its bullets; empty when no label has any."""
|
||||
text = "".join(f"\n{label}\n\n" + "".join(f"{bullet}\n" for bullet in bullets) for label, bullets in labelled if bullets)
|
||||
def placed(entry: Entry, listed: list[Listing]) -> str:
|
||||
"""The entry's heading, then the label and bullets of each listing that has bullets; empty when none has."""
|
||||
text = "".join(f"\n{listing.label}\n\n" + "".join(f"{bullet}\n" for bullet in listing.bullets) for listing in listed if listing.bullets)
|
||||
return f"## {entry.heading}\n{text}" if text else ""
|
||||
|
||||
|
||||
def worse_votes(body: str) -> dict[str, set[str]]:
|
||||
"""Each seat's dimensions, Overall included, whose vote in the ruling's table counted as worse; `same (voted worse, …)` counted as same. The votes table comes first, so a seat's row in a later scores table is not its vote."""
|
||||
return {name: {dimension for dimension, vote in zip(DIMENSIONS, cells) if vote == "worse"} for name, cells in table_rows(body).items() if len(cells) == len(DIMENSIONS)}
|
||||
def worse_dimensions(votes: list[str]) -> set[str]:
|
||||
"""The dimensions, Overall included, that a seat's row of votes counted as worse; `same (voted worse, …)` counts as same. A row without one vote per dimension, such as the older single `Vote` table's, gives an empty set."""
|
||||
return {dimension for dimension, vote in zip(DIMENSIONS, votes) if vote == "worse"} if len(votes) == len(DIMENSIONS) else set()
|
||||
|
||||
|
||||
def table_rows(body: str) -> dict[str, list[str]]:
|
||||
"""Each table row's cells after its first, keyed by that first cell; where rows share a first cell, the first row wins. Header and Mean rows are included."""
|
||||
found: dict[str, list[str]] = {}
|
||||
for line in body.splitlines():
|
||||
if line.startswith("| "):
|
||||
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
|
||||
found.setdefault(name, cells)
|
||||
return found
|
||||
def table_rows(body: str) -> list[dict[str, list[str]]]:
|
||||
"""Each table's rows after its header and separator, the cells after the first keyed by the first cell. Tables may touch, so a table starts at the row above a separator."""
|
||||
lines = [line for line in body.splitlines() if line.startswith("|")]
|
||||
separators = [index for index, line in enumerate(lines) if line.startswith("|-")]
|
||||
ends = [*(index - 1 for index in separators[1:]), len(lines)]
|
||||
return [dict(row_cells(line) for line in lines[separator + 1:end]) for separator, end in zip(separators, ends)]
|
||||
|
||||
|
||||
def row_cells(line: str) -> tuple[str, list[str]]:
|
||||
name, *cells = [cell.strip() for cell in line.strip("|").split("|")]
|
||||
return name, cells
|
||||
|
||||
|
||||
def place_dimensions(place: str) -> list[str]:
|
||||
@@ -199,25 +237,20 @@ def recorded(history: str, read: str) -> bool:
|
||||
return any(entry.heading.partition(", ")[2] == read for entry in entries(history))
|
||||
|
||||
|
||||
def seat_places(body: str, labels: re.Pattern[str]) -> list[Place]:
|
||||
"""The places on the first line of each bullet under a seat label the pattern `labels` matches."""
|
||||
return [place for _, bullets in labelled_bullets(body, labels) for bullet in bullets for place in bullet_places(bullet.splitlines()[0])]
|
||||
|
||||
|
||||
def labelled_bullets(body: str, labels: re.Pattern[str]) -> list[tuple[str, list[str]]]:
|
||||
"""Each seat label the pattern `labels` matches, with its bullets, each with its indented continuation lines."""
|
||||
found: list[tuple[str, list[str]]] = []
|
||||
listing = False
|
||||
def listings(body: str) -> list[Listing]:
|
||||
"""Each seat label in the body, with its bullets, each with its indented continuation lines."""
|
||||
found: list[Listing] = []
|
||||
under_label = False
|
||||
for line in body.splitlines():
|
||||
if labels.match(line):
|
||||
found.append((line, []))
|
||||
listing = True
|
||||
elif listing and line.startswith("- "):
|
||||
found[-1][1].append(line)
|
||||
elif listing and line.startswith(" ") and found[-1][1]:
|
||||
found[-1][1][-1] += f"\n{line}"
|
||||
if label := LABEL.match(line):
|
||||
found.append(Listing(line, label.group(1), label.group(2), []))
|
||||
under_label = True
|
||||
elif under_label and line.startswith("- "):
|
||||
found[-1].bullets.append(line)
|
||||
elif under_label and line.startswith(" ") and found[-1].bullets:
|
||||
found[-1].bullets[-1] += f"\n{line}"
|
||||
elif not line.startswith(" "):
|
||||
listing = False
|
||||
under_label = False
|
||||
return found
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
"""`deploy-release --cut`: cut the next release once it is ready, through a pull request, then tag it and move ~/.claude to it.
|
||||
|
||||
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned
|
||||
from git_repo import default_ref, git
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from deploy_release import forge
|
||||
from chunk_preflight.choices import forge_of
|
||||
from todo_table import items
|
||||
from release import newest_tag, Release, version
|
||||
|
||||
|
||||
def cut(clone: str, checkout: str) -> str | Failure:
|
||||
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
|
||||
if isinstance(same := same_origin(clone, checkout), Failure):
|
||||
return same
|
||||
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
|
||||
return fetched
|
||||
if isinstance(dropped := drop_unpushed_cut_tags(clone), Failure):
|
||||
return dropped
|
||||
ref = default_ref(cwd=clone)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
release = ready_release(clone, ref)
|
||||
if isinstance(release, Failure):
|
||||
return release
|
||||
named = version(release)
|
||||
title, tag = f"Cut release {named}", f"v{named}"
|
||||
merged = commit_titled(title, ref, clone)
|
||||
if merged is None:
|
||||
landed = land(clone, ref, named, title)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
|
||||
return fetched
|
||||
merged = commit_titled(title, ref, clone)
|
||||
if merged is None:
|
||||
return Failure(f"the pull request merged, but {ref} holds no commit titled {title!r}")
|
||||
if isinstance(merged, Failure):
|
||||
return merged
|
||||
if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure):
|
||||
return made
|
||||
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
|
||||
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
|
||||
git("tag", "--delete", tag, cwd=clone)
|
||||
return pushed
|
||||
moved = deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
|
||||
return f"Cut {tag}.\n\n{moved}"
|
||||
|
||||
|
||||
def drop_unpushed_cut_tags(clone: str) -> Failure | None:
|
||||
"""Delete each v* tag the clone holds but origin doesn't, where it tags a commit titled `Cut release <its version>`: one a run made and never pushed, such as a run that died between the two. The clone reads cut releases from its own tags, so such a tag would read as a cut nobody published."""
|
||||
local = git("tag", "--list", "v*", "--format=%(refname:short) %(*subject)", cwd=clone)
|
||||
remote = git("ls-remote", "--tags", "--refs", "origin", "refs/tags/v*", cwd=clone)
|
||||
if isinstance(local, Failure):
|
||||
return local
|
||||
if isinstance(remote, Failure):
|
||||
return remote
|
||||
pushed = {line.split("refs/tags/", 1)[-1] for line in remote.splitlines()}
|
||||
for line in local.splitlines():
|
||||
tag, _, subject = line.partition(" ")
|
||||
if tag not in pushed and subject == f"Cut release {tag.removeprefix('v')}":
|
||||
if isinstance(deleted := git("tag", "--delete", tag, cwd=clone), Failure):
|
||||
return deleted
|
||||
return None
|
||||
|
||||
|
||||
def same_origin(clone: str, checkout: str) -> Failure | None:
|
||||
"""A Failure unless clone is a clone of the origin checkout takes its releases from, so --cut never cuts another project."""
|
||||
urls = [git("ls-remote", "--get-url", "origin", cwd=where) for where in (clone, checkout)]
|
||||
failed = next((url for url in urls if isinstance(url, Failure)), None)
|
||||
if failed is not None:
|
||||
return failed
|
||||
if urls[0] != urls[1]:
|
||||
return Failure(f"run --cut in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}")
|
||||
return None
|
||||
|
||||
|
||||
def ready_release(clone: str, ref: str) -> Release | Failure:
|
||||
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
|
||||
plan = default_plan(clone, ref)
|
||||
found = items(plan.todo) if isinstance(plan.todo, str) else plan.todo
|
||||
if isinstance(found, Failure):
|
||||
return Failure(f"todo.md on {ref} cannot be read: {found.reason}")
|
||||
match chunk_item(found, plan.cut):
|
||||
case ReadyToCut(release=release) if release is not None:
|
||||
return release
|
||||
case ReadyToCut():
|
||||
return Failure("todo.md names no release after the last one cut")
|
||||
case Next(release=release) if release is not None:
|
||||
return Failure(f"release {version(release)} still holds items in todo.md")
|
||||
case ReviewDue(release=release):
|
||||
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
|
||||
case Unplanned():
|
||||
return Failure("every change is released already: nothing has landed since the last release cut")
|
||||
case Cut(release=release):
|
||||
return Failure(f"todo.md files items under {version(release)}, which is cut already")
|
||||
case _:
|
||||
return Failure("cannot tell which release is next")
|
||||
|
||||
|
||||
def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
|
||||
"""The commit titled title on ref, after the newest tag; None where there is none."""
|
||||
tag = newest_tag(clone, merged_into=ref)
|
||||
if isinstance(tag, Failure):
|
||||
return tag
|
||||
log = git("log", "--format=%H %s", f"{tag}..{ref}" if tag else ref, cwd=clone)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
|
||||
|
||||
|
||||
def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
|
||||
"""Push the branch release-<named> with the cut commit and open its pull request, where an earlier run hasn't; then wait for its checks and merge it."""
|
||||
url = git("config", "--get", "remote.origin.url", cwd=clone)
|
||||
if isinstance(url, Failure):
|
||||
return url
|
||||
on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/")
|
||||
head = branch_head(branch, clone)
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
behind = head is not None and behind_main(branch, head, ref, clone)
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
if head is None or behind:
|
||||
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
|
||||
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure):
|
||||
return pushed
|
||||
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
number = forge.open_pull(on, branch, head, run)
|
||||
if number is None:
|
||||
if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure):
|
||||
return created
|
||||
number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
|
||||
if isinstance(number, Failure):
|
||||
return number
|
||||
print(f"deploy-release: waiting for the checks of pull request {number}", file=sys.stderr)
|
||||
if isinstance(passed := forge.checks_passed(on, number, head, run), Failure):
|
||||
return passed
|
||||
return forge.merge(on, number, head, run)
|
||||
|
||||
|
||||
def branch_head(branch: str, clone: str) -> str | None | Failure:
|
||||
"""The commit origin's branch points at; None where origin has no such branch."""
|
||||
listed = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=clone)
|
||||
return listed if isinstance(listed, Failure) else next(iter(listed.split()), None)
|
||||
|
||||
|
||||
def behind_main(branch: str, head: str, ref: str, clone: str) -> bool | Failure:
|
||||
"""Whether origin's branch, at head, lacks a commit ref holds."""
|
||||
if isinstance(fetched := git("fetch", "--quiet", "origin", f"refs/heads/{branch}", cwd=clone), Failure):
|
||||
return fetched
|
||||
return isinstance(git("merge-base", "--is-ancestor", ref, head, cwd=clone), Failure)
|
||||
|
||||
|
||||
def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, replacing: str | None) -> Failure | None:
|
||||
"""Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own so the clone's checkout stays as it is, and push it as branch: a new one, or in place of replacing, the commit origin's branch points at."""
|
||||
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "cut"
|
||||
try:
|
||||
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
|
||||
return added
|
||||
changelog = worktree / "CHANGELOG.md"
|
||||
renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE)
|
||||
if not count:
|
||||
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
|
||||
changelog.write_text(renamed)
|
||||
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
|
||||
return committed
|
||||
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
|
||||
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
|
||||
return pushed if isinstance(pushed, Failure) else None
|
||||
finally:
|
||||
git("worktree", "remove", "--force", str(worktree), cwd=clone)
|
||||
shutil.rmtree(worktree.parent, ignore_errors=True)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Move a checkout to this repo's newest release, as a bare `deploy-release` does."""
|
||||
from failure import Failure
|
||||
from git_repo import git
|
||||
from release import newest_tag, parsed, tagged
|
||||
from markdown_text import sections
|
||||
|
||||
|
||||
def deploy(checkout: str) -> str | Failure:
|
||||
"""What the move of checkout to the newest release did, as the tool prints it; a Failure where it refused or git failed."""
|
||||
fetched = git("fetch", "--quiet", "--tags", "origin", cwd=checkout)
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
tag = newest_tag(checkout)
|
||||
if isinstance(tag, Failure):
|
||||
return tag
|
||||
if tag is None:
|
||||
return Failure("origin has no v* tag to move to")
|
||||
# Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged.
|
||||
if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=checkout), Failure):
|
||||
return refreshed
|
||||
changed = git("diff", "--name-only", "HEAD", cwd=checkout)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
unreleased = git("diff", "--name-only", tag, "--", *changed.split(), cwd=checkout) if changed.split() else ""
|
||||
if isinstance(unreleased, Failure):
|
||||
return unreleased
|
||||
if unreleased.split():
|
||||
return Failure(f"{checkout} has uncommitted changes that {tag} doesn't hold, to {', '.join(unreleased.split())}: merge them through the development clone and cut a release first")
|
||||
old = git("describe", "--tags", "--abbrev=0", "--match", "v*", "HEAD", cwd=checkout)
|
||||
old_tag = None if isinstance(old, Failure) else old.strip()
|
||||
at_tag = git("describe", "--tags", "--exact-match", "--match", "v*", "HEAD", cwd=checkout)
|
||||
if not isinstance(at_tag, Failure) and at_tag.strip() == tag:
|
||||
return f"Already on {tag}, the newest release."
|
||||
if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure):
|
||||
return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first")
|
||||
settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure)
|
||||
# The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy.
|
||||
if changed.split():
|
||||
restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout)
|
||||
if isinstance(restored, Failure):
|
||||
return restored
|
||||
moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return moved
|
||||
changelog = git("show", f"{tag}:CHANGELOG.md", cwd=checkout)
|
||||
lines = [f"Moved from {old_tag or 'an untagged commit'} to {tag}."]
|
||||
if settings_changed:
|
||||
lines.append("settings.json changed: pick the model again with /model.")
|
||||
if not isinstance(changelog, Failure):
|
||||
lines += newer_sections(changelog, old_tag)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def newer_sections(changelog: str, old_tag: str | None) -> list[str]:
|
||||
"""Each `## <version>` section of changelog newer than old_tag, newest first, as it reads."""
|
||||
since = tagged(old_tag)
|
||||
found = []
|
||||
for heading, bodies in sections(changelog).items():
|
||||
named = parsed(heading)
|
||||
if named is None:
|
||||
continue
|
||||
if since is None or named > since:
|
||||
found.append(f"## {heading}\n\n" + "\n".join(bodies))
|
||||
return found
|
||||
@@ -0,0 +1,101 @@
|
||||
"""The pull request steps of a cut. They run gh where origin is on GitHub and tea elsewhere, as chunk_preflight tells the two apart.
|
||||
|
||||
Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from chunk_preflight.choices import Forge
|
||||
|
||||
# How long the cut waits between two reads of the head commit's status on Gitea.
|
||||
POLL_SECONDS = 10
|
||||
|
||||
# Runs a command in the clone: what it printed, or a Failure with its reason.
|
||||
Run = typing.Callable[[list[str]], str | Failure]
|
||||
|
||||
|
||||
def runner(cwd: str) -> Run:
|
||||
def run(command: list[str]) -> str | Failure:
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
|
||||
except OSError as failure:
|
||||
return Failure(f"{command[0]} could not start: {failure}")
|
||||
if done.returncode:
|
||||
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
|
||||
return done.stdout
|
||||
return run
|
||||
|
||||
|
||||
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
|
||||
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure."""
|
||||
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
|
||||
if isinstance(answered, Failure) or not answered.strip():
|
||||
return answered
|
||||
try:
|
||||
parsed = json.loads(answered)
|
||||
except ValueError:
|
||||
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
|
||||
if isinstance(parsed, dict) and "message" in parsed:
|
||||
return Failure(f"tea api {endpoint}: {parsed['message']}")
|
||||
return parsed
|
||||
|
||||
|
||||
def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
|
||||
"""The number of the open pull request from origin's own branch whose head is head; None where there is none."""
|
||||
if forge == "gh":
|
||||
listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"])
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
rows = [line.split("\t") for line in listed.splitlines()]
|
||||
return next((row[0] for row in rows if row[1:] == [head, "false"]), None)
|
||||
# Gitea lists at most 50 a page; a release's pull request is among the newest.
|
||||
pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50")
|
||||
if isinstance(pulls, Failure):
|
||||
return pulls
|
||||
try:
|
||||
return next((str(pull["number"]) for pull in pulls if pull["head"]["ref"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"]), None)
|
||||
except (KeyError, TypeError):
|
||||
return Failure(f"tea api listed pull requests in a shape the cut doesn't read: {str(pulls)[:200]}")
|
||||
|
||||
|
||||
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
|
||||
body = ["--body" if forge == "gh" else "--description", "Rename ## Unreleased in CHANGELOG.md to the version."]
|
||||
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
|
||||
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
|
||||
return created if isinstance(created, Failure) else None
|
||||
|
||||
|
||||
def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
|
||||
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails."""
|
||||
if forge == "gh":
|
||||
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
|
||||
if isinstance(watched, Failure) and "no checks reported" not in watched.reason:
|
||||
return watched
|
||||
return None
|
||||
while True:
|
||||
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
|
||||
if isinstance(status, Failure):
|
||||
return status
|
||||
try:
|
||||
count, state = status["total_count"], status["state"]
|
||||
except (KeyError, TypeError):
|
||||
return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}")
|
||||
# Gitea reads a commit with no status as pending, with total_count 0.
|
||||
if count == 0 or state == "success":
|
||||
return None
|
||||
if state != "pending":
|
||||
return Failure(f"a check on pull request {number} ended in {state}")
|
||||
sleep(POLL_SECONDS)
|
||||
|
||||
|
||||
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
|
||||
"""Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head."""
|
||||
if forge == "gh":
|
||||
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
|
||||
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
|
||||
else:
|
||||
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
|
||||
return merged if isinstance(merged, Failure) else None
|
||||
+30
-71
@@ -1,6 +1,6 @@
|
||||
"""Move the checkout Claude Code reads its configuration from to this repo's newest release.
|
||||
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release.
|
||||
|
||||
usage: deploy-release [<checkout>]
|
||||
usage: deploy-release [--cut] [<checkout>]
|
||||
|
||||
<checkout> defaults to ~/.claude. The tool fetches origin's tags and checks out the newest v* tag,
|
||||
detached, so the checkout holds only what a release holds. Development happens in another clone,
|
||||
@@ -12,89 +12,48 @@ clean filter keeps the model out of every commit.
|
||||
It refuses, exit 1, and leaves the checkout as it was where a file the checkout tracks has an
|
||||
uncommitted change the newest tag doesn't hold: such as a hook Claude Code wrote into settings.json.
|
||||
Merge the change through the development clone and cut a release first. A model picked with /model
|
||||
is no such change. It
|
||||
also refuses where the newest tag doesn't hold the checkout's commit, since the move would drop
|
||||
work no release holds. Untracked files, such as Claude Code's sessions and memory, stay as they are.
|
||||
is no such change. It also refuses where the newest tag doesn't hold the checkout's commit, since
|
||||
the move would drop work no release holds. Untracked files, such as Claude Code's sessions and
|
||||
memory, stay as they are.
|
||||
|
||||
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
|
||||
refuses, changing nothing, unless that release holds no item in todo.md, its release review has
|
||||
landed and changes are unreleased. The release names the version; the tool doesn't choose one.
|
||||
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
|
||||
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
|
||||
checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main.
|
||||
2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for
|
||||
its checks where there are any, and merges it fast-forward only. GitHub has no such merge, so
|
||||
there it rebase-merges the branch, which is already on top of main.
|
||||
3. It tags the merged commit v<version>, annotated `Cut release <version>`, pushes only the tag,
|
||||
then moves <checkout> to it as above.
|
||||
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
|
||||
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
|
||||
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
|
||||
move stopped, fix what it names and run a bare deploy-release.
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from deploy_release.cut import cut
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from git_repo import git
|
||||
from release import newest_tag, parsed, tagged
|
||||
from markdown_text import sections
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) > 1:
|
||||
print("deploy-release: usage: deploy-release [<checkout>]", file=sys.stderr)
|
||||
cutting = argv[:1] == ["--cut"]
|
||||
rest = argv[1:] if cutting else argv
|
||||
if len(rest) > 1 or rest[:1] and rest[0].startswith("-"):
|
||||
print("deploy-release: usage: deploy-release [--cut] [<checkout>]", file=sys.stderr)
|
||||
return 1
|
||||
checkout = argv[0] if argv else str(pathlib.Path.home() / ".claude")
|
||||
moved = deploy(checkout)
|
||||
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
|
||||
moved = cut(os.getcwd(), checkout) if cutting else deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
print(f"deploy-release: {moved.reason}", file=sys.stderr)
|
||||
return 1
|
||||
print(moved)
|
||||
return 0
|
||||
|
||||
|
||||
def deploy(checkout: str) -> str | Failure:
|
||||
"""What the move of checkout to the newest release did, as the tool prints it; a Failure where it refused or git failed."""
|
||||
fetched = git("fetch", "--quiet", "--tags", "origin", cwd=checkout)
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
tag = newest_tag(checkout)
|
||||
if isinstance(tag, Failure):
|
||||
return tag
|
||||
if tag is None:
|
||||
return Failure("origin has no v* tag to move to")
|
||||
# Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged.
|
||||
if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=checkout), Failure):
|
||||
return refreshed
|
||||
changed = git("diff", "--name-only", "HEAD", cwd=checkout)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
unreleased = git("diff", "--name-only", tag, "--", *changed.split(), cwd=checkout) if changed.split() else ""
|
||||
if isinstance(unreleased, Failure):
|
||||
return unreleased
|
||||
if unreleased.split():
|
||||
return Failure(f"{checkout} has uncommitted changes that {tag} doesn't hold, to {', '.join(unreleased.split())}: merge them through the development clone and cut a release first")
|
||||
old = git("describe", "--tags", "--abbrev=0", "--match", "v*", "HEAD", cwd=checkout)
|
||||
old_tag = None if isinstance(old, Failure) else old.strip()
|
||||
at_tag = git("describe", "--tags", "--exact-match", "--match", "v*", "HEAD", cwd=checkout)
|
||||
if not isinstance(at_tag, Failure) and at_tag.strip() == tag:
|
||||
return f"Already on {tag}, the newest release."
|
||||
if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure):
|
||||
return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first")
|
||||
settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure)
|
||||
# The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy.
|
||||
if changed.split():
|
||||
restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout)
|
||||
if isinstance(restored, Failure):
|
||||
return restored
|
||||
moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return moved
|
||||
changelog = git("show", f"{tag}:CHANGELOG.md", cwd=checkout)
|
||||
lines = [f"Moved from {old_tag or 'an untagged commit'} to {tag}."]
|
||||
if settings_changed:
|
||||
lines.append("settings.json changed: pick the model again with /model.")
|
||||
if not isinstance(changelog, Failure):
|
||||
lines += newer_sections(changelog, old_tag)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def newer_sections(changelog: str, old_tag: str | None) -> list[str]:
|
||||
"""Each `## <version>` section of changelog newer than old_tag, newest first, as it reads."""
|
||||
since = tagged(old_tag)
|
||||
found = []
|
||||
for heading, bodies in sections(changelog).items():
|
||||
named = parsed(heading)
|
||||
if named is None:
|
||||
continue
|
||||
if since is None or named > since:
|
||||
found.append(f"## {heading}\n\n" + "\n".join(bodies))
|
||||
return found
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -6,6 +8,8 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from deploy_release.forge import checks_passed, POLL_SECONDS
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
|
||||
@@ -123,5 +127,335 @@ class DeployRelease(unittest.TestCase):
|
||||
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
|
||||
|
||||
|
||||
TODO = """# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = 100 * V / (2**S + 8)`
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 3`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
"""
|
||||
ROW = "| {id} | {release} | | | **Do thing {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# A fake forge, run as tea or as gh. It keeps origin's pull requests in <temp>/forge.json. Its merge moves origin's main only by fast-forward.
|
||||
FAKE_FORGE = """#!PYTHON
|
||||
import json, pathlib, subprocess, sys
|
||||
forge, args = pathlib.Path(sys.argv[0]).name, sys.argv[1:]
|
||||
state_file = pathlib.Path(__file__).resolve().parent.parent / "forge.json"
|
||||
state = json.loads(state_file.read_text())
|
||||
state["calls"].append([forge, *args])
|
||||
def save():
|
||||
state_file.write_text(json.dumps(state))
|
||||
def git(*words):
|
||||
return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True)
|
||||
def pull(number):
|
||||
return next(found for found in state["pulls"] if str(found["number"]) == number)
|
||||
# A fork's head as given; origin's own pull request follows its branch, as a forge does.
|
||||
def sha(found):
|
||||
return found.get("sha") or git("rev-parse", "refs/heads/" + found["head"]).stdout.strip()
|
||||
def merge(number, guard):
|
||||
head = sha(pull(number))
|
||||
if state.get("refuse_merge"):
|
||||
save()
|
||||
sys.exit("Not possible to fast-forward")
|
||||
if head != guard:
|
||||
save()
|
||||
sys.exit("head commit changed")
|
||||
if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode:
|
||||
save()
|
||||
sys.exit("Not possible to fast-forward")
|
||||
git("update-ref", "refs/heads/main", head)
|
||||
pull(number)["state"] = "merged"
|
||||
opened = [found for found in state["pulls"] if found["state"] == "open"]
|
||||
if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]:
|
||||
repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"}
|
||||
print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "sha": sha(found), "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened]))
|
||||
elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]:
|
||||
for found in opened:
|
||||
if found["head"] == args[3]:
|
||||
print(f"{found['number']}\t{sha(found)}\t{str(found['fork']).lower()}")
|
||||
elif args[:2] in (["pulls", "create"], ["pr", "create"]):
|
||||
head = args[args.index("--head") + 1]
|
||||
if any(found["head"] == head and not found["fork"] for found in opened):
|
||||
save()
|
||||
sys.exit("pull request already exists for these targets")
|
||||
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"})
|
||||
elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"):
|
||||
checks = state["checks"]
|
||||
print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1}))
|
||||
elif forge == "gh" and args[:2] == ["pr", "checks"]:
|
||||
if state["checks"] == "none":
|
||||
save()
|
||||
sys.exit("no checks reported on the 'release' branch")
|
||||
if state["checks"] == "failure":
|
||||
save()
|
||||
sys.exit("lint\tfail")
|
||||
elif forge == "tea" and args[:5] == ["api", "--method", "POST", "--field", "Do=fast-forward-only"] and args[5] == "--field" and args[7].endswith("/merge"):
|
||||
try:
|
||||
merge(args[7].split("/")[-2], args[6].removeprefix("head_commit_id="))
|
||||
except SystemExit as refused:
|
||||
# Gitea answers an error with a message, and tea api exits 0 all the same.
|
||||
print(json.dumps({"message": str(refused)}))
|
||||
elif args[:2] == ["pr", "merge"] and args[3:5] == ["--rebase", "--match-head-commit"]:
|
||||
merge(args[2], args[5])
|
||||
else:
|
||||
save()
|
||||
sys.exit("unexpected call")
|
||||
save()
|
||||
""".replace("PYTHON", sys.executable)
|
||||
|
||||
|
||||
class Cut(unittest.TestCase):
|
||||
"""A development clone whose next release, 0.2.0, holds no item, has its release review landed and one change unreleased; and a ~/.claude on v0.1.0."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = pathlib.Path(os.path.realpath(tempfile.mkdtemp()))
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
||||
self.origin = self.temp / "origin.git"
|
||||
fake = self.temp / "fake-bin"
|
||||
fake.mkdir()
|
||||
for name in ("tea", "gh"):
|
||||
(fake / name).write_text(FAKE_FORGE)
|
||||
(fake / name).chmod(0o755)
|
||||
(self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n")
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}"}
|
||||
self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []})
|
||||
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
|
||||
self.clone = self.temp / "claude-config"
|
||||
self.git(self.temp, "clone", "-q", str(self.origin), str(self.clone))
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Start")
|
||||
self.git(self.clone, "tag", "-a", "v0.1.0", "-m", "Cut release 0.1.0")
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0")}, "Ship item 1")
|
||||
self.git(self.clone, "commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
|
||||
self.git(self.clone, "push", "-q", "origin", "main", "--tags")
|
||||
self.target = self.temp / "dot-claude"
|
||||
self.git(self.temp, "clone", "-q", str(self.origin), str(self.target))
|
||||
self.git(self.target, "checkout", "-q", "--detach", "v0.1.0")
|
||||
|
||||
def git(self, cwd: pathlib.Path, *args: str) -> str:
|
||||
return subprocess.run(["git", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
|
||||
|
||||
def commit(self, files: dict[str, str], title: str) -> None:
|
||||
for name, text in files.items():
|
||||
(self.clone / name).write_text(text)
|
||||
self.git(self.clone, "add", "-A")
|
||||
self.git(self.clone, "commit", "-q", "-m", title)
|
||||
|
||||
def forge_state(self, state: dict | None = None) -> dict:
|
||||
if state is not None:
|
||||
(self.temp / "forge.json").write_text(json.dumps(state))
|
||||
return json.loads((self.temp / "forge.json").read_text())
|
||||
|
||||
def set_checks(self, checks: str) -> None:
|
||||
self.forge_state({**self.forge_state(), "checks": checks})
|
||||
|
||||
def cut(self) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), "--cut", str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
||||
|
||||
def origin_git(self, *args: str) -> str:
|
||||
return self.git(self.temp, "--git-dir", str(self.origin), *args)
|
||||
|
||||
def assert_cut(self, ran: subprocess.CompletedProcess[str]) -> None:
|
||||
"""origin's main ends in the cut commit, tagged v0.2.0, and ~/.claude is on that tag."""
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0")
|
||||
changelog = self.origin_git("show", "main:CHANGELOG.md")
|
||||
self.assertIn("## 0.2.0\n\n- Second.", changelog)
|
||||
self.assertNotIn("Unreleased", changelog)
|
||||
self.assertEqual(self.origin_git("rev-parse", "v0.2.0^{commit}"), self.origin_git("rev-parse", "main"))
|
||||
self.assertEqual(self.origin_git("cat-file", "-t", "v0.2.0").strip(), "tag", "the tag is annotated")
|
||||
self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.2.0").strip(), "Cut release 0.2.0")
|
||||
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.2.0")
|
||||
|
||||
def test_cuts_the_next_release_through_a_tea_pull_request_merged_fast_forward_then_tags_and_deploys_it(self):
|
||||
head = self.git(self.clone, "rev-parse", "HEAD")
|
||||
ran = self.cut()
|
||||
self.assert_cut(ran)
|
||||
self.assertIn("v0.2.0", ran.stdout)
|
||||
calls = self.forge_state()["calls"]
|
||||
self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
|
||||
self.assertIn("Do=fast-forward-only", [word for call in calls if call[-1].endswith("/pulls/1/merge") for word in call])
|
||||
self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was")
|
||||
self.assertEqual(self.git(self.clone, "status", "--porcelain"), "")
|
||||
|
||||
def test_cuts_through_gh_on_a_github_origin(self):
|
||||
self.use_github()
|
||||
ran = self.cut()
|
||||
self.assert_cut(ran)
|
||||
calls = self.forge_state()["calls"]
|
||||
self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
|
||||
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], [call[:5] for call in calls])
|
||||
|
||||
def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self):
|
||||
self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again")
|
||||
self.git(self.clone, "push", "-q", "origin", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("0.2.0", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["pulls"], [])
|
||||
self.assertEqual(self.origin_git("branch", "--list", "release-*"), "")
|
||||
|
||||
def test_refuses_changing_nothing_until_the_release_review_has_landed(self):
|
||||
self.git(self.clone, "reset", "-q", "--hard", "HEAD~1")
|
||||
self.git(self.clone, "push", "-q", "--force", "origin", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("release review", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["pulls"], [])
|
||||
|
||||
def test_stops_on_a_failing_check_leaving_the_pull_request_and_a_rerun_continues_it(self):
|
||||
self.set_checks("failure")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("failure", ran.stderr)
|
||||
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"])
|
||||
self.assertNotEqual(self.origin_git("branch", "--list", "release-0.2.0"), "")
|
||||
self.assertEqual(self.origin_git("tag", "-l", "v0.2.0"), "")
|
||||
self.set_checks("success")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request")
|
||||
|
||||
def test_stops_with_the_forges_reason_where_it_refuses_the_merge(self):
|
||||
self.forge_state({**self.forge_state(), "refuse_merge": True})
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("Not possible to fast-forward", ran.stderr)
|
||||
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"])
|
||||
|
||||
def test_a_rerun_rebuilds_the_cut_commit_on_main_where_main_moved_past_the_branch(self):
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
self.commit({"other.md": "Later.\n"}, "Fix the check")
|
||||
self.git(self.clone, "push", "-q", "origin", "main")
|
||||
self.set_checks("success")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main~1").strip(), "Fix the check")
|
||||
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request")
|
||||
|
||||
def test_deletes_the_tag_it_made_where_its_push_fails_so_a_rerun_tags_again(self):
|
||||
hook = self.origin / "hooks" / "pre-receive"
|
||||
hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then echo 'tags are refused' >&2; exit 1; fi\n")
|
||||
hook.chmod(0o755)
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("tags are refused", ran.stderr)
|
||||
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0"), "")
|
||||
hook.unlink()
|
||||
self.assert_cut(self.cut())
|
||||
|
||||
def test_refuses_changing_nothing_where_the_clone_is_not_a_clone_of_the_checkouts_origin(self):
|
||||
self.git(self.target, "remote", "set-url", "origin", str(self.temp / "other.git"))
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("origin", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["pulls"], [])
|
||||
|
||||
def test_says_which_pull_request_it_waits_for(self):
|
||||
ran = self.cut()
|
||||
self.assertIn("pull request 1", ran.stderr)
|
||||
|
||||
def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self):
|
||||
self.git(self.clone, "switch", "-q", "-c", "side")
|
||||
self.commit({"side.md": "Side.\n"}, "Side")
|
||||
self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Wrong")
|
||||
self.git(self.clone, "push", "-q", "origin", "side", "v0.2.0")
|
||||
self.git(self.clone, "switch", "-q", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("v0.2.0", ran.stderr)
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0")
|
||||
self.git(self.clone, "tag", "-d", "v0.2.0")
|
||||
self.origin_git("tag", "-d", "v0.2.0")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request")
|
||||
|
||||
def use_github(self) -> None:
|
||||
"""Point the clone's origin at a GitHub URL that git reads as the local origin, so the cut runs gh."""
|
||||
self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git")
|
||||
self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git")
|
||||
|
||||
def assert_fork_pull_ignored(self) -> None:
|
||||
"""After a failed first run, a fork opens a pull request from its own release-0.2.0, listed first; the rerun merges only origin's."""
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0")
|
||||
self.commit({"settings.json": "{}\n"}, "Cut release 0.2.0")
|
||||
self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0")
|
||||
self.git(self.clone, "switch", "-q", "main")
|
||||
state = self.forge_state()
|
||||
fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"}
|
||||
self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"})
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"])
|
||||
self.assertNotIn("settings.json", self.origin_git("ls-tree", "--name-only", "main"))
|
||||
|
||||
def test_merges_only_origins_own_pull_request_on_tea_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
|
||||
self.assert_fork_pull_ignored()
|
||||
|
||||
def test_merges_only_origins_own_pull_request_on_gh_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
|
||||
self.use_github()
|
||||
self.assert_fork_pull_ignored()
|
||||
|
||||
def test_a_rerun_drops_a_cut_tag_an_earlier_run_made_but_never_pushed(self):
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
self.set_checks("success")
|
||||
hook = self.origin / "hooks" / "pre-receive"
|
||||
hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then exit 1; fi\n")
|
||||
hook.chmod(0o755)
|
||||
self.cut()
|
||||
# A run that died between tagging and pushing left this tag behind.
|
||||
self.git(self.clone, "fetch", "-q", "origin")
|
||||
self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Cut release 0.2.0", "origin/main")
|
||||
hook.unlink()
|
||||
self.assert_cut(self.cut())
|
||||
|
||||
def test_keeps_a_pushed_cut_tag_and_an_unpushed_tag_on_any_other_commit(self):
|
||||
self.git(self.clone, "switch", "-q", "-c", "side")
|
||||
self.commit({"side.md": "Side.\n"}, "Side")
|
||||
self.git(self.clone, "tag", "-a", "v9.9.9", "-m", "Mine")
|
||||
self.git(self.clone, "switch", "-q", "main")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
|
||||
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
|
||||
|
||||
def test_takes_no_option_but_cut(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "--cut", "--force"], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("usage", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["calls"], [])
|
||||
|
||||
def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self):
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
state = self.forge_state()
|
||||
state["pulls"][0]["sha"] = "0" * 40
|
||||
self.forge_state({**state, "checks": "success"})
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("already exists", ran.stderr)
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
|
||||
|
||||
|
||||
class ChecksPassed(unittest.TestCase):
|
||||
def test_waits_on_tea_while_a_check_is_pending(self):
|
||||
statuses = iter(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}'])
|
||||
slept = []
|
||||
self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: next(statuses), slept.append))
|
||||
self.assertEqual(slept, [POLL_SECONDS])
|
||||
|
||||
def test_takes_a_commit_with_no_status_on_tea_as_passed(self):
|
||||
self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', self.fail))
|
||||
|
||||
def test_fails_on_tea_where_a_check_failed(self):
|
||||
self.assertIsInstance(checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', self.fail), Failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -50,21 +50,21 @@ REFERENCE_EFFORT = "xhigh"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
anchor = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
cases = archived_cases(anchor.model, archive_root(home, env), home)
|
||||
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
if isinstance(project, int):
|
||||
return project
|
||||
cases = archived_cases(project.model, archive_root(home, env), home)
|
||||
if isinstance(cases, Failure):
|
||||
return failed(TOOL, cases.reason)
|
||||
if not cases:
|
||||
return failed(TOOL, f"no archived verdicts of projects on {anchor.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
return failed(TOOL, f"no archived verdicts of projects on {project.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
cases = sample(cases, PER_KIND)
|
||||
reference = Rung(anchor.model, REFERENCE_EFFORT)
|
||||
reference = Rung(project.model, REFERENCE_EFFORT)
|
||||
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
|
||||
replay = replayed(cases, reference, down_from(anchor, lowest_worker_rung(anchor)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
replay = replayed(cases, reference, down_from(project, lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(anchor.model, reference, cases, replay))
|
||||
print(report(project.model, reference, cases, replay))
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import counted_vote, entries, Entry, overall_cells, scoring_runs
|
||||
from comprehension_history import by_time, counted_vote, entries, Entry, last_cells
|
||||
from larv_review.seats import FIRST_SEATS
|
||||
|
||||
# Matches score-outcomes, which waits for 10 finished chunks before it shows a median.
|
||||
@@ -10,7 +10,7 @@ MIN_PAIRS = 10
|
||||
def ruling_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each paired ruling that holds both of the first seats' overall votes, whether they counted alike."""
|
||||
first, second = FIRST_SEATS
|
||||
cells = [overall_cells(entry) for entry in found if entry.paired]
|
||||
cells = [last_cells(entry.vote_rows) for entry in found if entry.paired]
|
||||
return [counted_vote(each[first]) == counted_vote(each[second]) for each in cells if first in each and second in each]
|
||||
|
||||
|
||||
@@ -18,9 +18,9 @@ def run_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each commit scored at least twice, whether the first two seats' overall scores moved the same way, up, down or not at all, from its first run to its second. Both runs read one tree, so the pair is the ruling those seats would make from absolute scores on code that did not change."""
|
||||
first, second = FIRST_SEATS
|
||||
runs: dict[str, list[dict[str, decimal.Decimal]]] = {}
|
||||
for entry in scoring_runs(found):
|
||||
cells = overall_cells(entry)
|
||||
if first in cells and second in cells:
|
||||
for entry in by_time(found):
|
||||
cells = last_cells(entry.score_rows)
|
||||
if entry.scored and first in cells and second in cells:
|
||||
runs.setdefault(entry.commit, []).append({first: decimal.Decimal(cells[first]), second: decimal.Decimal(cells[second])})
|
||||
pairs = [(each[0], each[1]) for each in runs.values() if len(each) >= 2]
|
||||
return [direction(before[first], after[first]) == direction(before[second], after[second]) for before, after in pairs]
|
||||
|
||||
@@ -162,6 +162,30 @@ class History(unittest.TestCase):
|
||||
fell = ruled.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 6 | 7 | 7 | 7 |\n| Mean | 7 | 6 | 7 | 7 | 7 |\n\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n"
|
||||
self.assertEqual(latest_places(appended(appended("", scored), fell)), hard_since.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n")
|
||||
|
||||
def test_takes_a_seats_vote_from_the_votes_table_when_it_comes_first(self):
|
||||
self.assert_votes_table_read(lambda votes, scores: votes + scores)
|
||||
|
||||
def test_takes_a_seats_vote_from_the_votes_table_when_it_comes_second(self):
|
||||
self.assert_votes_table_read(lambda votes, scores: scores + votes)
|
||||
|
||||
def assert_votes_table_read(self, tables):
|
||||
votes = "| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | same | same | same |\n"
|
||||
scores = "| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 7 | 7 | 7 | 7 |\n| Mean | 7 | 7 | 7 | 7 | 7 |\n"
|
||||
places = "Mid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: kept\n- Shape: `bin/f.py:2` `o`: dropped\n"
|
||||
kept = "## 2026-10-07T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: kept\n"
|
||||
self.assertEqual(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + tables(votes, scores) + places)), kept)
|
||||
|
||||
def test_keeps_every_bullet_of_a_listing_that_opens_with_a_dimension_voted_worse(self):
|
||||
votes = "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | worse | same | same |\n"
|
||||
places = "\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: deep\n- Shape: `bin/f.py:2` `o`: wide\n"
|
||||
expected = "## 2026-10-07T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: deep\n- Shape: `bin/f.py:2` `o`: wide\n"
|
||||
self.assertEqual(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + votes + places)), expected)
|
||||
|
||||
def test_drops_the_bullets_of_a_seat_with_no_row_in_the_votes_table(self):
|
||||
votes = "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | same | same | same |\n"
|
||||
places = "\nJunior A, decided by:\n\n- Locality: `bin/e.py:1` `n`: deep\n"
|
||||
self.assertIsNone(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + votes + places)))
|
||||
|
||||
def test_names_the_places_of_every_run_on_the_newest_scored_commit(self):
|
||||
run = "## {time}, {pr} at {commit}\n\nJunior A, hardest first:\n\n- `bin/b.py:{line}` `h`: long\n"
|
||||
first, rerun, other = (run.format(time=time, pr=pr, commit=commit, line=line) for time, pr, commit, line in (("2026-10-08T12:00:00Z", "PR #1", "aaaaaaa", 1), ("2026-10-08T13:00:00Z", "PR #1 rerun", "aaaaaaa", 2), ("2026-10-09T12:00:00Z", "PR #2", "bbbbbbb", 3)))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/main.py's help).
|
||||
"""loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/usage.py's help).
|
||||
|
||||
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, project/ reads a checkout's files, and waiting/ shows a question to loop-inbox. Each module at this level is imported by more than one package, and loop-inbox imports several. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
|
||||
"""
|
||||
|
||||
@@ -1,126 +1,3 @@
|
||||
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
||||
worker prompt also quotes the premises. They, with code health
|
||||
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
|
||||
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
|
||||
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
||||
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
|
||||
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
|
||||
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
|
||||
writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the
|
||||
worker made that the premises or the records settle is not asked about. When the worker asks a
|
||||
question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes
|
||||
with it. A quote they do not hold word for word is dropped, and the question goes to the human. So
|
||||
does a question asked again after its answer. The fourth question they answer in one cycle goes to
|
||||
the human too, with the quote. An unfinished chunk resumes its session next cycle, and the worker
|
||||
is shown the passage the judge quoted as the work remaining. The next chunk starts a fresh session.
|
||||
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the
|
||||
interrupts of every loop on the machine. The first answer counts, from either place:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
chunk stays unfinished until the answer is recorded.
|
||||
- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or
|
||||
discuss first. Once that claude exits, the judge rules on what was typed there.
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
||||
as bin/loop_claude/running_loops.py describes.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
||||
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
||||
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
|
||||
after 600 s and is stopped, leaves the worker to find the facts itself.
|
||||
|
||||
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
||||
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
|
||||
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is available
|
||||
(bin/machine_load/memory.py).
|
||||
|
||||
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
|
||||
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
|
||||
compacts its context at about 170k tokens.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
||||
entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that
|
||||
question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for
|
||||
the worker and the session /talk opens; with both set, nothing is asked.
|
||||
|
||||
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
||||
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
||||
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
|
||||
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
|
||||
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
|
||||
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
|
||||
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
||||
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
||||
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
without it.
|
||||
|
||||
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
|
||||
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
|
||||
on the terminal in the setup's development clone, ~/code/claude-config, asked to put the calls to
|
||||
the human; loop-inbox lists it too. Once that claude ends, the calls are listed in
|
||||
routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the calls are said on stderr, the loop goes on, and they are raised
|
||||
again at the next measurement.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- README.md, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
||||
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
|
||||
- README.md holds no premises
|
||||
- the models file cannot be read or written
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
- claude cannot start for an interrupt
|
||||
- python cannot start for a reload
|
||||
- a reload cannot read the state the running script handed it, likely because the edit changed that
|
||||
handover
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
||||
mistypes a field, interrupts or quotes an answer without a question, or quotes a passage the
|
||||
transcript does not hold; it holds an elided passage when each fragment appears in order.
|
||||
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
|
||||
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
|
||||
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
||||
always retried every 10 minutes. stderr says when the next try is due.
|
||||
|
||||
Exit 2, when the human is needed to go on:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
||||
nothing typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session.
|
||||
|
||||
"""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
@@ -135,6 +12,7 @@ from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint,
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from loop_claude.loop.usage import HELP
|
||||
from loop_claude.running_loops import Listed, shown_running
|
||||
from loop_claude.paths import Paths
|
||||
from project_key import project_key
|
||||
@@ -209,7 +87,7 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
|
||||
if argv[:1] != [RELOAD_FLAG]:
|
||||
task = " ".join(argv)
|
||||
if task in ("", "-h", "--help"):
|
||||
return Stop(0 if task else 1, __doc__.strip())
|
||||
return Stop(0 if task else 1, HELP)
|
||||
root = checkout_root(cwd, effects)
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "")
|
||||
loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
"""Every CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`."""
|
||||
"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: loop-claude measures review rounds…`."""
|
||||
import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from loop_claude.waiting.ask import Ask, OpenOnTerminal
|
||||
from routing_figures.measure import calls, due, render, totals
|
||||
from routing_figures.calls import Call, calls, totals
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.waiting.listing import listed
|
||||
from loop_claude.paths import Paths
|
||||
from routing_figures.render import render
|
||||
from model_routing.ladder import Rung
|
||||
from routing_figures import state
|
||||
from loop_claude.stop import Stop
|
||||
from utc_stamp import utc
|
||||
|
||||
@@ -24,29 +26,31 @@ def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, p
|
||||
return raise_calls(root, checkout, session, new, rung, paths, questions, effects) if new else None
|
||||
|
||||
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure:
|
||||
"""Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due."""
|
||||
cycle = archive.cycles(root)
|
||||
last = archive.last_measured(root)
|
||||
if isinstance(cycle, Failure) or isinstance(last, Failure) or not due(cycle, last):
|
||||
return cycle if isinstance(cycle, Failure) else last if isinstance(last, Failure) else []
|
||||
kept = archive.raised(root)
|
||||
if isinstance(kept, Failure):
|
||||
return kept
|
||||
if isinstance(cycle, Failure):
|
||||
return cycle
|
||||
kept = state.read_state(root)
|
||||
if isinstance(kept, Failure) or not state.due(cycle, kept.measured_at):
|
||||
return kept if isinstance(kept, Failure) else []
|
||||
raised = state.raised(root)
|
||||
if isinstance(raised, Failure):
|
||||
return raised
|
||||
say(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", effects, stdout=True)
|
||||
measured = archive.measure_archive(root, str(paths.home), kept.since, effects.git)
|
||||
measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
figures = totals(measured.chunks, measured.skipped, measured.unread)
|
||||
found = calls(figures)
|
||||
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, kept.since)):
|
||||
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
|
||||
return unwritten
|
||||
return [call for call in found if call not in kept.calls]
|
||||
return [call for call in found if call not in raised.calls]
|
||||
|
||||
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None:
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[Call], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
bullets = "".join(f"- {call}\n" for call in new)
|
||||
bullets = "".join(f"- {call.sentence()}\n" for call in new)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
|
||||
say(f"\n{question}", effects)
|
||||
if not effects.on_terminal():
|
||||
@@ -59,6 +63,6 @@ def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str],
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls in {paths.config_clone}, the setup's development clone: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
if unmarked := state.mark_raised(root, new, utc(effects.now())):
|
||||
say(f"routing figures: {unmarked.reason}", effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
HELP = """Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
||||
worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md → "Shared goal")
|
||||
ranked first unless README.md voids it, choose between ways to deliver the chunk's todo.md items, or
|
||||
else the task, and never widen them. A judge then reads the transcript's end, the premises, and the
|
||||
records: the project's AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md,
|
||||
~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where they exist. It rules
|
||||
whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the
|
||||
human typed in it that a later chunk could need is recorded: the premises or the records hold it, or
|
||||
the transcript shows the worker writing it into the premises, AGENTS.md, docs/decisions.md, todo.md
|
||||
or a code comment. A choice the worker made that the premises or the records settle is not asked
|
||||
about. When the worker asks a question they answer, the judge quotes the answer, loop-claude prints
|
||||
it, and the worker resumes with it. A quote they do not hold word for word is dropped, and the
|
||||
question goes to the human. So does a question asked again after its answer. The fourth question
|
||||
they answer in one cycle goes to the human too, with the quote. An unfinished chunk resumes its
|
||||
session next cycle, and the worker is shown the passage the judge quoted as the work remaining. The
|
||||
next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words:
|
||||
~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the
|
||||
interrupts of every loop on the machine. The first answer counts, from either place:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
chunk stays unfinished until the answer is recorded.
|
||||
- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or
|
||||
discuss first. Once that claude exits, the judge rules on what was typed there.
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
||||
as bin/loop_claude/running_loops.py describes.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
||||
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
||||
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
|
||||
after 600 s and is stopped, leaves the worker to find the facts itself.
|
||||
|
||||
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
||||
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
|
||||
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is
|
||||
available (bin/machine_load/memory.py).
|
||||
|
||||
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
|
||||
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
|
||||
compacts its context at about 170k tokens.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
||||
entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that
|
||||
question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for
|
||||
the worker and the session /talk opens; with both set, nothing is asked.
|
||||
|
||||
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
||||
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
||||
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
|
||||
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
|
||||
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
|
||||
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
|
||||
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
||||
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
||||
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
without it.
|
||||
|
||||
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/). Each call the figures make for a
|
||||
routing change, unless raised before, is an interrupt: claude, on the project's model, on the
|
||||
terminal in the setup's development clone, ~/code/claude-config, asked to put the calls to the
|
||||
human; loop-inbox lists it too. Once that claude ends, the calls are listed in
|
||||
routing-calls-raised.md beside the figures, kept in routing-state.json, and not raised again. Off a
|
||||
terminal, the calls are said on stderr, the loop goes on, and they are raised again at the next
|
||||
measurement.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- README.md, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
||||
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
|
||||
- README.md holds no premises
|
||||
- the models file cannot be read or written
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
- claude cannot start for an interrupt
|
||||
- python cannot start for a reload
|
||||
- a reload cannot read the state the running script handed it, likely because the edit changed that
|
||||
handover
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
||||
mistypes a field, interrupts or quotes an answer without a question, or quotes a passage the
|
||||
transcript does not hold; it holds an elided passage when each fragment appears in order.
|
||||
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
|
||||
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
|
||||
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
||||
always retried every 10 minutes. stderr says when the next try is due.
|
||||
|
||||
Exit 2, when the human is needed to go on:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
||||
nothing typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session."""
|
||||
@@ -19,8 +19,9 @@ import uuid
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from routing_figures import archive, measure
|
||||
from routing_figures import archive, state
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from routing_figures.calls import Call
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from loop_claude.loop import chunk_start, close
|
||||
from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed
|
||||
@@ -33,7 +34,7 @@ from loop_claude import hand_over, paths, routing, running_loops, session_lock
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.loop import main, reload, routing_check
|
||||
from loop_claude.loop import main, reload, routing_check, usage
|
||||
from loop_claude.waiting.talk import make_way
|
||||
from machine_load import memory
|
||||
from transcript_archive import outcomes, write
|
||||
@@ -923,7 +924,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}])
|
||||
self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release")
|
||||
self.assertIn("Record what they decide in this checkout, the development clone", args[6])
|
||||
(self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across")
|
||||
self.assertIsNone(state.mark_measured(self.root, 0))
|
||||
self.assertEqual(self.check(FakeEffects(git=[UNREAD]))[0], None)
|
||||
self.assertNotIn(call, self.check(FakeEffects())[1])
|
||||
|
||||
@@ -938,7 +939,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
|
||||
def test_says_a_figure_it_cannot_read(self):
|
||||
self.chunks(5, 4)
|
||||
(self.root / "routing-figures.md").mkdir()
|
||||
(self.root / "routing-state.json").mkdir()
|
||||
self.assertIn("routing figures: could not read", self.check(FakeEffects())[1])
|
||||
|
||||
def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self):
|
||||
@@ -946,7 +947,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
stop, said = self.check(FakeEffects(on_terminal=False, git=[UNREAD]))
|
||||
self.assertIsNone(stop)
|
||||
self.assertIn("Not on a terminal: the calls are raised again at the next measurement.", said)
|
||||
(self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across")
|
||||
self.assertIsNone(state.mark_measured(self.root, 0))
|
||||
self.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False, git=[UNREAD]))[1])
|
||||
|
||||
def test_leaves_the_measuring_to_a_loop_holding_the_lock(self):
|
||||
@@ -970,6 +971,16 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.assertIsNone(stop)
|
||||
self.assertIn("routing figures: could not write", said)
|
||||
|
||||
def test_puts_every_new_call_to_the_human_and_says_one_it_cannot_keep(self):
|
||||
new = [Call("reports", ("Explore",)), Call("rounds", ("x", "y"))]
|
||||
fake = FakeEffects(on_terminal_claude=[0])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")):
|
||||
self.assertIsNone(routing_check.raise_calls(self.root, "/code/log", "s1", new, Rung("m", "high"), self.paths, self.paths.waiting, fake.effects()))
|
||||
((args),) = fake.made("claude_on_terminal")
|
||||
self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
|
||||
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue())
|
||||
self.assertIn("routing figures: full", said.getvalue())
|
||||
|
||||
|
||||
class ModelPrompt(unittest.TestCase):
|
||||
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
|
||||
@@ -1156,17 +1167,8 @@ class Routing(unittest.TestCase):
|
||||
def test_leaves_the_count_of_unfinished_verdicts_out_of_the_worker_line_so_a_rerun_restarts_it(self):
|
||||
self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).worker_line()), Route(self.HIGH, 3, 4, 5))
|
||||
|
||||
def test_reads_no_route_from_a_worker_line_of_unknown_or_mistyped_fields_or_levels_off_their_scales(self):
|
||||
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": '):
|
||||
with self.subTest(line=line):
|
||||
self.assertIsNone(route_from(line))
|
||||
|
||||
def test_reads_the_route_from_a_line_loop_claude_wrote_before_it_archived_json(self):
|
||||
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"), Route(self.HIGH, 3, 4, 5))
|
||||
self.assertEqual(route_from("claude-opus-5-5 at high effort"), Route(self.HIGH))
|
||||
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7, escalated at transcript entry 12"), Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12))
|
||||
self.assertEqual(route_from("claude-opus-5-5 at high effort, taking in an E + I of 6"), Route(self.HIGH, escape_and_impact_taken_in=6))
|
||||
for line in ("worker-model", "claude-opus-5-5 at high effort, routed by item 3's L of 5 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's R + C of 11"):
|
||||
def test_reads_no_route_from_a_worker_line_that_route_worker_line_could_not_have_written(self):
|
||||
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"):
|
||||
with self.subTest(line=line):
|
||||
self.assertIsNone(route_from(line))
|
||||
|
||||
@@ -1825,15 +1827,18 @@ class LoopRuns(unittest.TestCase):
|
||||
|
||||
|
||||
class HelpLimits(unittest.TestCase):
|
||||
def test_help_wraps_at_100_columns(self):
|
||||
self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], [])
|
||||
|
||||
def test_help_states_the_limits_the_code_holds(self):
|
||||
said = " ".join(main.__doc__.split())
|
||||
said = " ".join(usage.HELP.split())
|
||||
self.assertIn(f"The {['second', 'third', 'fourth', 'fifth'][states.QUOTED_ANSWERS_PER_CYCLE - 1]} question they answer in one cycle", said)
|
||||
# The retry messages say these limits in words too.
|
||||
self.assertEqual((retry.FAILURES_RUNNING, retry.RETRY_DELAY), (3, 60))
|
||||
self.assertIn("fails three times running, retried a minute apart", said)
|
||||
self.assertIn(f"retried {retry.PAST_RESET // 60} minutes after the limit resets, or every {retry.UNKNOWN_RESET_POLL // 60} minutes", said)
|
||||
self.assertIn(f"still running after {PYTHON_TIMEOUT} s", said)
|
||||
self.assertIn(f"Once {measure.CYCLES_PER_CHECK} cycles have closed across all projects", said)
|
||||
self.assertIn(f"Once {state.CYCLES_PER_CHECK} cycles have closed across all projects", said)
|
||||
self.assertIn(f"run with a {worker.COMPACT_WINDOW // 1000}k auto-compact window", said)
|
||||
self.assertIn(f"unfinished {close.UNFINISHED_LIMIT} cycles running", said)
|
||||
self.assertIn(f"rerun to give it {close.UNFINISHED_LIMIT} more", said)
|
||||
@@ -1861,7 +1866,7 @@ class ExitContract(unittest.TestCase):
|
||||
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
|
||||
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
|
||||
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
|
||||
("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"),
|
||||
("loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
|
||||
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
|
||||
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
|
||||
("loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {paths.config_clone}", "claude cannot start for an interrupt"),
|
||||
@@ -1880,7 +1885,7 @@ class ExitContract(unittest.TestCase):
|
||||
for (path, function, code, reason), (want_path, want_function, want_code, reason_start, _) in zip(found, clauses):
|
||||
self.assertEqual((path, function, code), (want_path, want_function, want_code))
|
||||
self.assertTrue(reason.startswith(reason_start), f"{path} {function}: {reason}")
|
||||
help_exit_1 = " ".join(main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")].split())
|
||||
help_exit_1 = " ".join(usage.HELP[usage.HELP.index("Exit 1"):usage.HELP.index("Exit 2")].split())
|
||||
self.assertEqual([clause for *_, clause in clauses if f"- {clause}" not in help_exit_1], [])
|
||||
|
||||
|
||||
@@ -1909,7 +1914,7 @@ class JudgeFailures(unittest.TestCase):
|
||||
for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses):
|
||||
self.assertEqual(function, want_function)
|
||||
self.assertTrue(reason.startswith(reason_start), f"{function}: {reason}")
|
||||
judge_clause = " ".join(main.__doc__[main.__doc__.index("a judge when"):main.__doc__.index("A usage limit")].split())
|
||||
judge_clause = " ".join(usage.HELP[usage.HELP.index("a judge when"):usage.HELP.index("A usage limit")].split())
|
||||
self.assertEqual([clause for *_, clause in clauses if clause not in judge_clause], [])
|
||||
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ class Rung:
|
||||
return Rung(model, effort)
|
||||
return Rung(family.model, effort) if effort else family
|
||||
|
||||
# The one spelling of a rung. loop-claude hands it to rule-hook in environment variables, and archive lines written before route.Route.worker_line hold it, so parse must keep reading it.
|
||||
# loop-claude hands a rung to rule-hook in environment variables in this spelling, so parse must keep reading it.
|
||||
def __str__(self) -> str:
|
||||
return f"{self.model} at {self.effort} effort" if self.effort else self.model
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each outcome."""
|
||||
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each verdict, interrupt, quoted answer, stop and step-up."""
|
||||
import dataclasses
|
||||
import json
|
||||
import re
|
||||
import typing
|
||||
|
||||
from todo_table import LEVELS
|
||||
@@ -11,8 +10,6 @@ from model_routing.ladder import REVIEW_STEPS, Rung
|
||||
ESCALATION_MARKER = "Escalation trigger"
|
||||
# What Route.worker_line writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
|
||||
WorkerLine = typing.NewType("WorkerLine", str)
|
||||
# A worker line loop-claude wrote before it archived the route as JSON. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
|
||||
LEGACY_WORKER = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?(?:, escalated at transcript entry (?P<escalated_at>[0-9]+))?")
|
||||
|
||||
|
||||
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
|
||||
@@ -82,8 +79,8 @@ WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if
|
||||
|
||||
|
||||
def route_from(worker: str) -> Route | None:
|
||||
"""The route an archived worker line names, whether JSON or a line written before JSON. None where it names no model, holds fields Route.worker_line never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
|
||||
fields = json_fields(worker) if worker.startswith("{") else legacy_fields(worker)
|
||||
"""The route an archived worker line names; None for a line Route.worker_line could not have written, such as text that isn't JSON."""
|
||||
fields = json_fields(worker)
|
||||
if fields is None or not Route.fits(fields):
|
||||
return None
|
||||
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
|
||||
@@ -99,12 +96,3 @@ def json_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
return None
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
|
||||
|
||||
|
||||
def legacy_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
"""The fields of a LEGACY_WORKER line, as json_fields gives them; None for any other text."""
|
||||
found = LEGACY_WORKER.fullmatch(line)
|
||||
rung = Rung.parse(found["rung"]) if found else None
|
||||
if not (found and rung):
|
||||
return None
|
||||
return {"model": rung.model, "effort": rung.effort, **{name: int(value or 0) for name, value in found.groupdict().items() if name != "rung"}}
|
||||
|
||||
@@ -13,6 +13,9 @@ RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
|
||||
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
|
||||
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
|
||||
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
|
||||
DECISION_CITATION = re.compile(r"`?docs/decisions\.md`? → `([^`]+)`")
|
||||
DECISION_TITLE = re.compile(r"^## (.+)$", re.MULTILINE)
|
||||
LISTED_TITLE = re.compile(r"^- (.+)$", re.MULTILINE)
|
||||
NAME = re.compile(r'"([^"]+)"')
|
||||
RULE_FILE = re.compile(rf"(?<![\w/.-])(?:~/\.claude/)?({RULE_PATH})")
|
||||
STRAY = re.compile(rf'(?:CLAUDE\.md|{RULE_PATH})(?!`? → "|:\d)[^\n"]{{1,5}}"')
|
||||
@@ -46,3 +49,15 @@ class Citations(unittest.TestCase):
|
||||
|
||||
def test_every_folder_the_judge_reads_rules_from_exists(self):
|
||||
self.assertEqual([folder for folder in HUMAN_RULE_DIRS if not (ROOT / folder).is_dir()], [])
|
||||
|
||||
def test_agents_md_lists_exactly_the_decision_titles(self):
|
||||
listed = (ROOT / "AGENTS.md").read_text().split("Decisions live in `docs/decisions.md`:\n\n")[1].split("\n\n")[0]
|
||||
# The two files order the titles differently, so they are compared sorted.
|
||||
self.assertEqual(sorted(LISTED_TITLE.findall(listed)), sorted(DECISION_TITLE.findall((ROOT / "docs/decisions.md").read_text())))
|
||||
|
||||
def test_every_todo_citation_of_a_decision_names_a_title(self):
|
||||
titles = DECISION_TITLE.findall((ROOT / "docs/decisions.md").read_text())
|
||||
cited = DECISION_CITATION.findall((ROOT / "todo.md").read_text())
|
||||
self.assertTrue(cited)
|
||||
# A citation cut short ends in `…`, and then names the start of a title.
|
||||
self.assertEqual([name for name in cited if not any(title == name or name.endswith("…") and title.startswith(name.removesuffix("…").rstrip(" ,")) for title in titles)], [])
|
||||
|
||||
+12
-12
@@ -71,24 +71,24 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
|
||||
if isinstance(read, int):
|
||||
return read
|
||||
reviewed, anchor = read
|
||||
rounds = archived_rounds(REVIEWERS[reviewed], anchor.model, archive_root(home, env), home)
|
||||
reviewed, project = read
|
||||
rounds = archived_rounds(REVIEWERS[reviewed], project.model, archive_root(home, env), home)
|
||||
if isinstance(rounds, Failure):
|
||||
return failed(TOOL, rounds.reason)
|
||||
codes = codes_found(rounds, effects)
|
||||
if not codes:
|
||||
return failed(TOOL, f"no archived {reviewed} round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
chosen = sample(list(codes), LATEST)
|
||||
# The project's rung is the reference, so the candidates start below it. They reach the ladder's lowest rung, below the lowest a worker routes to, since a pass may run below the worker's rung.
|
||||
candidates = down_from(anchor, LADDER[0])[1:]
|
||||
candidates = down_from(project, LADDER[0])[1:]
|
||||
|
||||
def found_on(found: Round, rung: Rung) -> set[int] | Limited:
|
||||
return findings_found(found, codes[found], rung, anchor, home, effects)
|
||||
return findings_found(found, codes[found], rung, project, home, effects)
|
||||
|
||||
replay = replayed(chosen, anchor, candidates, found_on, reproduced, f"{reviewed} rounds")
|
||||
replay = replayed(chosen, project, candidates, found_on, reproduced, f"{reviewed} rounds")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(reviewed, anchor.model, anchor, chosen, replay))
|
||||
print(report(reviewed, project.model, project, chosen, replay))
|
||||
return 0
|
||||
|
||||
|
||||
@@ -97,8 +97,8 @@ def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung] | None:
|
||||
if len(argv) != 2:
|
||||
return None
|
||||
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
|
||||
anchor = project_rung(argv[1])
|
||||
return (reviewed, anchor) if reviewed and anchor else None
|
||||
project = project_rung(argv[1])
|
||||
return (reviewed, project) if reviewed and project else None
|
||||
|
||||
|
||||
def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
|
||||
@@ -177,12 +177,12 @@ def commit_log(listed: str) -> list[tuple[str, float]]:
|
||||
return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())]
|
||||
|
||||
|
||||
def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, home: pathlib.Path, effects: Effects) -> set[int] | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as the reviewer on anchor matches them."""
|
||||
def findings_found(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects) -> set[int] | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them."""
|
||||
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects))
|
||||
if isinstance(reviewed, Limited):
|
||||
return reviewed
|
||||
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, anchor, effects))
|
||||
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, project, effects))
|
||||
if isinstance(matched, Failure):
|
||||
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return set()
|
||||
|
||||
@@ -1,41 +1,27 @@
|
||||
"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures and the calls raised at the archive's root."""
|
||||
"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures at the archive's root for the human to read."""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import fcntl
|
||||
import functools
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from transcript_archive.read import archived_outcomes, chunk_outcomes, finished_chunks
|
||||
from branch_chunks.read import branch_chunks
|
||||
from branch_chunks.cut import BranchChunk
|
||||
from project_key import checkout_of
|
||||
from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent
|
||||
from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Subagent
|
||||
from git_repo import default_ref, Git
|
||||
from failure import Failure
|
||||
from claude_code.entries import parse_entry
|
||||
from file_writes import replace_file
|
||||
from utc_stamp import STAMPED
|
||||
from transcript_archive.outcomes import VERDICT_AT
|
||||
|
||||
FIGURES = "routing-figures.md"
|
||||
# Seconds each git call reading a project's history may take.
|
||||
GIT_TIMEOUT = 60
|
||||
LOCK = "routing-figures.lock"
|
||||
RAISED = "routing-calls-raised.md"
|
||||
RAISED_HEADING = "# Routing calls raised\n"
|
||||
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again.
|
||||
RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE)
|
||||
RESET = "Reset"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Raised:
|
||||
"""since is the latest reset's stamp, empty for none; calls are those raised after it."""
|
||||
since: str
|
||||
calls: frozenset[str]
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
@@ -66,47 +52,36 @@ def cycles(root: pathlib.Path) -> int | Failure:
|
||||
return Failure(f"could not count the cycles in {root}: {failure}")
|
||||
|
||||
|
||||
def last_measured(root: pathlib.Path) -> int | Failure:
|
||||
"""The cycle the kept figures were measured at; 0 before any."""
|
||||
try:
|
||||
found = MEASURED_AT.search((root / FIGURES).read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return 0
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {root / FIGURES}: {failure}")
|
||||
return int(found.group(1)) if found else 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Measured:
|
||||
class ArchiveChunks:
|
||||
"""skipped names each chunk folder that could not be read whole, such as one another loop is writing; unread names each project whose default branch could not be read, with why."""
|
||||
chunks: list[ChunkFigures]
|
||||
skipped: tuple[str, ...]
|
||||
unread: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> Measured | Failure:
|
||||
def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> ArchiveChunks | Failure:
|
||||
"""The figures of each chunk that finished after since, measured one chunk at a time because the archive outgrows memory. Only an archive that cannot be listed fails."""
|
||||
listed = archived_outcomes(root)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
projects = [measure_project(root, project, home, since, git) for project in sorted({root / key for key, _ in listed})]
|
||||
return Measured(
|
||||
return ArchiveChunks(
|
||||
[chunk for project in projects for chunk in project.chunks],
|
||||
tuple(skipped for project in projects for skipped in project.skipped),
|
||||
tuple(unread for project in projects for unread in project.unread),
|
||||
)
|
||||
|
||||
|
||||
def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: str, git: Git) -> Measured:
|
||||
def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since: str, git: Git) -> ArchiveChunks:
|
||||
"""The figures of each of one project's chunks that finished after since, as measure_archive measures them."""
|
||||
key = str(project.relative_to(root))
|
||||
listed = finished_chunks(project)
|
||||
if isinstance(listed, Failure):
|
||||
return Measured([], (key,))
|
||||
return ArchiveChunks([], (key,))
|
||||
chunks = [chunk for chunk in listed if chunk.finished > since]
|
||||
if not chunks:
|
||||
return Measured([], ())
|
||||
return ArchiveChunks([], ())
|
||||
history = branch_history(checkout_of(key, pathlib.Path(home)), git)
|
||||
found = []
|
||||
skipped = []
|
||||
@@ -119,8 +94,8 @@ def measure_project(root: pathlib.Path, project: pathlib.Path, home: str, since:
|
||||
except (OSError, UnicodeDecodeError):
|
||||
skipped.append(str(folder.relative_to(root)))
|
||||
continue
|
||||
found.append(measured(Chunk(key, kept, worker, subagents), home, None if isinstance(history, Failure) else history))
|
||||
return Measured(found, tuple(skipped), (f"{key}: {history.reason}",) if isinstance(history, Failure) else ())
|
||||
found.append(chunk_figures(Chunk(key, kept, worker, subagents), home, None if isinstance(history, Failure) else history))
|
||||
return ArchiveChunks(found, tuple(skipped), (f"{key}: {history.reason}",) if isinstance(history, Failure) else ())
|
||||
|
||||
|
||||
def branch_history(checkout: str, git: Git) -> list[BranchChunk] | Failure:
|
||||
@@ -148,31 +123,3 @@ def subagent(transcript: pathlib.Path) -> Subagent:
|
||||
def write_figures(root: pathlib.Path, text: str) -> Failure | None:
|
||||
unwritten = replace_file(root / FIGURES, text.encode())
|
||||
return Failure(f"could not write {root / FIGURES}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def raised(root: pathlib.Path) -> Raised | Failure:
|
||||
text = read_raised(root)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
lines = RAISED_LINE.findall(text)
|
||||
since = max((stamp for stamp, what in lines if what == RESET), default="")
|
||||
return Raised(since, frozenset(what for stamp, what in lines if stamp > since and what != RESET))
|
||||
|
||||
|
||||
def mark_raised(root: pathlib.Path, calls: list[str], at: str) -> Failure | None:
|
||||
kept = read_raised(root)
|
||||
if isinstance(kept, Failure):
|
||||
return kept
|
||||
# The first line opens a list below the heading; each later one joins it.
|
||||
gap = "\n" if RAISED_LINE.search(kept) else "\n\n"
|
||||
unwritten = replace_file(root / RAISED, (kept.rstrip("\n") + gap + "".join(f"- {at} {call}\n" for call in calls)).encode())
|
||||
return Failure(f"could not write {root / RAISED}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def read_raised(root: pathlib.Path) -> str | Failure:
|
||||
try:
|
||||
return (root / RAISED).read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return RAISED_HEADING
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {root / RAISED}: {failure}")
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""The routing figures summed over every chunk, and the routing changes they call for: docs/decisions.md → `routing: loop-claude measures review rounds…`."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from routing_figures.chunk import ChunkFigures, Reports
|
||||
from routing_figures.dollars import DIMENSIONS, Dollars
|
||||
from model_routing.ladder import position, Rung
|
||||
|
||||
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
|
||||
MEASURED_AT_LEAST = 5
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Figures:
|
||||
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole; unmatched counts the routed chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why."""
|
||||
chunks: int
|
||||
dollars: Dollars
|
||||
routed: dict[Rung, list[ChunkFigures]]
|
||||
reports: dict[str, Reports]
|
||||
escalated: collections.Counter[int]
|
||||
skipped: tuple[str, ...] = ()
|
||||
unattributed: float = 0.0
|
||||
lacking: int = 0
|
||||
unmatched: int = 0
|
||||
unread: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tuple[str, ...] = ()) -> Figures:
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for chunk in chunks:
|
||||
for dimension in DIMENSIONS:
|
||||
for label, amount in chunk.dollars.get(dimension, {}).items():
|
||||
dollars[dimension][label] += amount
|
||||
routed: dict[Rung, list[ChunkFigures]] = {}
|
||||
reports: dict[str, Reports] = {}
|
||||
for chunk in chunks:
|
||||
if chunk.start:
|
||||
routed.setdefault(chunk.start, []).append(chunk)
|
||||
for kind, found in chunk.reports.items():
|
||||
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
|
||||
return Figures(
|
||||
chunks=len(chunks),
|
||||
dollars=dollars,
|
||||
routed=routed,
|
||||
reports=reports,
|
||||
escalated=summed(chunks, lambda chunk: chunk.escalated),
|
||||
skipped=skipped,
|
||||
unattributed=sum(chunk.unattributed for chunk in chunks),
|
||||
lacking=sum(chunk.lacking for chunk in chunks),
|
||||
unmatched=sum(chunk.start is not None and chunk.fixed_later is None for chunk in chunks),
|
||||
unread=unread,
|
||||
)
|
||||
|
||||
|
||||
Kind = typing.Literal["rounds", "unfinished", "reports"]
|
||||
# Each kind of call to the sentence it is put to the human in, filled with its subjects in order.
|
||||
SENTENCES: dict[Kind, str] = {
|
||||
"rounds": "Chunks routed onto {} took more review rounds past each pass's first than chunks routed onto {}.",
|
||||
"unfinished": "Chunks routed onto {} took more unfinished verdicts than chunks routed onto {}.",
|
||||
"reports": "{} subagents' reports took more of the worker's context than their searches would have.",
|
||||
}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Call:
|
||||
"""A routing change the figures call for. Its fields, not its sentence, tell whether it was raised before. kind names its sentence in SENTENCES; subjects are the two rungs compared, lower first, or the subagent type."""
|
||||
kind: Kind
|
||||
subjects: tuple[str, ...]
|
||||
|
||||
def sentence(self) -> str:
|
||||
return SENTENCES[self.kind].format(*self.subjects)
|
||||
|
||||
|
||||
def calls(figures: Figures) -> list[Call]:
|
||||
"""Each routing change the figures call for."""
|
||||
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position)
|
||||
found = []
|
||||
for lower, upper in zip(compared, compared[1:]):
|
||||
measures: tuple[tuple[Kind, typing.Callable[[ChunkFigures], int]], ...] = (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished))
|
||||
for kind, of in measures:
|
||||
if mean(figures.routed[lower], of) > mean(figures.routed[upper], of):
|
||||
found.append(Call(kind, (str(lower), str(upper))))
|
||||
# Characters stand in for tokens: reports and the tool results their subagents read are both text the worker would read, so their sums compare their shares of its context.
|
||||
found += [Call("reports", (kind,)) for kind, reports in sorted(figures.reports.items()) if reports.subagents >= MEASURED_AT_LEAST and reports.report_chars > reports.read_chars]
|
||||
return found
|
||||
|
||||
|
||||
def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -> float:
|
||||
return statistics.mean(map(of, chunks))
|
||||
|
||||
|
||||
def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], collections.Counter]) -> collections.Counter:
|
||||
return sum(map(of, chunks), collections.Counter())
|
||||
@@ -0,0 +1,182 @@
|
||||
"""The figures of one finished chunk: its dollars, the rung it started on, its review rounds and unfinished verdicts, its subagents' rungs and reports, its escalations and its later fixes."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
|
||||
from branch_chunks.cut import BranchChunk
|
||||
from git_command import commits
|
||||
from routing_figures.dollars import costed, Dollars, Message, messages, recorded_costs, Spent
|
||||
from model_routing.route import ESCALATION_MARKER, Route, route_from
|
||||
from transcript_archive.outcomes import judge_costs, UNFINISHED_AT, workers
|
||||
from round_titles import rounds_past_first
|
||||
from model_routing.ladder import Rung
|
||||
from shell_command import simple_commands
|
||||
|
||||
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Subagent:
|
||||
"""kind is the agentType and launched_by the toolUseId of the launching Agent call, as the subagent's .meta.json names them, each empty where it names none; entries are its transcript's entries."""
|
||||
kind: str
|
||||
launched_by: str
|
||||
entries: list[dict]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Chunk:
|
||||
"""outcomes holds each outcomes file archived for the chunk, one per transcript copy, each opening with its task; worker is its finished transcript's entries."""
|
||||
project: str
|
||||
outcomes: list[str]
|
||||
worker: list[dict]
|
||||
subagents: list[Subagent]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reports:
|
||||
"""How many subagents of a type reported, the characters of their reports, and the characters of the tool results they read."""
|
||||
subagents: int
|
||||
report_chars: int
|
||||
read_chars: int
|
||||
|
||||
def __add__(self, other: "Reports") -> "Reports":
|
||||
return Reports(self.subagents + other.subagents, self.report_chars + other.report_chars, self.read_chars + other.read_chars)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ChunkFigures:
|
||||
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive; fixed_later counts the later chunks that fixed code it shipped, None where no item routed it, its project's default branch could not be read, or no chunk on that branch shipped its item."""
|
||||
dollars: Dollars
|
||||
start: Rung | None
|
||||
rounds_past_first: int
|
||||
unfinished: int
|
||||
delegated: collections.Counter[str]
|
||||
reports: dict[str, Reports]
|
||||
escalated: collections.Counter[int]
|
||||
unattributed: float
|
||||
lacking: int = 0
|
||||
fixed_later: int | None = None
|
||||
|
||||
|
||||
def chunk_figures(chunk: Chunk, home: str, history: list[BranchChunk] | None = None) -> ChunkFigures:
|
||||
"""history is the chunks on the project's default branch, None where it could not be read."""
|
||||
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
|
||||
launches = agent_calls(chunk.worker)
|
||||
reported = results(chunk.worker)
|
||||
delegated = [delegation(subagent, launches, reported, cycles) for subagent in chunk.subagents]
|
||||
dollars, unattributed = chunk_dollars(chunk, cycles, delegated)
|
||||
start = route_from(cycles[0][1]) if cycles else None
|
||||
return ChunkFigures(
|
||||
dollars=dollars,
|
||||
start=start.rung if start and start.item else None,
|
||||
rounds_past_first=rounds_past_first(commit_titles(chunk.worker, home)),
|
||||
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
|
||||
delegated=collections.Counter(one.rung for one in delegated),
|
||||
reports=reports_by_type(delegated),
|
||||
escalated=escalations(launches),
|
||||
unattributed=unattributed,
|
||||
lacking=transcripts_lacking(launches, chunk.subagents),
|
||||
fixed_later=later_fixes_of(start, history),
|
||||
)
|
||||
|
||||
|
||||
def chunk_dollars(chunk: Chunk, cycles: list[tuple[str, str]], delegated: list[Delegation]) -> tuple[Dollars, float]:
|
||||
"""What costed makes of the messages of the worker, each on the rung of the cycle it ran in, and of its subagents, and of the chunk's judge runs."""
|
||||
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
|
||||
spent += [Spent(one.kind, one.rung, message) for one in delegated for message in one.messages]
|
||||
judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)]
|
||||
return costed(spent, judged, chunk.project, recorded_costs(chunk.worker))
|
||||
|
||||
|
||||
def reports_by_type(delegated: list[Delegation]) -> dict[str, Reports]:
|
||||
reports: dict[str, Reports] = {}
|
||||
for one in delegated:
|
||||
reports[one.kind] = reports.get(one.kind, Reports(0, 0, 0)) + Reports(1, one.report_chars, one.read_chars)
|
||||
return reports
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Delegation:
|
||||
"""One subagent as the figures count it: its type, the rung it ran on, the characters of its report and of the tool results it read, and its messages."""
|
||||
kind: str
|
||||
rung: str
|
||||
report_chars: int
|
||||
read_chars: int
|
||||
messages: list[Message]
|
||||
|
||||
|
||||
def delegation(subagent: Subagent, launches: dict[str, tuple[str, dict]], reported: dict[str, str], cycles: list[tuple[str, str]]) -> Delegation:
|
||||
"""reported holds the worker's tool results by call id, so the Agent call's result is the subagent's report."""
|
||||
launched_at, arguments = launches.get(subagent.launched_by, ("", {}))
|
||||
return Delegation(
|
||||
kind=subagent.kind or str(arguments.get("subagent_type") or "unknown"),
|
||||
rung=str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at))),
|
||||
report_chars=len(reported.get(subagent.launched_by, "")),
|
||||
read_chars=sum(map(len, results(subagent.entries).values())),
|
||||
messages=messages(subagent.entries),
|
||||
)
|
||||
|
||||
|
||||
def transcripts_lacking(launches: dict[str, tuple[str, dict]], subagents: list[Subagent]) -> int:
|
||||
"""How many Agent calls, the worker's and its subagents', have no subagent transcript in the archive. Each transcript answers one call, so they are the calls less the transcripts."""
|
||||
return max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in subagents) - len(subagents))
|
||||
|
||||
|
||||
def later_fixes_of(start: Route | None, history: list[BranchChunk] | None) -> int | None:
|
||||
"""How many later chunks fixed code shipped by the chunk in history that shipped the item start names. None where no item routed the chunk, history could not be read, or no chunk in it shipped the item."""
|
||||
# lilleman chose on 2026-10-28 to find a routed chunk's chunk on the default branch by the item its route names, not by commit titles: it needs no title matching, and works where the worker's transcript doesn't show the titles; a chunk whose PR didn't remove its item reads as unknown.
|
||||
if start is None or not start.item or history is None:
|
||||
return None
|
||||
return next((len(chunk.fixed_by) for chunk in history if any(shipped.id == start.item for shipped in chunk.shipped)), None)
|
||||
|
||||
|
||||
def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]:
|
||||
"""How many of the worker's Agent calls open with each escalation trigger's number."""
|
||||
opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values())
|
||||
return collections.Counter(int(found[1]) for found in opened if found)
|
||||
|
||||
|
||||
def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
|
||||
"""The timestamp and the arguments of each Agent call, by the call's id."""
|
||||
found = {}
|
||||
for entry in worker:
|
||||
for part in assistant_parts(entry):
|
||||
call = tool_call(part)
|
||||
if call and call[0] == "Agent" and isinstance(part, dict) and isinstance(call[1], dict):
|
||||
found[str(part.get("id"))] = (str(entry.get("timestamp", "")), call[1])
|
||||
return found
|
||||
|
||||
|
||||
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
|
||||
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker."""
|
||||
found = next((rung for stamp, rung in cycles if stamp >= to_the_second(timestamp)), cycles[-1][1] if cycles else "unrouted")
|
||||
route = route_from(found)
|
||||
return route.rung if route else found
|
||||
|
||||
|
||||
def to_the_second(timestamp: str) -> str:
|
||||
"""A message's stamp, such as 2026-10-15T00:00:00.123Z, cut to the second, as an outcome is stamped: 2026-10-15T00:00:00Z. Stamps in that one form sort as text in time order."""
|
||||
return timestamp[:19] + "Z"
|
||||
|
||||
|
||||
def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung:
|
||||
"""The model the subagent ran, at the effort its Agent call set, or else at the worker's."""
|
||||
model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown"))
|
||||
effort = arguments.get("effort") or (worker.effort if isinstance(worker, Rung) else "")
|
||||
return Rung(model, str(effort))
|
||||
|
||||
|
||||
def results(entries: list[dict]) -> dict[str, str]:
|
||||
"""Each tool result's text by the id of the call it answers."""
|
||||
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
|
||||
|
||||
|
||||
def commit_titles(worker: list[dict], home: str) -> list[str]:
|
||||
"""The title of each commit the worker's Bash calls made, in order, each once: a commit retried after a failed hook repeats its title."""
|
||||
return list(dict.fromkeys(
|
||||
commit.messages[0].split("\n", 1)[0]
|
||||
for entry in worker for part in assistant_parts(entry)
|
||||
if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict)
|
||||
for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages
|
||||
))
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Dollars a chunk's messages cost, by project, subagent type, rung and tool: each model's recorded cost split across its messages by their list prices."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
from claude_code.entries import assistant_parts, tool_call
|
||||
from routing_figures.prices import listed
|
||||
|
||||
DIMENSIONS = ("project", "subagent type", "rung", "tool")
|
||||
# Each of DIMENSIONS to its labels' dollars.
|
||||
Dollars = dict[str, collections.defaultdict[str, float]]
|
||||
# The tool label of a message that follows no tool call, such as the first message after a prompt.
|
||||
PROMPT = "prompt"
|
||||
# The subagent type the judge's runs are counted under; the judge is no subagent, and has no tools, so its dollars count towards PROMPT.
|
||||
JUDGE = "judge"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Message:
|
||||
"""An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices."""
|
||||
at: str
|
||||
tools: list[str]
|
||||
model: str
|
||||
list_price: float
|
||||
|
||||
|
||||
class Spent(typing.NamedTuple):
|
||||
"""A message with the subagent type that wrote it, or `worker`, and the rung it ran on."""
|
||||
kind: str
|
||||
rung: str
|
||||
message: Message
|
||||
|
||||
|
||||
def messages(entries: list[dict]) -> list[Message]:
|
||||
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
|
||||
# Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
|
||||
kept: dict[str, tuple[str, dict, list[str]]] = {}
|
||||
for entry in entries:
|
||||
if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict):
|
||||
continue
|
||||
found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, []))
|
||||
found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str))
|
||||
counted = []
|
||||
before = [PROMPT]
|
||||
for at, message, called in kept.values():
|
||||
model = str(message.get("model") or "")
|
||||
counted.append(Message(at, before, model, listed(model, message.get("usage"))))
|
||||
before = called or [PROMPT]
|
||||
return counted
|
||||
|
||||
|
||||
# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...}
|
||||
def recorded_costs(worker: list[dict]) -> dict[str, float]:
|
||||
"""The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too."""
|
||||
for entry in reversed(worker):
|
||||
if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict):
|
||||
return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))}
|
||||
return {}
|
||||
|
||||
|
||||
def costed(spent: list[Spent], judged: list[tuple[str, float]], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]:
|
||||
"""Each message's dollars by DIMENSIONS, with each judge run's cost in judged, by the judge's rung, under the subagent type JUDGE and the tool PROMPT; and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices."""
|
||||
listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float)
|
||||
for _, _, message in spent:
|
||||
listed_by_model[message.model] += message.list_price
|
||||
scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded}
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for kind, rung, message in spent:
|
||||
cost = message.list_price * scale.get(message.model, 1.0)
|
||||
dollars["project"][project] += cost
|
||||
dollars["subagent type"][kind] += cost
|
||||
dollars["rung"][rung] += cost
|
||||
for tool in message.tools:
|
||||
dollars["tool"][tool] += cost / len(message.tools)
|
||||
for rung, cost in judged:
|
||||
dollars["project"][project] += cost
|
||||
dollars["subagent type"][JUDGE] += cost
|
||||
dollars["rung"][rung] += cost
|
||||
dollars["tool"][PROMPT] += cost
|
||||
return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])
|
||||
@@ -1,367 +0,0 @@
|
||||
"""Dollar spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import re
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from claude_code.entries import assistant_parts, parts, tool_call, tool_result
|
||||
from branch_chunks.cut import BranchChunk
|
||||
from git_command import commits
|
||||
from model_routing.route import ESCALATION_MARKER, Route, route_from
|
||||
from transcript_archive.outcomes import judge_costs
|
||||
from routing_figures.prices import listed
|
||||
from model_routing.ladder import position, Rung
|
||||
from round_titles import rounds_past_first
|
||||
from shell_command import simple_commands
|
||||
from transcript_archive.outcomes import UNFINISHED_AT, workers
|
||||
|
||||
CYCLES_PER_CHECK = 20
|
||||
MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE)
|
||||
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
|
||||
MEASURED_AT_LEAST = 5
|
||||
DIMENSIONS = ("project", "subagent type", "rung", "tool")
|
||||
# Each of DIMENSIONS to its labels' dollars.
|
||||
Dollars = dict[str, collections.defaultdict[str, float]]
|
||||
# The tool label of a message that follows no tool call, such as the first message after a prompt.
|
||||
PROMPT = "prompt"
|
||||
# The subagent type the judge's runs are counted under; the judge is no subagent, and has no tools, so its dollars count towards PROMPT.
|
||||
JUDGE = "judge"
|
||||
ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Subagent:
|
||||
"""kind is the agentType and launched_by the toolUseId of the launching Agent call, as the subagent's .meta.json names them, each empty where it names none; entries are its transcript's entries."""
|
||||
kind: str
|
||||
launched_by: str
|
||||
entries: list[dict]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Chunk:
|
||||
"""outcomes holds each outcomes file archived for the chunk, one per transcript copy, each opening with its task; worker is its finished transcript's entries."""
|
||||
project: str
|
||||
outcomes: list[str]
|
||||
worker: list[dict]
|
||||
subagents: list[Subagent]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reports:
|
||||
"""How many subagents of a type reported, and the characters of their reports and of the tool results they read."""
|
||||
subagents: int
|
||||
report: int
|
||||
searches: int
|
||||
|
||||
def __add__(self, other: "Reports") -> "Reports":
|
||||
return Reports(self.subagents + other.subagents, self.report + other.report, self.searches + other.searches)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ChunkFigures:
|
||||
"""dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive; fixed_later counts the later chunks that fixed code it shipped, None where no item routed it, its project's default branch could not be read, or no chunk on that branch shipped its item."""
|
||||
dollars: Dollars
|
||||
start: Rung | None
|
||||
rounds_past_first: int
|
||||
unfinished: int
|
||||
delegated: collections.Counter[str]
|
||||
reports: dict[str, Reports]
|
||||
escalated: collections.Counter[int]
|
||||
unattributed: float
|
||||
lacking: int = 0
|
||||
fixed_later: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Figures:
|
||||
"""escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole; unmatched counts the routed chunks whose later fixes are unknown; unread names each project whose default branch could not be read, with why."""
|
||||
chunks: int
|
||||
dollars: Dollars
|
||||
routed: dict[Rung, list[ChunkFigures]]
|
||||
reports: dict[str, Reports]
|
||||
escalated: collections.Counter[int]
|
||||
skipped: tuple[str, ...] = ()
|
||||
unattributed: float = 0.0
|
||||
lacking: int = 0
|
||||
unmatched: int = 0
|
||||
unread: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Message:
|
||||
"""An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices."""
|
||||
at: str
|
||||
tools: list[str]
|
||||
model: str
|
||||
list_price: float
|
||||
|
||||
|
||||
class Spent(typing.NamedTuple):
|
||||
"""A message with the subagent type that wrote it, or `worker`, and the rung it ran on."""
|
||||
kind: str
|
||||
rung: str
|
||||
message: Message
|
||||
|
||||
|
||||
def measured(chunk: Chunk, home: str, history: list[BranchChunk] | None = None) -> ChunkFigures:
|
||||
"""history is the chunks on the project's default branch, None where it could not be read."""
|
||||
cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0])
|
||||
spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)]
|
||||
launches = agent_calls(chunk.worker)
|
||||
reported = results(chunk.worker)
|
||||
delegated: collections.Counter[str] = collections.Counter()
|
||||
reports: dict[str, Reports] = {}
|
||||
for subagent in chunk.subagents:
|
||||
launched_at, arguments = launches.get(subagent.launched_by, ("", {}))
|
||||
kind = subagent.kind or str(arguments.get("subagent_type") or "unknown")
|
||||
rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at)))
|
||||
delegated[rung] += 1
|
||||
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
|
||||
spent += [Spent(kind, rung, message) for message in messages(subagent.entries)]
|
||||
judged = [judged for kept in chunk.outcomes for judged in judge_costs(kept)]
|
||||
dollars, unattributed = costed(spent, judged, chunk.project, recorded_costs(chunk.worker))
|
||||
start = route_from(cycles[0][1]) if cycles else None
|
||||
return ChunkFigures(
|
||||
dollars=dollars,
|
||||
start=start.rung if start and start.item else None,
|
||||
rounds_past_first=rounds_past_first(commit_titles(chunk.worker, home)),
|
||||
unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes),
|
||||
delegated=delegated,
|
||||
reports=reports,
|
||||
escalated=escalations(launches),
|
||||
unattributed=unattributed,
|
||||
lacking=transcripts_lacking(launches, chunk.subagents),
|
||||
fixed_later=later_fixes_of(start, history),
|
||||
)
|
||||
|
||||
|
||||
def transcripts_lacking(launches: dict[str, tuple[str, dict]], subagents: list[Subagent]) -> int:
|
||||
"""How many Agent calls, the worker's and its subagents', have no subagent transcript in the archive. Each transcript answers one call, so they are the calls less the transcripts."""
|
||||
return max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in subagents) - len(subagents))
|
||||
|
||||
|
||||
def later_fixes_of(start: Route | None, history: list[BranchChunk] | None) -> int | None:
|
||||
"""How many later chunks fixed code shipped by the chunk in history that shipped the item start names. None where no item routed the chunk, history could not be read, or no chunk in it shipped the item."""
|
||||
# lilleman chose on 2026-10-28 to find a routed chunk's chunk on the default branch by the item its route names, not by commit titles: it needs no title matching, and works where the worker's transcript doesn't show the titles; a chunk whose PR didn't remove its item reads as unknown.
|
||||
if start is None or not start.item or history is None:
|
||||
return None
|
||||
return next((len(chunk.fixed_by) for chunk in history if any(shipped.id == start.item for shipped in chunk.shipped)), None)
|
||||
|
||||
|
||||
def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]:
|
||||
"""How many of the worker's Agent calls open with each escalation trigger's number."""
|
||||
opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values())
|
||||
return collections.Counter(int(found[1]) for found in opened if found)
|
||||
|
||||
|
||||
def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]:
|
||||
"""The timestamp and the arguments of each Agent call, by the call's id."""
|
||||
found = {}
|
||||
for entry in worker:
|
||||
for part in assistant_parts(entry):
|
||||
call = tool_call(part)
|
||||
if call and call[0] == "Agent" and isinstance(part, dict) and isinstance(call[1], dict):
|
||||
found[str(part.get("id"))] = (str(entry.get("timestamp", "")), call[1])
|
||||
return found
|
||||
|
||||
|
||||
# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...}
|
||||
def recorded_costs(worker: list[dict]) -> dict[str, float]:
|
||||
"""The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too."""
|
||||
for entry in reversed(worker):
|
||||
if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict):
|
||||
return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))}
|
||||
return {}
|
||||
|
||||
|
||||
def costed(spent: list[Spent], judged: list[tuple[str, float]], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]:
|
||||
"""Each message's dollars by DIMENSIONS, with each judge run's cost in judged, by the judge's rung, under the subagent type JUDGE and the tool PROMPT; and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices."""
|
||||
listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float)
|
||||
for _, _, message in spent:
|
||||
listed_by_model[message.model] += message.list_price
|
||||
scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded}
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for kind, rung, message in spent:
|
||||
cost = message.list_price * scale.get(message.model, 1.0)
|
||||
dollars["project"][project] += cost
|
||||
dollars["subagent type"][kind] += cost
|
||||
dollars["rung"][rung] += cost
|
||||
for tool in message.tools:
|
||||
dollars["tool"][tool] += cost / len(message.tools)
|
||||
for rung, cost in judged:
|
||||
dollars["project"][project] += cost
|
||||
dollars["subagent type"][JUDGE] += cost
|
||||
dollars["rung"][rung] += cost
|
||||
dollars["tool"][PROMPT] += cost
|
||||
return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model])
|
||||
|
||||
|
||||
def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
|
||||
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker."""
|
||||
second = timestamp[:19] + "Z"
|
||||
found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted")
|
||||
route = route_from(found)
|
||||
return route.rung if route else found
|
||||
|
||||
|
||||
def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung:
|
||||
"""The model the subagent ran, at the effort its Agent call set, or else at the worker's."""
|
||||
model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown"))
|
||||
effort = arguments.get("effort") or (worker.effort if isinstance(worker, Rung) else "")
|
||||
return Rung(model, str(effort))
|
||||
|
||||
|
||||
def messages(entries: list[dict]) -> list[Message]:
|
||||
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
|
||||
# Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
|
||||
kept: dict[str, tuple[str, dict, list[str]]] = {}
|
||||
for entry in entries:
|
||||
if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict):
|
||||
continue
|
||||
found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, []))
|
||||
found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str))
|
||||
counted = []
|
||||
before = [PROMPT]
|
||||
for at, message, called in kept.values():
|
||||
model = str(message.get("model") or "")
|
||||
counted.append(Message(at, before, model, listed(model, message.get("usage"))))
|
||||
before = called or [PROMPT]
|
||||
return counted
|
||||
|
||||
|
||||
def results(entries: list[dict]) -> dict[str, str]:
|
||||
"""Each tool result's text by the id of the call it answers."""
|
||||
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
|
||||
|
||||
|
||||
def commit_titles(worker: list[dict], home: str) -> list[str]:
|
||||
"""The title of each commit the worker's Bash calls made, in order, each once: a commit retried after a failed hook repeats its title."""
|
||||
return list(dict.fromkeys(
|
||||
commit.messages[0].split("\n", 1)[0]
|
||||
for entry in worker for part in assistant_parts(entry)
|
||||
if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict)
|
||||
for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages
|
||||
))
|
||||
|
||||
|
||||
def due(cycle: int, last_measured: int) -> bool:
|
||||
"""Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK."""
|
||||
return cycle >= last_measured + CYCLES_PER_CHECK
|
||||
|
||||
|
||||
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = (), unread: tuple[str, ...] = ()) -> Figures:
|
||||
dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS}
|
||||
for chunk in chunks:
|
||||
for dimension in DIMENSIONS:
|
||||
for label, amount in chunk.dollars.get(dimension, {}).items():
|
||||
dollars[dimension][label] += amount
|
||||
routed: dict[Rung, list[ChunkFigures]] = {}
|
||||
reports: dict[str, Reports] = {}
|
||||
for chunk in chunks:
|
||||
if chunk.start:
|
||||
routed.setdefault(chunk.start, []).append(chunk)
|
||||
for kind, found in chunk.reports.items():
|
||||
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found
|
||||
return Figures(
|
||||
chunks=len(chunks),
|
||||
dollars=dollars,
|
||||
routed=routed,
|
||||
reports=reports,
|
||||
escalated=summed(chunks, lambda chunk: chunk.escalated),
|
||||
skipped=skipped,
|
||||
unattributed=sum(chunk.unattributed for chunk in chunks),
|
||||
lacking=sum(chunk.lacking for chunk in chunks),
|
||||
unmatched=sum(chunk.start is not None and chunk.fixed_later is None for chunk in chunks),
|
||||
unread=unread,
|
||||
)
|
||||
|
||||
|
||||
def calls(figures: Figures) -> list[str]:
|
||||
"""Each routing change the figures call for, worded alike whatever the numbers, so a call already raised is known again."""
|
||||
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position)
|
||||
found = []
|
||||
for lower, upper in zip(compared, compared[1:]):
|
||||
for what, of in (("review rounds past each pass's first", lambda chunk: chunk.rounds_past_first), ("unfinished verdicts", lambda chunk: chunk.unfinished)):
|
||||
if mean(figures.routed[lower], of) > mean(figures.routed[upper], of):
|
||||
found.append(f"Chunks routed onto {lower} took more {what} than chunks routed onto {upper}.")
|
||||
# Characters stand in for tokens: reports and searches are both text the worker would read, so their sums compare their shares of its context.
|
||||
found += [f"{kind} subagents' reports took more of the worker's context than their searches would have." for kind, reports in sorted(figures.reports.items()) if reports.subagents >= MEASURED_AT_LEAST and reports.report > reports.searches]
|
||||
return found
|
||||
|
||||
|
||||
def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -> float:
|
||||
return statistics.mean(map(of, chunks))
|
||||
|
||||
|
||||
def basis(figures: Figures) -> str:
|
||||
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
|
||||
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's cost counts from the verdicts and rejections that record it, so a chunk archived before they did, and a judge run that failed, add none."
|
||||
if figures.unattributed:
|
||||
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
|
||||
if figures.lacking:
|
||||
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
|
||||
return text
|
||||
|
||||
|
||||
def fixes_basis(figures: Figures) -> str:
|
||||
"""What the later fixes column counts, and how many routed chunks it can't count."""
|
||||
text = "A routed chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, counted as `score-outcomes` counts them. A recent chunk has had less time to gather any. The routed chunk is matched to the chunk on that branch that removed the item its route names from todo.md. The column gives the mean over a rung's chunks whose later fixes are known, and how many those are."
|
||||
if figures.unmatched:
|
||||
text += f" The later fixes of {figures.unmatched} of the routed chunks are unknown, since no chunk on the branch removed their item from todo.md, or the branch could not be read."
|
||||
return text
|
||||
|
||||
|
||||
def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str:
|
||||
"""The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none."""
|
||||
sections = [
|
||||
"# Routing figures",
|
||||
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
||||
"## Calls for a routing change",
|
||||
"".join(f"- {call}\n" for call in found).rstrip("\n") or "None.",
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))],
|
||||
"## Routed chunks by the rung they started on",
|
||||
fixes_basis(figures),
|
||||
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, mean", "Subagent rungs", "Escalations by trigger"), [
|
||||
(str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", fixes_per_chunk(chunks), subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
|
||||
for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0]))
|
||||
]),
|
||||
"## Escalations by trigger across every chunk, routed or not",
|
||||
f"{triggers(figures.escalated) or 'None'}.",
|
||||
"## Subagent reports against the searches they ran, in characters",
|
||||
table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(found.subagents), str(found.report), str(found.searches)) for kind, found in sorted(figures.reports.items())]),
|
||||
*(["## Chunks skipped, unreadable", "".join(f"- {folder}\n" for folder in figures.skipped).rstrip("\n")] if figures.skipped else []),
|
||||
*(["## Default branches unread","".join(f"- {project}\n" for project in figures.unread).rstrip("\n")] if figures.unread else []),
|
||||
]
|
||||
return "\n\n".join(sections) + "\n"
|
||||
|
||||
|
||||
def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], collections.Counter]) -> collections.Counter:
|
||||
return sum(map(of, chunks), collections.Counter())
|
||||
|
||||
|
||||
def fixes_per_chunk(chunks: list[ChunkFigures]) -> str:
|
||||
"""The mean later fixes of the chunks whose later fixes are known, and how many those are, as `1.0 (3 known)`; `unknown` where none is."""
|
||||
# A mean, not a median: most chunks gather no later fix, so the median reads 0 until over half do, and can't show the rise per finished chunk that goal 1's counter-signal watches.
|
||||
known = [chunk.fixed_later for chunk in chunks if chunk.fixed_later is not None]
|
||||
return f"{statistics.mean(known):.1f} ({len(known)} known)" if known else "unknown"
|
||||
|
||||
|
||||
def subagent_rungs(chunks: list[ChunkFigures]) -> str:
|
||||
"""The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`."""
|
||||
return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common())
|
||||
|
||||
|
||||
def triggers(escalated: collections.Counter[int]) -> str:
|
||||
"""Escalations as `trigger 2: 3, trigger 3: 1`."""
|
||||
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items()))
|
||||
|
||||
|
||||
def money(dollars: float) -> str:
|
||||
return f"${dollars:,.2f}"
|
||||
|
||||
|
||||
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
|
||||
if not rows:
|
||||
return "None."
|
||||
return "\n".join(f"| {' | '.join(row)} |" for row in [header, tuple("---" for _ in header), *rows])
|
||||
@@ -0,0 +1,100 @@
|
||||
"""The routing figures as the markdown kept at the archive's root."""
|
||||
import collections
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from routing_figures.calls import Call, Figures, mean, summed
|
||||
from routing_figures.chunk import ChunkFigures
|
||||
from routing_figures.dollars import DIMENSIONS
|
||||
from model_routing.ladder import position
|
||||
|
||||
|
||||
def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str) -> str:
|
||||
"""The figures as markdown, for the human to read. since is the latest reset's stamp, empty for none."""
|
||||
sections = [
|
||||
"# Routing figures",
|
||||
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
||||
"## Calls for a routing change",
|
||||
bullets([call.sentence() for call in found]) or "None.",
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", dollars_table(figures, dimension))],
|
||||
"## Routed chunks by the rung they started on",
|
||||
fixes_basis(figures),
|
||||
routed_table(figures),
|
||||
"## Escalations by trigger across every chunk, routed or not",
|
||||
f"{triggers(figures.escalated) or 'None'}.",
|
||||
"## Subagent reports against the tool results they read, in characters",
|
||||
table(("Subagent type", "Subagents", "Reports", "Tool results read"), [(kind, str(reports.subagents), str(reports.report_chars), str(reports.read_chars)) for kind, reports in sorted(figures.reports.items())]),
|
||||
*(["## Chunks skipped, unreadable", bullets(figures.skipped)] if figures.skipped else []),
|
||||
*(["## Default branches unread", bullets(figures.unread)] if figures.unread else []),
|
||||
]
|
||||
return "\n\n".join(sections) + "\n"
|
||||
|
||||
|
||||
def dollars_table(figures: Figures, dimension: str) -> str:
|
||||
"""The dimension's labels and their dollars, largest first."""
|
||||
return table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])])
|
||||
|
||||
|
||||
def routed_table(figures: Figures) -> str:
|
||||
"""One row per rung the routed chunks started on, from the bottom of the ladder up."""
|
||||
return table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, mean", "Subagent rungs", "Escalations by trigger"), [
|
||||
(
|
||||
str(rung),
|
||||
str(len(chunks)),
|
||||
f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}",
|
||||
f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}",
|
||||
fixes_per_chunk(chunks),
|
||||
subagent_rungs(chunks),
|
||||
triggers(summed(chunks, lambda chunk: chunk.escalated)),
|
||||
)
|
||||
for rung, chunks in sorted(figures.routed.items(), key=lambda routed: position(routed[0]))
|
||||
])
|
||||
|
||||
|
||||
def bullets(lines: typing.Iterable[str]) -> str:
|
||||
return "\n".join(f"- {line}" for line in lines)
|
||||
|
||||
|
||||
def basis(figures: Figures) -> str:
|
||||
"""What the dollars are, what they leave out, and where the archive falls short of the recorded cost."""
|
||||
text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's cost counts from the verdicts and rejections that record it, so a chunk archived before they did, and a judge run that failed, add none."
|
||||
if figures.unattributed:
|
||||
text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive."
|
||||
if figures.lacking:
|
||||
text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls."
|
||||
return text
|
||||
|
||||
|
||||
def fixes_basis(figures: Figures) -> str:
|
||||
"""What the later fixes column counts, and how many routed chunks it can't count."""
|
||||
text = "A routed chunk's later fixes are the chunks on its project's default branch, as last fetched, that fixed code it shipped, counted as `score-outcomes` counts them. A recent chunk has had less time to gather any. The routed chunk is matched to the chunk on that branch that removed the item its route names from todo.md. The column gives the mean over a rung's chunks whose later fixes are known, and how many those are."
|
||||
if figures.unmatched:
|
||||
text += f" The later fixes of {figures.unmatched} of the routed chunks are unknown, since no chunk on the branch removed their item from todo.md, or the branch could not be read."
|
||||
return text
|
||||
|
||||
|
||||
def fixes_per_chunk(chunks: list[ChunkFigures]) -> str:
|
||||
"""The mean later fixes of the chunks whose later fixes are known, and how many those are, as `1.0 (3 known)`; `unknown` where none is."""
|
||||
# A mean, not a median: most chunks gather no later fix, so the median reads 0 until over half do, and can't show the rise per finished chunk that goal 1's counter-signal watches.
|
||||
known = [chunk.fixed_later for chunk in chunks if chunk.fixed_later is not None]
|
||||
return f"{statistics.mean(known):.1f} ({len(known)} known)" if known else "unknown"
|
||||
|
||||
|
||||
def subagent_rungs(chunks: list[ChunkFigures]) -> str:
|
||||
"""The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`."""
|
||||
return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common())
|
||||
|
||||
|
||||
def triggers(escalated: collections.Counter[int]) -> str:
|
||||
"""Escalations as `trigger 2: 3, trigger 3: 1`."""
|
||||
return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items()))
|
||||
|
||||
|
||||
def money(dollars: float) -> str:
|
||||
return f"${dollars:,.2f}"
|
||||
|
||||
|
||||
def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str:
|
||||
if not rows:
|
||||
return "None."
|
||||
return "\n".join(f"| {' | '.join(row)} |" for row in [header, tuple("---" for _ in header), *rows])
|
||||
@@ -0,0 +1,125 @@
|
||||
"""What loop-claude keeps at the archive's root between measurements: docs/decisions.md → `routing: loop-claude measures review rounds…`.
|
||||
|
||||
STATE holds, as fields loop-claude reads back, the cycle it last measured at and each call it raised. RAISED lists the raised calls for the human to read. A chunk appends a reset to RAISED by hand, as AGENTS.md says, and loop-claude reads the resets from there."""
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from routing_figures.calls import Call, SENTENCES
|
||||
from failure import Failure
|
||||
from file_writes import replace_file, replace_json
|
||||
from utc_stamp import STAMPED
|
||||
|
||||
CYCLES_PER_CHECK = 20
|
||||
RAISED = "routing-calls-raised.md"
|
||||
RAISED_HEADING = "# Routing calls raised\n"
|
||||
# Each line is a call and when it was raised, or a reset: `- <UTC time> <call>` or `- <UTC time> Reset`. After a reset the figures count only chunks that finished after it, and a call raised before it may be raised again.
|
||||
RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE)
|
||||
RESET = "Reset"
|
||||
# {"measured_at": 40, "raised": [{"at": "2026-10-15T00:00:00Z", "kind": "reports", "subjects": ["Explore"]}]}
|
||||
STATE = "routing-state.json"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stamped:
|
||||
"""A call and when it was raised."""
|
||||
at: str
|
||||
call: Call
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class State:
|
||||
"""measured_at is the cycle the kept figures were measured at, 0 before any; raised holds every call raised, oldest first."""
|
||||
measured_at: int
|
||||
raised: tuple[Stamped, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Raised:
|
||||
"""since is the latest reset's stamp, empty for none; calls are those raised after it."""
|
||||
since: str
|
||||
calls: frozenset[Call]
|
||||
|
||||
|
||||
def due(cycle: int, measured_at: int) -> bool:
|
||||
"""Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK."""
|
||||
return cycle >= measured_at + CYCLES_PER_CHECK
|
||||
|
||||
|
||||
def read_state(root: pathlib.Path) -> State | Failure:
|
||||
"""The kept state; before any is kept, no measurement and no call."""
|
||||
try:
|
||||
text = (root / STATE).read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return State(0, ())
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {root / STATE}: {failure}")
|
||||
return decoded(text) or Failure(f"could not read {root / STATE}: not the shape the comment on STATE in bin/routing_figures/state.py shows")
|
||||
|
||||
|
||||
def decoded(text: str) -> State | None:
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(data, dict) or type(data.get("measured_at")) is not int or not isinstance(data.get("raised"), list):
|
||||
return None
|
||||
raised = [stamped(entry) for entry in data["raised"]]
|
||||
return State(data["measured_at"], tuple(entry for entry in raised if entry)) if all(raised) else None
|
||||
|
||||
|
||||
def stamped(entry: object) -> Stamped | None:
|
||||
if not isinstance(entry, dict) or not isinstance(at := entry.get("at"), str) or (kind := entry.get("kind")) not in SENTENCES:
|
||||
return None
|
||||
subjects = entry.get("subjects")
|
||||
if not isinstance(subjects, list) or not all(isinstance(subject, str) for subject in subjects) or len(subjects) != SENTENCES[kind].count("{}"):
|
||||
return None
|
||||
return Stamped(at, Call(kind, tuple(subjects)))
|
||||
|
||||
|
||||
def write_state(root: pathlib.Path, state: State) -> Failure | None:
|
||||
unwritten = replace_json(root / STATE, {"measured_at": state.measured_at, "raised": [{"at": entry.at, "kind": entry.call.kind, "subjects": list(entry.call.subjects)} for entry in state.raised]}, indent="\t")
|
||||
return Failure(f"could not write {root / STATE}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def mark_measured(root: pathlib.Path, cycle: int) -> Failure | None:
|
||||
kept = read_state(root)
|
||||
return kept if isinstance(kept, Failure) else write_state(root, dataclasses.replace(kept, measured_at=cycle))
|
||||
|
||||
|
||||
def raised(root: pathlib.Path) -> Raised | Failure:
|
||||
"""The calls raised after the latest reset that RAISED names."""
|
||||
text = read_raised(root)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
kept = read_state(root)
|
||||
if isinstance(kept, Failure):
|
||||
return kept
|
||||
since = max((stamp for stamp, what in RAISED_LINE.findall(text) if what == RESET), default="")
|
||||
return Raised(since, frozenset(entry.call for entry in kept.raised if entry.at > since))
|
||||
|
||||
|
||||
def mark_raised(root: pathlib.Path, calls: list[Call], at: str) -> Failure | None:
|
||||
"""Keeps the calls in STATE, and adds a line for each to RAISED."""
|
||||
kept = read_state(root)
|
||||
if isinstance(kept, Failure):
|
||||
return kept
|
||||
text = read_raised(root)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
if unwritten := write_state(root, dataclasses.replace(kept, raised=kept.raised + tuple(Stamped(at, call) for call in calls))):
|
||||
return unwritten
|
||||
# The first line opens a list below the heading; each later one joins it.
|
||||
gap = "\n" if RAISED_LINE.search(text) else "\n\n"
|
||||
unwritten = replace_file(root / RAISED, (text.rstrip("\n") + gap + "".join(f"- {at} {call.sentence()}\n" for call in calls)).encode())
|
||||
return Failure(f"could not write {root / RAISED}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def read_raised(root: pathlib.Path) -> str | Failure:
|
||||
try:
|
||||
return (root / RAISED).read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return RAISED_HEADING
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {root / RAISED}: {failure}")
|
||||
@@ -14,15 +14,18 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from routing_figures import archive
|
||||
from routing_figures import archive, state
|
||||
from branch_chunks.cut import BranchChunk
|
||||
from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals
|
||||
from routing_figures.calls import Call, calls, totals
|
||||
from routing_figures.chunk import Chunk, chunk_figures, ChunkFigures, Reports, Subagent
|
||||
from routing_figures.state import due
|
||||
from failure import Failure
|
||||
import git_repo
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from transcript_archive import outcomes, write
|
||||
from routing_figures.render import render
|
||||
from model_routing.route import Route
|
||||
|
||||
LOW = Rung("claude-opus-5-5", "medium")
|
||||
@@ -77,7 +80,7 @@ class Measured(unittest.TestCase):
|
||||
message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}),
|
||||
]
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).worker_line())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
|
||||
found = measured(Chunk("log", [kept], worker, []), "/h")
|
||||
found = chunk_figures(Chunk("log", [kept], worker, []), "/h")
|
||||
self.assertEqual(found.dollars["project"], {"log": 6.0})
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 4.0, str(HIGH): 2.0})
|
||||
@@ -86,7 +89,7 @@ class Measured(unittest.TestCase):
|
||||
|
||||
def test_counts_the_judges_recorded_cost_under_the_judge_and_the_rung_it_ran_on(self):
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "judge-rung", "", judge_cost=0.5)) + stamped("2026-10-14T12:00:00Z", outcomes.finished(LOW_ROUTE, "m", "judge-rung", judge_cost=0.25)) + stamped("2026-10-14T12:00:00Z", outcomes.rejected("why", "{}", "other-rung", judge_cost=1.0))
|
||||
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T10:00:00Z")], []), "/h")
|
||||
found = chunk_figures(Chunk("log", [kept], [message("m1", "2026-10-14T10:00:00Z")], []), "/h")
|
||||
self.assertEqual(found.dollars["project"], {"log": 3.75})
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "judge": 1.75})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, "judge-rung": 0.75, "other-rung": 1.0})
|
||||
@@ -102,7 +105,7 @@ class Measured(unittest.TestCase):
|
||||
Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z", model="claude-sonnet-5-5"), result("r", "z" * 20)]),
|
||||
Subagent("", "a2", [message("s2", "2026-10-14T10:00:01Z")]),
|
||||
]
|
||||
found = measured(Chunk("log", [stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))], worker, subagents), "/h")
|
||||
found = chunk_figures(Chunk("log", [stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j"))], worker, subagents), "/h")
|
||||
self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1})
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 2.0, "Explore": 3.0})
|
||||
self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)})
|
||||
@@ -112,16 +115,16 @@ class Measured(unittest.TestCase):
|
||||
message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", prompt="Escalation trigger 2: the test failed twice"), call("Agent", "a2", prompt="Escalation trigger 2: again"), call("Agent", "a3", prompt="Escalation trigger 3: a 🔴 in round 2")),
|
||||
message("m2", "2026-10-14T10:01:00Z", call("Agent", "a4", prompt="Find the callers. Escalation trigger 1: not at the start"), call("Agent", "a5", prompt="Escalation trigger x: no number")),
|
||||
]
|
||||
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1})
|
||||
self.assertEqual(chunk_figures(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1})
|
||||
|
||||
def test_counts_review_rounds_past_each_passs_first_once_per_title(self):
|
||||
commit = lambda id_, title: message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'"))
|
||||
worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")]
|
||||
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1)
|
||||
self.assertEqual(chunk_figures(Chunk("log", [], worker, []), "/h").rounds_past_first, 1)
|
||||
|
||||
def fixed_later(self, history, route=LOW_ROUTE):
|
||||
"""The later fixes measured counts for a chunk that route started, which LOW_ROUTE does by item 7, on a project whose default branch holds history, None where it could not be read."""
|
||||
return measured(Chunk("log", [stamped("2026-10-14T10:00:00Z", outcomes.finished(route, "m", "j"))], [], []), "/h", history).fixed_later
|
||||
return chunk_figures(Chunk("log", [stamped("2026-10-14T10:00:00Z", outcomes.finished(route, "m", "j"))], [], []), "/h", history).fixed_later
|
||||
|
||||
def test_counts_the_later_fixes_of_the_chunk_that_shipped_the_item_its_route_names(self):
|
||||
self.assertEqual(self.fixed_later([shipping(6, fixed_by=("c", "d", "e")), shipping(5, 7, fixed_by=("c", "d"))]), 2)
|
||||
@@ -139,16 +142,9 @@ class Measured(unittest.TestCase):
|
||||
def test_leaves_the_later_fixes_unknown_where_the_route_names_no_item(self):
|
||||
self.assertIsNone(self.fixed_later([shipping(7, fixed_by=("c",))], Route(LOW).worker_line()))
|
||||
|
||||
def test_reads_the_route_of_a_line_loop_claude_wrote_before_it_archived_json(self):
|
||||
older = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j"))
|
||||
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
|
||||
self.assertEqual(found.start, LOW)
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
|
||||
|
||||
def test_starts_no_route_for_a_chunk_no_item_routed(self):
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "m", "j"))
|
||||
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
|
||||
found = chunk_figures(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
|
||||
self.assertIsNone(found.start)
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0})
|
||||
|
||||
@@ -160,14 +156,14 @@ class Measured(unittest.TestCase):
|
||||
message("m3", "2026-10-14T10:31:00Z", call("Agent", "a2", subagent_type="Explore")),
|
||||
]
|
||||
subagents = [Subagent("Explore", "a1", [result("r", "x")]), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])]
|
||||
found = measured(Chunk("log", [kept], worker, subagents), "/h")
|
||||
found = chunk_figures(Chunk("log", [kept], worker, subagents), "/h")
|
||||
self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0})
|
||||
|
||||
def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))]
|
||||
subagents = [Subagent("stability-reviewer", "a1", []), Subagent("", "a2", []), Subagent("", "", [])]
|
||||
self.assertEqual(measured(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)})
|
||||
self.assertEqual(chunk_figures(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)})
|
||||
|
||||
def test_counts_a_message_without_usage_or_a_priced_model_as_nothing_and_splits_a_cost_evenly_across_tools(self):
|
||||
worker = [
|
||||
@@ -177,20 +173,20 @@ class Measured(unittest.TestCase):
|
||||
{"type": "assistant", "uuid": "u3", "message": {"model": "claude-opus-5-5", "content": []}},
|
||||
{"type": "assistant", "uuid": "u4", "message": {"model": "claude-unheard-of", "content": [], "usage": {"input_tokens": 9_000_000}}},
|
||||
]
|
||||
found = measured(Chunk("log", [], worker, []), "/h")
|
||||
found = chunk_figures(Chunk("log", [], worker, []), "/h")
|
||||
self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 4.0, "Grep": 4.0})
|
||||
self.assertEqual(found.dollars["project"], {"log": 12.0})
|
||||
|
||||
def test_prices_input_cache_writes_by_their_lifetime_cache_reads_and_output_at_the_models_list_prices(self):
|
||||
usage = {"input_tokens": 1_000_000, "cache_creation_input_tokens": 2_000_000, "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, "cache_read_input_tokens": 1_000_000, "output_tokens": 1_000_000}
|
||||
opus = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
|
||||
opus = chunk_figures(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
|
||||
self.assertAlmostEqual(opus.dollars["project"]["log"], 4 + 5 + 8 + 0.2 + 20)
|
||||
sonnet = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h")
|
||||
sonnet = chunk_figures(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h")
|
||||
self.assertAlmostEqual(sonnet.dollars["project"]["log"], 2 + 2.5 + 4 + 0.2 + 10)
|
||||
|
||||
def test_counts_a_cache_write_without_a_lifetime_as_a_five_minute_one(self):
|
||||
usage = {"cache_creation_input_tokens": 1_000_000}
|
||||
found = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
|
||||
found = chunk_figures(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h")
|
||||
self.assertAlmostEqual(found.dollars["project"]["log"], 5)
|
||||
|
||||
def test_splits_the_cost_a_chunks_last_cost_state_records_for_each_model_across_its_messages_by_list_price(self):
|
||||
@@ -201,31 +197,31 @@ class Measured(unittest.TestCase):
|
||||
cost_state(claude_opus_5_5=9.0, claude_haiku_5_5=0.5),
|
||||
]
|
||||
subagents = [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]
|
||||
found = measured(Chunk("log", [], worker, subagents), "/h")
|
||||
found = chunk_figures(Chunk("log", [], worker, subagents), "/h")
|
||||
self.assertEqual(found.dollars["subagent type"], {"worker": 6.0, "Explore": 3.0})
|
||||
self.assertEqual(found.dollars["project"], {"log": 9.0})
|
||||
self.assertEqual(found.unattributed, 0.5)
|
||||
|
||||
def test_counts_the_subagents_the_worker_launched_that_have_no_transcript(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Explore"), call("Read", "r1", file_path="/c/a"))]
|
||||
found = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h")
|
||||
found = chunk_figures(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h")
|
||||
self.assertEqual(found.lacking, 1)
|
||||
unnamed = measured(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h")
|
||||
unnamed = chunk_figures(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h")
|
||||
self.assertEqual(unnamed.lacking, 0)
|
||||
nested = [message("s1", "2026-10-14T10:00:01Z", call("Agent", "n1", subagent_type="Explore"))]
|
||||
launched = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h")
|
||||
launched = chunk_figures(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h")
|
||||
self.assertEqual(launched.lacking, 0)
|
||||
self.assertEqual(measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1)
|
||||
self.assertEqual(chunk_figures(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1)
|
||||
|
||||
def test_charges_a_message_without_a_timestamp_to_the_rung_of_the_last_outcome(self):
|
||||
undated = message("m1", "")
|
||||
del undated["timestamp"]
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j"))
|
||||
self.assertEqual(measured(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0})
|
||||
self.assertEqual(chunk_figures(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0})
|
||||
|
||||
def test_keeps_list_prices_for_a_model_the_cost_state_does_not_name(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z"), message("m2", "2026-10-14T10:01:00Z", model="claude-sonnet-5-5"), cost_state(claude_opus_5_5=3.0)]
|
||||
found = measured(Chunk("log", [], worker, []), "/h")
|
||||
found = chunk_figures(Chunk("log", [], worker, []), "/h")
|
||||
self.assertEqual(found.dollars["project"], {"log": 4.0})
|
||||
self.assertEqual(found.unattributed, 0.0)
|
||||
|
||||
@@ -233,15 +229,14 @@ class Measured(unittest.TestCase):
|
||||
class Calls(unittest.TestCase):
|
||||
def test_calls_when_chunks_on_a_rung_took_more_rounds_or_unfinished_verdicts_than_the_rung_above(self):
|
||||
chunks = [figures(LOW, rounds=2)] * 5 + [figures(HIGH, unfinished=1)] * 5
|
||||
self.assertEqual(calls(totals(chunks)), [
|
||||
f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.",
|
||||
])
|
||||
self.assertEqual(calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5)), [
|
||||
f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.",
|
||||
])
|
||||
self.assertEqual(calls(totals(chunks)), [Call("rounds", (str(LOW), str(HIGH)))])
|
||||
self.assertEqual(calls(totals(chunks))[0].sentence(), f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.")
|
||||
[unfinished] = calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5))
|
||||
self.assertEqual(unfinished, Call("unfinished", (str(LOW), str(HIGH))))
|
||||
self.assertEqual(unfinished.sentence(), f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.")
|
||||
|
||||
def test_compares_the_bottom_rungs_and_calls_nothing_on_a_tie(self):
|
||||
self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [f"Chunks routed onto {LADDER[0]} took more review rounds past each pass's first than chunks routed onto {LADDER[1]}."])
|
||||
self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [Call("rounds", (str(LADDER[0]), str(LADDER[1])))])
|
||||
self.assertEqual(calls(totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), [])
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), [])
|
||||
|
||||
@@ -249,17 +244,17 @@ class Calls(unittest.TestCase):
|
||||
self.assertEqual(calls(totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), [])
|
||||
|
||||
def test_calls_when_a_subagent_types_reports_outgrow_the_searches_they_ran(self):
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5)), [
|
||||
"Explore subagents' reports took more of the worker's context than their searches would have.",
|
||||
])
|
||||
[call] = calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5))
|
||||
self.assertEqual(call, Call("reports", ("Explore",)))
|
||||
self.assertEqual(call.sentence(), "Explore subagents' reports took more of the worker's context than their searches would have.")
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), [])
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
|
||||
|
||||
def test_renders_each_dimension_largest_first_and_the_calls(self):
|
||||
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
|
||||
text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "")
|
||||
text = render(totals([chunk]), [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
|
||||
self.assertIn("## Calls for a routing change\n\n- Call.\n", text)
|
||||
self.assertIn("## Calls for a routing change\n\n- Explore subagents' reports took more of the worker's context than their searches would have.\n", text)
|
||||
self.assertIn("## Dollars by project", text)
|
||||
self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text)
|
||||
self.assertIn("cache reads included", text)
|
||||
@@ -325,7 +320,7 @@ class Archive(unittest.TestCase):
|
||||
found = archive.measure_archive(self.root, "/h", "", no_checkout)
|
||||
self.assertEqual([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}])
|
||||
self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0})
|
||||
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.Measured([], ()))
|
||||
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.ArchiveChunks([], ()))
|
||||
|
||||
def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self):
|
||||
home = self.root / "home"
|
||||
@@ -414,26 +409,54 @@ class Archive(unittest.TestCase):
|
||||
self.assertEqual((len(found.chunks), found.skipped), (1, ("broken", "log/c1")))
|
||||
self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
|
||||
def test_keeps_the_figures_and_reads_back_the_cycle_they_were_measured_at(self):
|
||||
self.assertEqual(archive.last_measured(self.root), 0)
|
||||
self.assertIsNone(archive.write_figures(self.root, render(totals([]), [], "2026-10-15T00:00:00Z", 40, "")))
|
||||
self.assertEqual(archive.last_measured(self.root), 40)
|
||||
def test_keeps_the_cycle_it_measured_at_and_reads_it_back(self):
|
||||
self.assertEqual(state.read_state(self.root), state.State(0, ()))
|
||||
self.assertIsNone(state.mark_measured(self.root, 40))
|
||||
self.assertEqual(state.read_state(self.root), state.State(40, ()))
|
||||
self.assertIsNone(archive.write_figures(self.root, "# Routing figures\n"))
|
||||
self.assertEqual(state.read_state(self.root).measured_at, 40, "the rendered figures are for the human, and never read back")
|
||||
|
||||
def test_reads_the_calls_raised_since_the_latest_reset(self):
|
||||
self.assertEqual(archive.raised(self.root), archive.Raised("", frozenset()))
|
||||
self.assertIsNone(archive.mark_raised(self.root, ["A."], "2026-10-15T00:00:00Z"))
|
||||
self.assertIsNone(archive.mark_raised(self.root, ["B."], "2026-10-15T01:00:00Z"))
|
||||
self.assertEqual((self.root / archive.RAISED).read_text(), "# Routing calls raised\n\n- 2026-10-15T00:00:00Z A.\n- 2026-10-15T01:00:00Z B.\n")
|
||||
self.assertEqual(archive.raised(self.root), archive.Raised("", frozenset({"A.", "B."})))
|
||||
self.assertIsNone(archive.mark_raised(self.root, ["Reset", "C."], "2026-10-15T00:30:00Z"))
|
||||
self.assertEqual(archive.raised(self.root), archive.Raised("2026-10-15T00:30:00Z", frozenset({"B."})))
|
||||
a, b, c = Call("reports", ("Explore",)), Call("rounds", ("x", "y")), Call("unfinished", ("x", "y"))
|
||||
self.assertEqual(state.raised(self.root), state.Raised("", frozenset()))
|
||||
self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T00:00:00Z"))
|
||||
self.assertIsNone(state.mark_raised(self.root, [b, c], "2026-10-15T01:00:00Z"))
|
||||
self.assertEqual((self.root / state.RAISED).read_text(), f"# Routing calls raised\n\n- 2026-10-15T00:00:00Z {a.sentence()}\n- 2026-10-15T01:00:00Z {b.sentence()}\n- 2026-10-15T01:00:00Z {c.sentence()}\n")
|
||||
self.assertEqual(state.raised(self.root), state.Raised("", frozenset({a, b, c})))
|
||||
with open(self.root / state.RAISED, "a") as handle:
|
||||
handle.write("- 2026-10-15T01:00:00Z Reset\n")
|
||||
self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset()), "a call stamped at the reset's second was raised before it")
|
||||
self.assertIsNone(state.mark_raised(self.root, [a], "2026-10-15T02:00:00Z"))
|
||||
self.assertEqual(state.raised(self.root), state.Raised("2026-10-15T01:00:00Z", frozenset({a})))
|
||||
|
||||
def test_reads_no_measured_cycle_from_figures_that_name_none(self):
|
||||
(self.root / archive.FIGURES).write_text("# Routing figures\n")
|
||||
self.assertEqual(archive.last_measured(self.root), 0)
|
||||
(self.root / archive.FIGURES).unlink()
|
||||
(self.root / archive.FIGURES).mkdir()
|
||||
self.assertIsInstance(archive.last_measured(self.root), Failure)
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_fails_when_it_cannot_keep_the_state(self):
|
||||
self.root.chmod(0o555)
|
||||
self.addCleanup(self.root.chmod, 0o755)
|
||||
self.assertIsInstance(state.mark_measured(self.root, 40), Failure)
|
||||
self.assertIsInstance(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure)
|
||||
|
||||
def test_fails_when_it_cannot_list_a_raised_call_for_the_human(self):
|
||||
self.assertIsNone(state.mark_measured(self.root, 40))
|
||||
written = state.replace_file
|
||||
with unittest.mock.patch.object(state, "replace_file", lambda path, data: Failure("full") if path.name == state.RAISED else written(path, data)):
|
||||
self.assertEqual(state.mark_raised(self.root, [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z"), Failure(f"could not write {self.root / state.RAISED}: full"))
|
||||
|
||||
def test_knows_a_raised_call_by_its_fields_whatever_its_line_reads(self):
|
||||
call = Call("reports", ("Explore",))
|
||||
self.assertIsNone(state.mark_raised(self.root, [call], "2026-10-15T00:00:00Z"))
|
||||
(self.root / state.RAISED).write_text("# Routing calls raised\n\n- 2026-10-15T00:00:00Z Reworded.\n")
|
||||
self.assertEqual(state.raised(self.root).calls, frozenset({call}))
|
||||
|
||||
def test_fails_on_a_state_it_cannot_read(self):
|
||||
for text in ("not json", "[]", '{"measured_at": "40", "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "nope", "subjects": []}]}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": ["a", "b"]}]}', '{"measured_at": true, "raised": []}', '{"measured_at": 40, "raised": [{"at": "x", "kind": "reports", "subjects": "a"}]}'):
|
||||
with self.subTest(text):
|
||||
(self.root / state.STATE).write_text(text)
|
||||
self.assertIsInstance(state.read_state(self.root), Failure)
|
||||
self.assertIsInstance(state.raised(self.root), Failure)
|
||||
(self.root / state.STATE).unlink()
|
||||
(self.root / state.STATE).mkdir()
|
||||
self.assertIsInstance(state.read_state(self.root), Failure)
|
||||
|
||||
def test_holds_the_lock_while_no_other_loop_does(self):
|
||||
with archive.locked(self.root) as held, archive.locked(self.root) as other:
|
||||
@@ -442,8 +465,8 @@ class Archive(unittest.TestCase):
|
||||
self.assertTrue(again)
|
||||
|
||||
def test_fails_on_an_archive_it_cannot_read(self):
|
||||
(self.root / archive.RAISED).mkdir()
|
||||
self.assertIsInstance(archive.raised(self.root), Failure)
|
||||
(self.root / state.RAISED).mkdir()
|
||||
self.assertIsInstance(state.raised(self.root), Failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+3
-10
@@ -5,8 +5,9 @@ import typing
|
||||
|
||||
from round_titles import CAP, lacks_counts, RELEASE_REVIEW_CAP
|
||||
from git_command import commits
|
||||
from run_heavy.capped_docker import finds_this_docker
|
||||
from rule_hook.heavy_command import heavy
|
||||
from shell_command import launched, Simple, tool_name
|
||||
from shell_command import launched, Simple
|
||||
from review_folder import REPORTS
|
||||
from docker_command import unlimited
|
||||
|
||||
@@ -162,15 +163,7 @@ def unlimited_container(words: list[str]) -> bool:
|
||||
docker = launched(words, {"docker"})
|
||||
if docker is None or not unlimited(docker.arguments):
|
||||
return False
|
||||
# On Linux, run-heavy's docker adds the limits a container lacks, where PATH finds it: docker named bare, with PATH left as run-heavy set it.
|
||||
before = words[:len(words) - len(docker.arguments) - 1]
|
||||
capped = "run-heavy" in docker.launchers and words[len(before)] == "docker" and not any(resets_path(word) for word in before)
|
||||
return not capped
|
||||
|
||||
|
||||
def resets_path(word: str) -> bool:
|
||||
"""Whether a word before docker drops the PATH run-heavy set: a PATH= of its own, env's -i or -u, or sudo or doas, which reset it."""
|
||||
return word.startswith(("PATH=", "--unset")) or word in ("-i", "--ignore-environment", "-u") or tool_name(word) in ("doas", "sudo")
|
||||
return not ("run-heavy" in docker.launchers and finds_this_docker(docker.word, docker.before))
|
||||
|
||||
|
||||
def file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
|
||||
|
||||
@@ -6,6 +6,7 @@ import sys
|
||||
import typing
|
||||
|
||||
from docker_command import capped
|
||||
from shell_command import tool_name
|
||||
|
||||
# The folder run-heavy puts first on its command's PATH, holding the docker that runs main.
|
||||
PATH_ENTRY = pathlib.Path(__file__).resolve().parent / "path_entry"
|
||||
@@ -33,3 +34,13 @@ def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
def without_path_entry(path: str) -> str:
|
||||
"""path less PATH_ENTRY, so the real docker is the one found."""
|
||||
return os.pathsep.join(entry for entry in path.split(os.pathsep) if pathlib.Path(entry).resolve() != PATH_ENTRY)
|
||||
|
||||
|
||||
def finds_this_docker(word: str, before: list[str]) -> bool:
|
||||
"""Whether a command's docker is this one, given the word that names docker and the words before it, assuming run-heavy put this docker first on PATH, as it does on Linux. It is where docker is named bare, since a path names a different docker, and no word before it may reset PATH."""
|
||||
return word == "docker" and not any(resets_path(earlier) for earlier in before)
|
||||
|
||||
|
||||
def resets_path(word: str) -> bool:
|
||||
"""Whether a word before docker may drop the PATH run-heavy set. It errs towards yes, so that a command it matches must set its own memory limits: it matches a PATH= assignment, -i, --ignore-environment, -u or --unset whichever variable and launcher they belong to, and sudo or doas, which reset PATH."""
|
||||
return word.startswith(("PATH=", "--unset")) or word in ("-i", "--ignore-environment", "-u") or tool_name(word) in ("doas", "sudo")
|
||||
|
||||
@@ -18,9 +18,11 @@ PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""",
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Launch:
|
||||
"""A tool a simple command runs: the launchers it runs through, such as nice and run-heavy, and the words it is given."""
|
||||
"""A tool a simple command runs: the launchers it runs through, such as nice and run-heavy; the word that names the tool, as written; the words before that word; and the tool's arguments."""
|
||||
launchers: frozenset[str]
|
||||
tool: str
|
||||
word: str
|
||||
before: list[str]
|
||||
arguments: list[str]
|
||||
|
||||
|
||||
@@ -107,4 +109,4 @@ def launched(words: list[str], tools: typing.Collection[str]) -> Launch | None:
|
||||
at = next((i for i, name in enumerate(reachable) if name in tools), None)
|
||||
if at is None:
|
||||
return None
|
||||
return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at + 1:])
|
||||
return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at], words[:at], words[at + 1:])
|
||||
|
||||
@@ -23,10 +23,10 @@ USAGE = f"usage: subagent-rung [--plan] <model> <L>, L a level from 1 to {LEVELS
|
||||
|
||||
def agent_args(model: str, likelihood: int, planning: bool = False) -> str | None:
|
||||
"""The Agent tool's model and effort for the rung likelihood picks from model's cheapest rung, never below it when planning; None for a model off the ladder."""
|
||||
anchor = project_rung(model)
|
||||
if anchor is None:
|
||||
project = project_rung(model)
|
||||
if project is None:
|
||||
return None
|
||||
return (planning_rung if planning else worker_rung)(anchor, likelihood).agent_args()
|
||||
return (planning_rung if planning else worker_rung)(project, likelihood).agent_args()
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
|
||||
+1
-1
@@ -6,8 +6,8 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from release import newest_tag, tagged
|
||||
from test_env import isolated_env
|
||||
from release import newest_tag, tagged
|
||||
|
||||
|
||||
class NewestTag(unittest.TestCase):
|
||||
|
||||
@@ -3360,3 +3360,27 @@ Inherited architect, decided by:
|
||||
- Locality: `bin/rule_hook/main.py:75` `breaches_of`: the repeat-read helpers moved beside their rule in `repeat_read.py`, so `main.py` only dispatches
|
||||
- Locality: `bin/release_standing.py:177` `dated_cut`: whether a CHANGELOG heading counts as the cut is recomputed at four call sites and not kept in `LastCut`; worse here, outweighed by the places above, and where it rots first
|
||||
- Shape: `bin/loop_claude/routing.py:84` `next_route`: fewer names to learn, a denser body to trace by hand; on balance the same
|
||||
|
||||
## 2026-11-08T18:43:52Z, PR #428 at 4ab3648, against 6e0ef22
|
||||
|
||||
Ruling: better
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | better | better | same | better |
|
||||
| Inherited architect | same | better | better | same | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Shape: `bin/comprehension_history.py:127` `entries`: parses each entry once into vote_rows, score_rows, ruled_listings and scored_listings, where the older Entry kept a raw body that every consumer re-parsed under order rules ("the votes table comes first", "the first row wins")
|
||||
- Shape: `bin/comprehension_history.py:168` `newest_commit_runs`: says what it returns, where the older `newest_scored` packed the same logic into one conditional comprehension, and `scoring_runs` with its caveat is gone
|
||||
- Locality: `bin/rule_hook/rules.py:161` `unlimited_container`: asks `finds_this_docker` of the module beside run-heavy's docker, where the older version did index arithmetic on the words before docker and kept its own `resets_path`
|
||||
- Shape: `bin/model_routing/route.py:81` `route_from`: reads one format, where the older version also kept a legacy regex and `legacy_fields`
|
||||
- Shape: `bin/deploy_release/main.py:44` `main`: a thin dispatcher over `deploy.py`, `cut.py` and `forge.py`, each cohesive
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality, Shape: `bin/rule_hook/rules.py:166` `unlimited_container`: the PATH reasoning now sits in `finds_this_docker` and `resets_path` in `bin/run_heavy/capped_docker.py:39` next to the docker it describes, and `Launch` carries `word` and `before`
|
||||
- Locality, Shape: `bin/comprehension_history.py:127` `entries`: parses each entry once; worse_places reads `listing.seat` instead of splitting a label, and the tables stay separate so no ordering trap remains
|
||||
- Shape: `bin/model_routing/route.py:81` `route_from`: the legacy worker-line format is gone, so one format is left to read and keep in sync
|
||||
- Shape: `bin/review_replay/main.py:100` `main`: the old `anchor` variable is renamed `project`, matching the project's-rung vocabulary
|
||||
|
||||
+17
-3
@@ -32,6 +32,10 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the
|
||||
|
||||
2026-10-29, lilleman. Serves goal 1.3 and goal 2. `~/.claude` was this repo's development checkout, so every merge reached every session on the machine at once, its unfinished work included, while other machines took only tags. Now each machine takes only releases: what a release holds is what every session runs, and cutting one is the human's step that ships it. `deploy-release` automates README → Update. It refuses an uncommitted change to a tracked file that the new tag doesn't hold, such as a hook Claude Code wrote into `settings.json`, and a move that would drop commits no release holds; a model pick, which the clean filter drops, is no change. Valid while Claude Code reads its configuration from one directory per machine.
|
||||
|
||||
## deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
|
||||
|
||||
2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. Nobody can push to `main` on the remote, and it merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release <version>`, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request.
|
||||
|
||||
## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
|
||||
|
||||
2026-09-20, lilleman. Serves goal 1. Across six projects scored with the four seats, Locality or Self-sufficiency was the lowest dimension at every seat and Navigation at none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats.
|
||||
@@ -374,7 +378,7 @@ Valid while the archived verdicts show what a judge should return, and until a n
|
||||
|
||||
The rungs, least competent first: Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The 2026-10-29 note below took Haiku 5.5 off. They first were: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models, read 2026-10-14), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). That cut drops Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index falls among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scores it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price.
|
||||
|
||||
A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the first steps on 2026-10-16 as a guess: `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings, and `todo.md` item 170 re-tunes the steps once 50 chunks have shipped under the steps that hold today. A change to the ladder or the steps is lilleman's.
|
||||
A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. A model off the ladder routes nothing: claude runs it at the effort its settings give. A task's L steps its worker from the project's rung: 1 and 2 one down, 3 none, 4 one up. Its E + I steps its reviewers up from the project's rung: 4 or less none, 5 one up, 6 two up, 7 three up, 8 four up. A step past either end stops there. A worker errs more the more it changes and the newer that is, which L scores; review must look harder the further a defect would escape and the more it would break, which E + I scores (goals 1.1 and 1.4). Size raises L, so a large change runs its worker higher. The steps spread the values this repo's plan held when rescored on 2026-10-16, L 1 to 4 and E + I 2 to 7, so a worker on most items runs at or below the project's rung, and a review climbs only where a defect would escape far or break much. lilleman approved the steps on 2026-10-16 as a guess. `score-outcomes` reports how well L, E and I each order finished chunks by review rounds and 🔴 findings. A change to the ladder or the steps is lilleman's.
|
||||
|
||||
2026-10-21, lilleman, settling the routing calls stamped 2026-10-21T20:33:29Z: L 1 steps one rung down, not two as before, so an Opus 5.5 project runs no worker on Haiku 5.5. A delegated subagent takes the same steps, so an L 1 search moves off Haiku 5.5 too: lilleman chose one set of steps for chunk workers and subagents alike, so loop-claude, `subagent-rung` and rule-hook read one table (code health). No figure yet shows whether Sonnet 5.5 searches better than Haiku 5.5, so this costs more per search for a gain nobody has measured (goal 1.4). The calls came from loop-claude's routing figures, measured at cycle 165 over 46 chunks. Chunks started on Haiku 5.5 at max took a mean 7.8 review rounds past each pass's first, against 2.8 on Sonnet 5.5 at high, and 0.2 unfinished verdicts, against 0.1. The figures also called for moving workers off Sonnet 5.5 at high, whose chunks took 0.1 unfinished verdicts against 0.0 on Opus 5.5 at medium. lilleman kept L 2 on Sonnet 5.5, since that gap rests on one or two verdicts.
|
||||
|
||||
@@ -384,6 +388,8 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
|
||||
|
||||
2026-10-31, lilleman kept the steps, so L 1 and L 2 workers on an Opus 5.5 project stay on Sonnet 5.5 at high. The routing figures measured at 2026-10-31T02:40:55Z, over 24 chunks finished since the 2026-10-29 reset, called for moving them off it: chunks started on Sonnet 5.5 at high took a mean 0.9 review rounds past each pass's first over 15 chunks, against 0.6 over 5 on Opus 5.5 at medium. The gap is 0.3 rounds on the fewest chunks a call allows, and Sonnet's chunks did better on the other figures: 0.1 unfinished verdicts against 0.4, and 0.0 later fixes against 0.4, at a lower cost (goal 1.4).
|
||||
|
||||
2026-11-08, lilleman kept the steps, starting the re-tune with 54 `item-*` branches merged since the steps took effect, 36 of them chunks that each shipped one item scored with L, E and I, in place of waiting for 50 such chunks. Mean review rounds past each pass's first rose with L: 1.57 at L 1, 2.15 at L 2, 2.75 at L 3 and 3.50 at L 4. E + I ordered neither rounds nor 🔴 findings between 3 and 5, and no chunk scored an E + I of 7 or more, so nothing supports changing the steps for E + I 6 to 8. L 1 and L 2 share the Sonnet 5.5 rung yet differ in 🔴 (1 of 7 chunks against 6 of 12), so a 🔴 follows the item more than the rung, and nothing moves L 2. `todo.md` item 273 re-tunes the E + I steps once 10 chunks score an E + I of 6 or more.
|
||||
|
||||
Valid while the index ranks these models, and while no newer model joins the catalog.
|
||||
|
||||
## routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
|
||||
@@ -450,11 +456,19 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
|
||||
|
||||
2026-10-15, lilleman: the scores follow a researched method, built by `todo.md` items 149 and 151 after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R is L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. A task's L and E + I pick its rungs in place of R (2026-10-16, lilleman), as `routing: one ladder` records. There is no C column: what it scored beyond size, spread and novelty, which L already holds, is complexity, and that adds almost nothing once size is accounted for. There is no A column either, since the Audience says whose value the goals serve. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals mark them. Two parts are not built yet and hold once their items ship: each release fills by priority up to a capacity it states (item 149), and each project keeps 10 to 20 settled decisions to test its goals against (item 151).
|
||||
|
||||
2026-10-16, PR #283: items rank by `Score = 100 * V / (2**S + F)`. The 100 lets a score read to one decimal. V sums, over the achieve goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. A Moves column holds `1.1 by 8, 1.2 by 5`, and `rank_todo.py` derives the weights from README.md. Each achieve goal, in reading order, weighs 0.97 times the one before it, and the weights sum to 1; The worker picked 0.97, and `GOAL_STEP` sets it. lilleman wanted goals to weigh almost the same on 2026-10-18, since under the sum-reciprocal weight the goal ranked k of n achieve goals weighed (1/k) / (1 + 1/2 + … + 1/n), so the last of twelve goals weighed a twelfth of the first. The step departs from `docs/scoring-and-goals-research.md`, where sum-reciprocal weights came closest to the weights people gave. PR #319 restored the sum-reciprocal weights on a misreading of lilleman's answer, and lilleman then confirmed the step, so they stay dropped. An item that cited only maintain goals names the achieve goal it moves, or, as a defect restoring one, that maintain goal, as the defect paragraph below says. 2**S is the cost, and F is the fixed part every chunk carries that its size does not shrink: the reading before its first commit, about 130k tokens, and its review passes, so `2**S` alone overrated tiny items. F is 8, about one S 3 change, until `todo.md` item 158 measures it. A panel of three readers seated as lilleman picked the spelling: two put a Moves column holding `1.1 by 8, 1.2 by 5` first, and one put `1.1: 8` first; two chose `2**S`, since a Python reader takes `^` for XOR; all three chose one decimal of `100 * V / 2**S` over three significant digits or a log. The columns L, E and I sit right before R, which `rank_todo.py` writes from them: of three readers seated as lilleman, two ranked that order first, since a reader meets each level before the R it builds and R sits beside S, and the third ranked it second, after an order with S before the levels. A table in the old shape still ranks by the formula and weights it states, and ranking it says to reshape it, so no other project's commits stop; reshaping it is that project's only work until done, as `CLAUDE.md` → "Working loop" says. The old shape's ranking is valid until `todo.md` item 156.
|
||||
2026-10-16, PR #283: items rank by `Score = 100 * V / (2**S + F)`. The 100 lets a score read to one decimal. 2**S is the cost. V sums, over the achieve goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. A Moves column holds `1.1 by 8, 1.2 by 5`. An item that cites only maintain goals names the achieve goal it moves, or, as a defect restoring one, that maintain goal, as the defect paragraph below says.
|
||||
|
||||
2026-10-18, lilleman: `rank_todo.py` derives the goal weights from README.md. Each achieve goal, in reading order, weighs 0.97 times the one before it, and the weights sum to 1; `GOAL_STEP` sets the 0.97. lilleman wanted goals to weigh almost the same, since under the sum-reciprocal weight the goal ranked k of n achieve goals weighed (1/k) / (1 + 1/2 + … + 1/n), so the last of twelve goals weighed a twelfth of the first. The step departs from `docs/scoring-and-goals-research.md`, where sum-reciprocal weights came closest to the weights people gave.
|
||||
|
||||
2026-11-08, item 158, replacing lilleman's F of 8 from PR #283. Serves goal 1.4: this repo's plan sets F, the cost every chunk pays whatever its size, to 32, which is `2**5`, one S 5 change. F is the fixed cost divided by the cost of one unit of `2**S`. The fit is least squares over the 10 chunks in this repo's loop-claude archive that shipped an item, counting only those `score-outcomes` finds with an S. A chunk's cost is the new input tokens (input plus cache creation) and the output tokens of its worker and subagents, leaving out cache reads and judge runs. It comes to about 399k tokens fixed plus 10.9k per unit of `2**S`, so F is about 36 (R² 0.24); output tokens alone give 24 (R² 0.35). 32 sits between them. The 10 chunks' (S, thousand tokens) are (1, 405), (2, 446), (2, 442), (2, 368), (2, 294), (2, 130), (3, 1027), (4, 733), (5, 754) and (5, 599). The fit holds loosely: it covers S 1 to 5 and no larger chunk, 10 points scatter widely, and a chunk that shipped several items counts whole against the S of the item its first route names. Lines changed explain little of the tokens (R² 0.07), so the fit uses S, not lines. Hours do not fit: the worker's active time, each gap capped at 10 minutes, has a median of 0.29 hours whatever S (R² 0.01), so hours don't change F. The formula charges each item the whole F, though a chunk that bundles tiny items pays it once, so such an item ranks lower than its real cost warrants. `rank_todo.py --help` keeps 8 in its example, which shows a valid file's shape, not this plan's F.
|
||||
|
||||
2026-10-16, PR #283: a panel of three readers seated as lilleman picked the spelling. Two put a Moves column holding `1.1 by 8, 1.2 by 5` first, and one put `1.1: 8` first. Two chose `2**S`, since a Python reader takes `^` for XOR. All three chose one decimal of `100 * V / 2**S` over three significant digits or a log. The columns L, E and I sit right before R, which `rank_todo.py` writes from them: of three readers seated as lilleman, two ranked that order first, since a reader meets each level before the R it builds and R sits beside S, and the third ranked it second, after an order with S before the levels.
|
||||
|
||||
2026-10-16, PR #283: a table in the old shape, with C, A, G and Goals columns in place of L, E, I and Moves, still ranks by the formula and weights it states, and ranking it says to reshape it, so no other project's commits stop. Reshaping it is that project's only work until done, as `CLAUDE.md` → "Working loop" says. The old shape's ranking is valid until `todo.md` item 156.
|
||||
|
||||
2026-10-16, lilleman, answering the review of PR #283. An item that restores a maintain goal the project breaks today is a defect: exempt as `defect`. Its Moves name that maintain goal and how much of it is broken, and the goal weighs as the heaviest achieve goal, since a broken maintain goal outranks any achieve goal. Every defect ranks by its score, so a trivial one waits behind valuable work. Only questions and then security findings rank first in their release: a question's answer may change other items, and a question waits for the human anyway, so ranking it first delays no chunk. An item names the most specific goal it moves, and a parent only for a move none of its sub-goals covers, so a sub-goal's move does not count twice; `rank_todo.py` refuses a goal named beside its own sub-goal. Each project reshapes its own `todo.md`; `CLAUDE.md` → "Working loop" makes the reshape the only work until done, as it makes writing missing premises. An item that makes this project easier to read moves code health, as the paragraph below says, and goal 1.4, since reading cost is measured in tokens per chunk.
|
||||
|
||||
2026-10-18, lilleman. Serves goal 1.1: every project shares one achieve goal, code health, which `CLAUDE.md` → "Shared goal" states once and which replaces each project's own readability goal. It ranks first among a project's achieve goals, since lilleman rates it very important while the comprehension panel's overall is under 7.0. While that overall is under 7.0, or no scoring run has measured the project, it weighs four times its weight at 7.0 or above, as `UNDER_FLOOR` sets. The overall is the mean of the overall means of every scoring run on the newest scored commit in `docs/comprehension-history.md`, as `newest_scored` finds them. Two runs of one head measure it twice, and the newest alone would let their noise flip the weight: 7.13 and 6.88 on one head of another project would have. The review of PR #324 raised this choice. Weighing code health four times as much leaves the other achieve goals' weights as they are. So crossing 7.0 changes only the scores of the items that move code health, and of the defects, since a broken maintain goal weighs as the heaviest achieve goal. `larv-review record-scoring` re-ranks `todo.md` after it appends a run. A project that opts out of the comprehension check voids the goal, as `review: a project decision may opt every chunk out …` records. A README voids the goal with `**Void:** code health, since <reason>.` under `## Goals`, and an item's Moves cell names it as in `code health by 6`. A panel of three readers seated as lilleman picked both 3-0: `code health` over `code`, `health`, `C` and `0`, and the bold `Void:` line over a sentence under `## Goals` or a line under `## Audience`. `score-outcomes` counts the counter-signal's misread findings per chunk, as `review: a reviewer under …` records. Valid while the comprehension panel's overall is how a project measures how hard it is to read.
|
||||
2026-10-18, lilleman. Serves goal 1.1: every project shares one achieve goal, code health, which `CLAUDE.md` → "Shared goal" states once and which replaces each project's own readability goal. It ranks first among a project's achieve goals, since lilleman rates it very important while the comprehension panel's overall is under 7.0. While that overall is under 7.0, or no scoring run has measured the project, it weighs four times its weight at 7.0 or above, as `UNDER_FLOOR` sets. The overall is the mean of the overall means of every scoring run on the newest scored commit in `docs/comprehension-history.md`, as `newest_commit_runs` finds them. Two runs of one head measure it twice, and the newest alone would let their noise flip the weight: 7.13 and 6.88 on one head of another project would have. The review of PR #324 raised this choice. Weighing code health four times as much leaves the other achieve goals' weights as they are. So crossing 7.0 changes only the scores of the items that move code health, and of the defects, since a broken maintain goal weighs as the heaviest achieve goal. `larv-review record-scoring` re-ranks `todo.md` after it appends a run. A project that opts out of the comprehension check voids the goal, as `review: a project decision may opt every chunk out …` records. A README voids the goal with `**Void:** code health, since <reason>.` under `## Goals`, and an item's Moves cell names it as in `code health by 6`. A panel of three readers seated as lilleman picked both 3-0: `code health` over `code`, `health`, `C` and `0`, and the bold `Void:` line over a sentence under `## Goals` or a line under `## Audience`. `score-outcomes` counts the counter-signal's misread findings per chunk, as `review: a reviewer under …` records. Valid while the comprehension panel's overall is how a project measures how hard it is to read.
|
||||
|
||||
2026-10-15, lilleman. Serves goal 1.4: loop-claude routes a chunk's first cycle on the item the chunk takes (`routing: a chunk's worker runs on the rung its item's L picks`). An item lists the items that must be done before it starts in a Blocked by column, and `rank_todo.py` ranks each blocker above every item it blocks. The table's order is `todo.md`'s only order: `rank_todo.py` fails on text beside the table under `## Items`, since a prose order there, "Release 0.3.0 takes items 125, 114 and 124 first", contradicted the table and loop-claude could not read it. A decision that wants an order sets the scores instead. An item waits while it is marked `question` or a blocker of it is still in the table, whatever the rows' order, so a release's first row that does not wait is the item a chunk takes. A blocker the table no longer holds was finished or deleted, and is dropped, so the cell shows what still blocks. A panel of three readers seated as lilleman picked the spelling: two ranked "Blocked by" first, as the cell lists only what still blocks, and all three chose bare IDs such as `12, 14` in a column right after Release, read before the tagline and kept apart from the scores. `rank_todo.py` adds the column to a table without it. The tools read cells by column name, so a later column leaves a reader on an older release working; `rank_todo.py`, which writes every column, fails on one it does not know rather than drop it.
|
||||
|
||||
|
||||
@@ -974,3 +974,148 @@ Read most (opens and searches):
|
||||
- `AGENTS.md` 1
|
||||
- `CHANGELOG.md` 1
|
||||
- `bin/claude_code/__init__.py` 1
|
||||
|
||||
## Reading cost, chunk 65835030caa6, finished 2026-11-08T10:06:31Z
|
||||
|
||||
168681 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/chunk_preflight/test_chunk_preflight.py` 6
|
||||
- `bin/loop_claude/loop/main.py` 5
|
||||
- `AGENTS.md` 2
|
||||
- `README.md` 2
|
||||
- `todo.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
- `bin/chunk_preflight/facts.py` 1
|
||||
- `bin/chunk_preflight/gathered.py` 1
|
||||
- `bin/chunk_preflight/main.py` 1
|
||||
- `bin/loop_claude/cycle/prompts.py` 1
|
||||
|
||||
## Reading cost, chunk e3e09719dd25, finished 2026-11-08T10:18:57Z
|
||||
|
||||
57098 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/run_heavy/test_run_heavy.py` 4
|
||||
- `CHANGELOG.md` 3
|
||||
- `bin/rule_hook/rules.py` 3
|
||||
- `bin/shell_command.py` 3
|
||||
- `docs/decisions.md` 3
|
||||
- `todo.md` 3
|
||||
- `README.md` 2
|
||||
- `AGENTS.md` 1
|
||||
- `bin/rule_hook/test_rule_hook.py` 1
|
||||
- `bin/run_heavy/capped_docker.py` 1
|
||||
|
||||
## Reading cost, chunk 84fca41a7ef4, finished 2026-11-08T18:02:06Z
|
||||
|
||||
139686 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 4
|
||||
- `bin/score_outcomes/main.py` 3
|
||||
- `bin/score_outcomes/results.py` 3
|
||||
- `bin/branch_chunks/cut.py` 2
|
||||
- `bin/todo_table.py` 2
|
||||
- `AGENTS.md` 1
|
||||
- `bin/branch_chunks/read.py` 1
|
||||
- `bin/loop_claude/loop/main.py` 1
|
||||
- `bin/routing_figures/archive.py` 1
|
||||
- `bin/score-outcomes` 1
|
||||
|
||||
## Reading cost, chunk cbe1c9d0886f, finished 2026-11-08T18:11:52Z
|
||||
|
||||
70801 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 3
|
||||
- `bin/loop_claude/loop/main.py` 3
|
||||
- `bin/loop_claude/test_loop_claude.py` 3
|
||||
- `bin/model_routing/route.py` 3
|
||||
- `bin/routing_figures/test_routing_figures.py` 3
|
||||
- `bin/model_routing/ladder.py` 2
|
||||
- `todo.md` 2
|
||||
- `AGENTS.md` 1
|
||||
- `docs/decisions.md` 1
|
||||
|
||||
## Reading cost, chunk df74fc6177be, finished 2026-11-08T18:19:56Z
|
||||
|
||||
56035 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 7
|
||||
- `AGENTS.md` 2
|
||||
- `README.md` 2
|
||||
- `bin/judge_replay/main.py` 2
|
||||
- `bin/review_replay/main.py` 2
|
||||
- `bin/subagent_rung/main.py` 2
|
||||
- `CHANGELOG.md` 1
|
||||
- `docs/decisions.md` 1
|
||||
|
||||
## Reading cost, chunk 9fd7519bd086, finished 2026-11-08T18:24:16Z
|
||||
|
||||
56261 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/decisions.md` 7
|
||||
- `todo.md` 5
|
||||
- `AGENTS.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
- `README.md` 1
|
||||
|
||||
## Reading cost, chunk efca40024e84, finished 2026-11-08T18:44:32Z
|
||||
|
||||
87773 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/comprehension-history.md` 8
|
||||
- `bin/comprehension_history.py` 7
|
||||
- `bin/larv_review/test_larv_review.py` 6
|
||||
- `todo.md` 4
|
||||
- `CHANGELOG.md` 1
|
||||
- `README.md` 1
|
||||
- `bin/larv_review/agreement.py` 1
|
||||
- `bin/markdown_text.py` 1
|
||||
|
||||
## Reading cost, chunk a5564ebb47d2, finished 2026-11-08T19:08:11Z
|
||||
|
||||
123230 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 13
|
||||
- `bin/routing_figures/test_routing_figures.py` 10
|
||||
- `docs/decisions.md` 6
|
||||
- `AGENTS.md` 5
|
||||
- `bin/loop_claude/test_loop_claude.py` 5
|
||||
- `bin/loop_claude/loop/routing_check.py` 4
|
||||
- `bin/routing_figures/archive.py` 4
|
||||
- `README.md` 3
|
||||
- `bin/routing_figures/render.py` 3
|
||||
- `CHANGELOG.md` 2
|
||||
|
||||
## Reading cost, chunk 3938cca80252, finished 2026-11-08T19:16:01Z
|
||||
|
||||
86301 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 8
|
||||
- `docs/decisions.md` 5
|
||||
- `CHANGELOG.md` 3
|
||||
- `README.md` 3
|
||||
- `bin/routing_figures/chunk.py` 3
|
||||
- `AGENTS.md` 2
|
||||
- `bin/branch_chunks/cut.py` 2
|
||||
- `bin/routing_figures/archive.py` 2
|
||||
- `bin/score_outcomes/main.py` 2
|
||||
- `bin/branch_chunks/read.py` 1
|
||||
|
||||
## Reading cost reset, 2026-11-08T19:18:18Z
|
||||
|
||||
@@ -2,97 +2,74 @@
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = 100 * V / (2**S + 8)`
|
||||
`Score = 100 * V / (2**S + 32)`
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 272`
|
||||
`Next ID = 276`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 271 | 0.6.0 | | owner | **Have `deploy-release --cut` cut the next release once it holds no item, through a PR it opens, waits for and merges, then tag and deploy it, and stop with git's or the forge's reason where a step fails.** | 4 | 2 | 3 | 7 | 5 | 1.5 by 6 | 2.3 |
|
||||
| 1 | 0.7.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
|
||||
| 229 | 0.7.0 | | | **Keep the rule for which commands reach run-heavy's docker beside that docker in `bin/run_heavy/capped_docker.py`, so rule-hook's `docker-run-memory` asks it instead of repeating run-heavy's PATH rules.** | 2 | 1 | 3 | 4 | 2 | code health by 3 | 18.0 |
|
||||
| 170 | 0.7.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.9 |
|
||||
| 218 | 0.7.0 | 170 | | **Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only JSON worker lines.** | 1 | 2 | 1 | 2 | 1 | code health by 2 | 14.4 |
|
||||
| 219 | 0.7.0 | | | **Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it.** | 1 | 1 | 3 | 3 | 2 | code health by 2 | 12.0 |
|
||||
| 224 | 0.7.0 | | | **Split `docs/decisions.md` → `todo.md: one table of items, …`'s 420-word scoring paragraph into one paragraph per choice, and drop the sentences that tell how the goal weights changed.** | 1 | 1 | 1 | 1 | 2 | code health by 2 | 12.0 |
|
||||
| 123 | 0.7.0 | | | **Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.** | 2 | 1 | 2 | 3 | 5 | code health by 5, 1.4 by 5 | 11.0 |
|
||||
| 139 | 0.7.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | code health by 5, 1.4 by 5 | 11.0 |
|
||||
| 158 | 0.7.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 |
|
||||
| 215 | 0.7.0 | | | **Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.** | 2 | 1 | 3 | 4 | 3 | code health by 2 | 9.0 |
|
||||
| 237 | 0.7.0 | | principle | **Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.** | 2 | 1 | 2 | 3 | 3 | code health by 2 | 9.0 |
|
||||
| 242 | 0.7.0 | | principle | **Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.** | 2 | 1 | 1 | 2 | 3 | code health by 2 | 9.0 |
|
||||
| 49 | 0.7.0 | | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 6 | 8.4 |
|
||||
| 263 | 0.7.0 | | | **Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 6, 1.5 by 2 | 8.1 |
|
||||
| 262 | 0.7.0 | | | **Let a worker take its own recommendation on a choice no rule reserves for the human, record it in the item or a decision, and interrupt only for a reserved choice or an ask it has no recommendation for.** | 3 | 2 | 3 | 6 | 4 | 1.2 by 7, 1.5 by 5 | 8.0 |
|
||||
| 105 | 0.7.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 8.0 |
|
||||
| 162 | 0.7.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 7.8 |
|
||||
| 175 | 0.7.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 7.8 |
|
||||
| 230 | 0.7.0 | | | **Have larv-review file one ambitious refactor item, aimed at the lowest-scoring dimension, whenever a scoring run leaves any score under 7.0, so such a project always holds a plan item meant to reach 7.0.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 7, 1.2 by 4 | 7.7 |
|
||||
| 184 | 0.7.0 | | | **Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 |
|
||||
| 221 | 0.7.0 | | | **Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.** | 3 | 1 | 3 | 5 | 5 | code health by 4 | 7.2 |
|
||||
| 116 | 0.7.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 7.0 |
|
||||
| 203 | 0.7.0 | | | **Make `bin/repo_checks` fail on a `todo.md` citation of a `docs/decisions.md` title that no heading holds.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 5 | 7.0 |
|
||||
| 113 | 0.7.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 6.8 |
|
||||
| 112 | 0.7.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 6.3 |
|
||||
| 124 | 0.7.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 5, 1.4 by 3 | 5.7 |
|
||||
| 81 | 0.7.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 5.6 |
|
||||
| 173 | 0.7.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 |
|
||||
| 101 | 0.7.0 | | principle | **Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 12 | 0.7.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 4.2 |
|
||||
| 102 | 0.8.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 4.2 |
|
||||
| 135 | 0.8.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 |
|
||||
| 270 | 0.8.0 | | | **Compare each review pass's share of chunks that go to a second round, and move each check stability repeats across chunks into the worker's pre-review gate.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 2, 1.4 by 2 | 4.1 |
|
||||
| 171 | 0.8.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 4.0 |
|
||||
| 196 | 0.8.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 4.0 |
|
||||
| 260 | 0.8.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 4.0 |
|
||||
| 269 | 0.8.0 | | | **Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 4.0 |
|
||||
| 267 | 0.8.0 | | | **Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.** | 2 | 1 | 3 | 4 | 2 | 1.5 by 3 | 3.9 |
|
||||
| 68 | 0.8.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 3.5 |
|
||||
| 181 | 0.8.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 192 | 0.8.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 193 | 0.8.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 194 | 0.8.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 202 | 0.8.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 268 | 0.8.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 3 | 3.3 |
|
||||
| 77 | 0.8.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 3.2 |
|
||||
| 4 | 0.8.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 3.2 |
|
||||
| 187 | 0.8.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 3.0 |
|
||||
| 264 | 0.8.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 3.0 |
|
||||
| 266 | 0.8.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 3.0 |
|
||||
| 149 | 0.8.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 3.0 |
|
||||
| 165 | 0.8.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 2.9 |
|
||||
| 151 | 0.8.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 2.9 |
|
||||
| 156 | 0.8.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 2.8 |
|
||||
| 201 | 0.8.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 2.6 |
|
||||
| 5 | 0.8.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 2.5 |
|
||||
| 155 | 0.8.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 6 | 2.4 |
|
||||
| 51 | 0.8.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 2.1 |
|
||||
| 169 | 0.8.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.1 |
|
||||
| 265 | 0.8.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 1.9 |
|
||||
| 174 | 0.8.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 1 | 1.1 by 1 | 1.7 |
|
||||
| 52 | 0.8.0 | | principle | **Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4, 1.4 by 2 | 1.4 |
|
||||
| 197 | 0.8.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 1.3 |
|
||||
| 221 | 0.7.0 | | | **Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.** | 3 | 1 | 3 | 5 | 5 | code health by 4 | 4.5 |
|
||||
| 124 | 0.7.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 5, 1.4 by 3 | 4.2 |
|
||||
| 262 | 0.7.0 | | | **Let a worker take its own recommendation on a choice no rule reserves for the human, record it in the item or a decision, and interrupt only for a reserved choice or an ask it has no recommendation for.** | 3 | 2 | 3 | 6 | 4 | 1.2 by 7, 1.5 by 5 | 4.0 |
|
||||
| 230 | 0.7.0 | | | **Have larv-review file one ambitious refactor item, aimed at the lowest-scoring dimension, whenever a scoring run leaves any score under 7.0, so such a project always holds a plan item meant to reach 7.0.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 7, 1.2 by 4 | 3.8 |
|
||||
| 215 | 0.7.0 | | | **Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.** | 2 | 1 | 3 | 4 | 3 | code health by 2 | 3.6 |
|
||||
| 237 | 0.7.0 | | principle | **Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.** | 2 | 1 | 2 | 3 | 3 | code health by 2 | 3.6 |
|
||||
| 242 | 0.7.0 | | principle | **Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.** | 2 | 1 | 1 | 2 | 3 | code health by 2 | 3.6 |
|
||||
| 113 | 0.7.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 3.4 |
|
||||
| 263 | 0.7.0 | | | **Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 6, 1.5 by 2 | 3.2 |
|
||||
| 162 | 0.7.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 3.1 |
|
||||
| 105 | 0.7.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 2.7 |
|
||||
| 175 | 0.7.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 |
|
||||
| 112 | 0.7.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 2.5 |
|
||||
| 116 | 0.7.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 2.3 |
|
||||
| 101 | 0.7.0 | | principle | **Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 2.1 |
|
||||
| 12 | 0.7.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 2.1 |
|
||||
| 81 | 0.7.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 1.9 |
|
||||
| 173 | 0.7.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 1.8 |
|
||||
| 272 | 0.7.0 | | owner | **Make `deploy-release --cut` say when each step finishes, end on one line saying the release is cut and `~/.claude` is on it, and delete the merged release branch.** | 1 | 1 | 1 | 1 | 2 | 1.5 by 3 | 1.3 |
|
||||
| 274 | 0.7.0 | | | **Let an item name a maintain goal it raises confidence in, such as a test leg that guards it, and weigh that move against the achieve goals in `bin/rank_todo.py`.** | 2 | 2 | 3 | 5 | 4 | 1 by 3 | 1.1 |
|
||||
| 275 | 0.7.0 | | | **Make the `Main` tests of `judge-replay` and `review-replay` fail when the replays ignore the project's model, its lowest worker rung or the round's checkout.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2 | 0.9 |
|
||||
| 77 | 0.8.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 |
|
||||
| 273 | 0.8.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 |
|
||||
| 171 | 0.8.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 2.0 |
|
||||
| 149 | 0.8.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 1.8 |
|
||||
| 165 | 0.8.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 1.8 |
|
||||
| 151 | 0.8.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 1.8 |
|
||||
| 68 | 0.8.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 1.8 |
|
||||
| 102 | 0.8.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 1.7 |
|
||||
| 135 | 0.8.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 1.7 |
|
||||
| 270 | 0.8.0 | | | **Compare each review pass's share of chunks that go to a second round, and move each check stability repeats across chunks into the worker's pre-review gate.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 2, 1.4 by 2 | 1.6 |
|
||||
| 5 | 0.8.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.6 |
|
||||
| 156 | 0.8.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.4 |
|
||||
| 196 | 0.8.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 260 | 0.8.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 269 | 0.8.0 | | | **Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 51 | 0.8.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.3 |
|
||||
| 268 | 0.8.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 3 | 1.3 |
|
||||
| 201 | 0.8.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.3 |
|
||||
| 267 | 0.8.0 | | | **Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.** | 2 | 1 | 3 | 4 | 2 | 1.5 by 3 | 1.3 |
|
||||
| 4 | 0.8.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 1.3 |
|
||||
| 187 | 0.8.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 264 | 0.8.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 266 | 0.8.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 52 | 0.8.0 | | principle | **Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4, 1.4 by 2 | 1.0 |
|
||||
| 181 | 0.8.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 192 | 0.8.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 193 | 0.8.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 194 | 0.8.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 202 | 0.8.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 265 | 0.8.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 1.0 |
|
||||
| 169 | 0.8.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 0.8 |
|
||||
| 174 | 0.8.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 1 | 1.1 by 1 | 0.5 |
|
||||
| 197 | 0.8.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 0.4 |
|
||||
|
||||
## Details
|
||||
|
||||
### 271. Have `deploy-release --cut` cut the next release once it holds no item, through a PR it opens, waits for and merges, then tag and deploy it, and stop with git's or the forge's reason where a step fails.
|
||||
|
||||
`main` on the remote is now protected: nobody can push to it, and it merges only by fast-forward, with no merge commits. So README → Release, which commits on `main`, tags and pushes both, no longer works.
|
||||
|
||||
`deploy-release --cut` runs in the development clone, `~/code/claude-config`. It works out the next release as `chunk-preflight` does, through `bin/release_standing.py`. It fails, changing nothing, unless that release holds no item in `todo.md`, its release review has landed and changes are unreleased. The version is that release: the tool doesn't choose one.
|
||||
|
||||
It then makes the branch `release-<version>` off a freshly fetched `origin/main`, renames `## Unreleased` in `CHANGELOG.md` to the version, and commits `Cut release <version>`. It pushes the branch and opens a PR, with `tea` on a Gitea remote and `gh` on a GitHub one, as `forge_of` in `bin/chunk_preflight/choices.py` tells them apart. It waits for the PR's checks, where there are any, and merges the PR fast-forward only. Then it fetches, tags the merged commit `v<version>`, annotated with the message `Cut release <version>`, and pushes only the tag. Last, it moves `~/.claude` to that tag, as a bare `deploy-release` does.
|
||||
|
||||
Where the PR can't merge, a check fails, the tag already exists on another commit or any step fails, it stops with git's or the forge's reason. It leaves the PR and the branch as they are. A rerun continues where the last run stopped: it finds an open or merged PR for the branch, and a tag already on the merged commit.
|
||||
|
||||
The human runs it, since releases stay theirs; the publishing credentials are theirs too and out of scope. A bare `deploy-release` keeps moving `~/.claude` to the newest tag, and both keep refusing an uncommitted change to a tracked file. The first cut runs from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0.
|
||||
|
||||
Write the tests first in `bin/deploy_release/test_deploy_release.py`, taking expected values from this item. Update README → Release, Update and Tools, `deploy-release --help`, and `CHANGELOG.md`. Record the choice under a new title in `docs/decisions.md` and list it in `AGENTS.md`. Where the change touches README → Tools' map of `bin/`'s shared modules, which a comprehension seat found hard, make it easier to read, such as naming what `deploy_release` imports.
|
||||
|
||||
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
|
||||
|
||||
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
|
||||
@@ -101,77 +78,19 @@ It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost
|
||||
|
||||
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3).
|
||||
|
||||
### 229. Keep the rule for which commands reach run-heavy's docker beside that docker in `bin/run_heavy/capped_docker.py`, so rule-hook's `docker-run-memory` asks it instead of repeating run-heavy's PATH rules.
|
||||
### 221. Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.
|
||||
|
||||
The paired ruling of PR #373 found Locality worse with all four seats, and named `bin/rule_hook/rules.py` `unlimited_container` and `resets_path` first. rule-hook exempts a `docker run` under run-heavy only where run-heavy's docker will run it: docker named bare, with PATH left as run-heavy set it. That knowledge of how `run_heavy/main.py` `capping` puts `PATH_ENTRY` first lives in rule-hook, so a change to run-heavy silently changes what the rule lets through. Move the predicate, with its words-before-docker index arithmetic made plain, next to `PATH_ENTRY`, and have the rule call it. Make the two places easier to read, as the seats named them.
|
||||
"Validate data and build DTOs as early as possible", in `principles/technical-principles.md`, raised 🟢 by the principles audit of item 210's PR. `read_transcript` (`bin/claude_code/transcript.py:16`) returns raw `dict`s, so each consumer, such as `render` beside it and `since_step` in `bin/loop_claude/escalation_mark.py`, calls the helpers in `bin/claude_code/entries.py` (`human_text`, `loop_text`, `assistant_parts`, `tool_call`) to work out an entry's kind again. Parse each line once into types such as a human turn, a loop-claude prompt and an assistant turn, and have every consumer of `claude_code.entries` under `bin/` take those types. The change touches the escalation mark, which the comprehension seats found hard at `bin/loop_claude/cycle/judge.py:153` `escalation_mark` before item 210 moved it: make `since_step` in `bin/loop_claude/escalation_mark.py`, and `Grounds.since_step` and `judge_prompt` in `bin/loop_claude/cycle/judge.py`, easier to read.
|
||||
|
||||
### 170. Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.
|
||||
### 124. Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.
|
||||
|
||||
`docs/decisions.md` → `routing: one ladder…` calls the steps a first guess. Start this item once 50 chunks have merged since PR #339 set today's steps, each shipping one item scored with L, E and I. By 2026-10-23, 15 had: those of items 117, 126, 122, 207, 130, 154, 186, 66, 121, 213, 137, 212, 214, 210 and 216. Then read `score-outcomes`' rank correlations for L, E and I and the routed-chunks table of `routing-figures.md`, and propose new steps to lilleman, whose call they are.
|
||||
|
||||
### 218. Drop `LEGACY_WORKER` from `bin/model_routing/route.py`, so `route_from` reads only JSON worker lines.
|
||||
|
||||
PR #357 archived the route as JSON on each `Worker:` line, and kept `LEGACY_WORKER` to read the lines an older loop-claude wrote as sentences. The routing figures still count chunks whose archive holds such lines: 51 when PR #357 shipped, every chunk finished after the reset of 2026-10-21T22:16:41Z. A chunk that changes the routing steps has a `Reset` appended to `routing-calls-raised.md`, after which the figures count only chunks whose worker lines are JSON. This item waits for item 170 whether or not 170 changes the steps, as lilleman decided on 2026-10-23. Before starting, check that `routing-calls-raised.md` holds a `Reset` stamped after PR #357's merge; where none does, ask lilleman whether to append one. Delete `LEGACY_WORKER`, `legacy_fields`, the tests that read sentences (in `bin/loop_claude/test_loop_claude.py` and `bin/routing_figures/test_routing_figures.py`), and the sentence on them in "loop-claude --help". Reword `route_from`'s docstring, and the comment at `Rung.__str__` in `bin/model_routing/ladder.py`, which gives the old lines as a reason `parse` must keep reading that spelling.
|
||||
|
||||
### 219. Name the project's rung `project` in `bin/judge_replay/main.py`, `bin/subagent_rung/main.py` and `bin/review_replay/main.py`, in place of `anchor`, as `bin/model_routing/ladder.py` and `bin/loop_claude` name it.
|
||||
|
||||
Item 172 renamed `anchor` to `project` across `bin/loop_claude`, after release 0.3.0's inherited architect named `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: "the project's rung is also called anchor". Three tools outside it still call the same rung `anchor`: `bin/judge_replay/main.py:54` (`anchor = arguments_or_exit(...)`, a `Rung` parsed from the model argument), `bin/subagent_rung/main.py:26` (`anchor = project_rung(model)`), and `bin/review_replay/main.py:74`, `:100` and `:180`, with `findings_found`'s docstring. While the name differs between tools, a reader works out each time that the two are one rung. The rename keeps behaviour. `bin/score_outcomes/anchors.py` uses `anchor` for score anchors, a different thing, and keeps the name.
|
||||
|
||||
### 224. Split `docs/decisions.md` → `todo.md: one table of items, …`'s 420-word scoring paragraph into one paragraph per choice, and drop the sentences that tell how the goal weights changed.
|
||||
|
||||
Found by the prose review of PR #368. The paragraph that opens `2026-10-16, PR #283: items rank by` covers the formula, F, the goal weights, the panels' spelling picks, the column order and the old shape, and grew a sentence per chunk. A reader looking for what F is, or why `2**S`, searches all of it. Its sentences on how the goal weights changed over time, such as the one on PR #319, describe past states, not what holds; git history keeps them.
|
||||
|
||||
### 123. Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.
|
||||
|
||||
Three seats of PR #257's scoring run named `bin/comprehension_history.py:106` `latest_places`; the logic it rests on is `:114` `worse_places` and `:126` `worse_votes`. They regex the markdown the module writes. `worse_votes` keeps a seat's first row through `setdefault`, because the votes table comes first. `worse_places` recovers the seat with `label.split(",")[0]`. `Entry` still holds scoring seats' places for rulings recorded before PR #255. Release 0.3.0's seats named near-synonyms left from before PR #255: `:150` `scoring_runs`, "near-synonyms scored and scoring_runs differ only on a ruling from before PR #255" (Maintainability senior), `:130` `newest_scored`, "four near-identical names over two concepts", and `:159` `scored`. Make these functions easier to read.
|
||||
|
||||
### 139. Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.
|
||||
|
||||
The paired ruling on PR #265 ruled worse. Make these places easier to read: `measure.py` `measured` and `render` (token attribution, subagent rungs, round counting, calls and rendering in one module; `measured`, `Measured` and `measure_archive` side by side); `calls` with `archive.py` `raised` and `last_measured`, where a call's identity is its sentence and the measured cycle is read back from rendered markdown; and `Reports.searches`, which holds characters, not searches.
|
||||
|
||||
### 158. Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.
|
||||
|
||||
F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk costs more than its size: the worker reads about 130k tokens before its first commit whatever the item, and every chunk takes its review passes. Fit cost against 2**S from the finished chunks `score-outcomes` measures, in the same units `2**S` counts, and say in `docs/decisions.md` → `todo.md: …` how far the fit holds. A chunk bundling tiny items shares F between them.
|
||||
|
||||
### 215. Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.
|
||||
|
||||
Release 0.3.0's Mid A (PR #324 at c713910) named `bin/loop_claude/loop/reload.py:43` `decoded_as`: "a generic decoder with two sentinels and a duck-typed fits hook defined on Route". This lowers Shape: `decoded_as` is generic over any type, yet `decode_handed` calls it with one dataclass, `LoopRun`. Keep what it does today: a field added since the running script started may be missing, and a handed dataclass holding a field its `RETIRED` names decodes as None where its type allows None, and is rejected otherwise. `LoopRun.items_taken_in`, a tuple of item IDs, decodes only from a JSON array of integers. Make `decoded_as` easier to read.
|
||||
|
||||
### 237. Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.
|
||||
|
||||
Found by the principles audit of PR #376. "About seven things per level" in `principles/technical-principles.md`: `judge` takes nine parameters and `judge_once` eight, past the four or five for things that act on each other, with no recorded reason. Both take root, task, premises, records, entries, escalated_at, rung and effects, which one record could carry.
|
||||
|
||||
### 242. Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.
|
||||
|
||||
"Tests" in `principles/technical-principles.md`. The principles audit of PR #380 found test bodies that loop over their cases without `subTest`, some checking several behaviours at once: `bin/judge_replay/test_judge_replay.py:38`, `:139`, `:176`; `bin/loop_claude/test_loop_claude.py:590`; `bin/machine_load/test_machine_load.py:19`, `:31`; `bin/rule_hook/test_rule_hook.py:480`; `bin/subagent_rung/test_subagent_rung.py:32`, `:43`, `:45`; `bin/test_settings_filter.py:28`; `bin/test_statusline.py:102`. The first failing case stops the loop, and without a message the failure doesn't say which case broke. Split the tests that check several behaviours at once, `test_judge_replay.py:176` and `test_subagent_rung.py:43-46`, into one test per behaviour ("One behaviour per test").
|
||||
|
||||
### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.
|
||||
|
||||
DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy.
|
||||
|
||||
### 263. Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open.
|
||||
|
||||
43 of the 175 chunks with an interrupt asked two or more times, and hold 123 of the archive's 255 interrupts (2026-11-08). Examples: adf-codec asked 4 times between 19:04 and 20:54 on 2026-11-04, 3 of them on item 167; bender-infra asked 3 times on 2026-10-21 whether to grant principles and stability one more round; fejkdata asked twice in 4 minutes on 2026-10-12 to cut 0.1.0. The judge already reads the transcript (`docs/decisions.md:45`), so it sees the earlier answer. The change touches `bin/loop_claude/cycle/judge.py` `quotes_checked` and `grounded`; make them easier to read, as the seats named them.
|
||||
Shape scored 6.25 in PR #257's run. `bin/` held about 30 entries then: 6 launchers, 6 tool packages, 3 shared packages and 15 root modules. Two root modules are tools (`rank_todo.py`, `statusline.py`) and 13 are shared libraries, and nothing in the layout tells them apart; only README's import-root paragraph maps them. Candidate packages: git running and parsing, the todo table with `rank_todo.py`'s formula language and goal weighing, and the comprehension history with round titles. `rank_todo.py` keeps its path, which every project's rules name. The `.gitignore` allowlist and README follow the move. Release 0.3.0's inherited architect named `bin/git_repo.py:8` `git` in the rerun (PR #324 rerun at c713910): "bin/'s root holds about 43 entries, with 13 loose modules … not grouped by purpose". In the first run (PR #324 at c713910) it named `bin/rank_todo.py:196` `read_all`: "a 658-line library as well as a tool, imported by rule_hook and larv_review". Make `git` and `read_all` easier to read.
|
||||
|
||||
### 262. Let a worker take its own recommendation on a choice no rule reserves for the human, record it in the item or a decision, and interrupt only for a reserved choice or an ask it has no recommendation for.
|
||||
|
||||
On 2026-11-08 the human answered yes, with a reserved list: a worker takes its own recommendation on a choice no rule reserves for the human, records it in the item or a decision, and interrupts only for a reserved choice or an ask it has no recommendation for. The reserved choices are a release, a change to the ladder or its steps, and a goal, listed in one place.
|
||||
|
||||
92 of the 255 interrupts in loop-claude's archive, on 2026-11-08, carry the worker's recommendation, such as "I recommend shipping". The judge answered 16 asks itself, as `Verdict: quoted`, from the records. A finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. The change touches the interrupt contract in `CLAUDE.md` → "Ask, don't guess" and the judge's prompt in `bin/loop_claude/cycle/judge.py`. Watch goal 1.2's counter-signal afterwards: decisions the human reverses.
|
||||
|
||||
### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.
|
||||
|
||||
The `worker:` decision is valid while review rounds per pass do not rise. Count the rounds from each PR's `Answer <pass> round <n>:` commits, and take reading cost from `docs/reading-cost.md`. Run it once five chunks have merged after the one that recorded the decision.
|
||||
|
||||
### 162. Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
|
||||
|
||||
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). Item 161 scripts the steps found before the first edit in item 140's chunk. This audit reads the archived transcripts of the chunks that shipped release 0.2.0 for every step repeated by hand across chunks whose answer a program computes the same way, before, during and after review: a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model.
|
||||
|
||||
The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it.
|
||||
|
||||
### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.
|
||||
|
||||
Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong.
|
||||
92 of the 255 interrupts in loop-claude's archive, on 2026-11-08, carry the worker's recommendation, such as "I recommend shipping". The judge answered 16 asks itself, as `Verdict: quoted`, from the records. A finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. The change touches the interrupt contract in `CLAUDE.md` → "Working loop", "Ask, don't guess" and the judge's prompt in `bin/loop_claude/cycle/judge.py`. Watch goal 1.2's counter-signal afterwards: decisions the human reverses.
|
||||
|
||||
### 230. Have larv-review file one ambitious refactor item, aimed at the lowest-scoring dimension, whenever a scoring run leaves any score under 7.0, so such a project always holds a plan item meant to reach 7.0.
|
||||
|
||||
@@ -187,41 +106,47 @@ Settle in the change:
|
||||
|
||||
Once it ships, `~/code/log` drops its item 98, which does the same by hand, and revises the decisions that cite it.
|
||||
|
||||
### 184. Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.
|
||||
### 215. Decode a reload's handed JSON with a decoder for `LoopRun` and its `Route`, in place of `decoded_as`'s generic one with its two sentinels and `Route.fits` hook.
|
||||
|
||||
In `bin/loop_claude/loop/main.py`'s docstring, the line holding "of one PR, is finished" and the one ending "Each of these opens with its UTC time." run to 107 and 159 columns. Raised by the prose review of PR #308.
|
||||
Release 0.3.0's Mid A (PR #324 at c713910) named `bin/loop_claude/loop/reload.py:43` `decoded_as`: "a generic decoder with two sentinels and a duck-typed fits hook defined on Route". This lowers Shape: `decoded_as` is generic over any type, yet `decode_handed` calls it with one dataclass, `LoopRun`. Keep what it does today: a field added since the running script started may be missing, and a handed dataclass holding a field its `RETIRED` names decodes as None where its type allows None, and is rejected otherwise. `LoopRun.items_taken_in`, a tuple of item IDs, decodes only from a JSON array of integers. Make `decoded_as` easier to read.
|
||||
|
||||
### 221. Parse each transcript entry once, where `bin/claude_code/transcript.py` reads it, into a typed value naming its kind, so no consumer works out an entry's kind from a raw `dict`.
|
||||
### 237. Give `judge` and `judge_once` in `bin/loop_claude/cycle/judge.py` a record of the inputs they share, in place of nine and eight parameters, or record why they stay.
|
||||
|
||||
"Validate data and build DTOs as early as possible", in `principles/technical-principles.md`, raised 🟢 by the principles audit of item 210's PR. `read_transcript` (`bin/claude_code/transcript.py:16`) returns raw `dict`s, so each consumer, such as `render` beside it and `since_step` in `bin/loop_claude/escalation_mark.py`, calls the helpers in `bin/claude_code/entries.py` (`human_text`, `loop_text`, `assistant_parts`, `tool_call`) to work out an entry's kind again. Parse each line once into types such as a human turn, a loop-claude prompt and an assistant turn, and have every consumer of `claude_code.entries` under `bin/` take those types. The change touches the escalation mark, which the comprehension seats found hard at `bin/loop_claude/cycle/judge.py:153` `escalation_mark` before item 210 moved it: make `since_step` in `bin/loop_claude/escalation_mark.py`, and `Grounds.since_step` and `judge_prompt` in `bin/loop_claude/cycle/judge.py`, easier to read.
|
||||
Found by the principles audit of PR #376. "About seven things per level" in `principles/technical-principles.md`: `judge` takes nine parameters and `judge_once` eight, past the four or five for things that act on each other, with no recorded reason. Both take root, task, premises, records, entries, escalated_at, rung and effects, which one record could carry.
|
||||
|
||||
### 116. Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.
|
||||
### 242. Run each case of a table-driven test in its own `subTest`, and split each test that checks several behaviours, so one failure does not hide the others and names its case.
|
||||
|
||||
`score-outcomes` reports the median 🔴 count at each guessed R, and how well L orders chunks by 🔴 findings; the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and the rank correlation rests on the few that have one, which tells a scorer little. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known.
|
||||
|
||||
### 203. Make `bin/repo_checks` fail on a `todo.md` citation of a `docs/decisions.md` title that no heading holds.
|
||||
|
||||
A retitled decision leaves its citations in `todo.md` stale, and no check reads them. `test_citations.py` covers only citations of `CLAUDE.md` and of rule files. Item 49 covers `AGENTS.md`'s list of titles, not these citations.
|
||||
"Tests" in `principles/technical-principles.md`. The principles audit of PR #380 found test bodies that loop over their cases without `subTest`, some checking several behaviours at once: `bin/judge_replay/test_judge_replay.py:38`, `:139`, `:176`; `bin/loop_claude/test_loop_claude.py:590`; `bin/machine_load/test_machine_load.py:19`, `:31`; `bin/rule_hook/test_rule_hook.py:480`; `bin/subagent_rung/test_subagent_rung.py:32`, `:43`, `:45`; `bin/test_settings_filter.py:28`; `bin/test_statusline.py:102`. The first failing case stops the loop, and without a message the failure doesn't say which case broke. Split the tests that check several behaviours at once, `test_judge_replay.py:176` and `test_subagent_rung.py:43-46`, into one test per behaviour ("One behaviour per test").
|
||||
|
||||
### 113. Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.
|
||||
|
||||
`score-outcomes` grounds L, E, I and S in finished chunks only. Where an item names files or units, their size bounds what the change can touch.
|
||||
|
||||
### 263. Have the judge reject an interrupt that re-asks what the human answered earlier in the chunk, unless the ask quotes what that answer left open.
|
||||
|
||||
43 of the 175 chunks with an interrupt asked two or more times, and hold 123 of the archive's 255 interrupts (2026-11-08). Examples: adf-codec asked 4 times between 19:04 and 20:54 on 2026-11-04, 3 of them on item 167; bender-infra asked 3 times on 2026-10-21 whether to grant principles and stability one more round; fejkdata asked twice in 4 minutes on 2026-10-12 to cut 0.1.0. The judge already reads the transcript (`docs/decisions.md:45`), so it sees the earlier answer. The change touches `bin/loop_claude/cycle/judge.py` `quotes_checked` and `grounded`; make them easier to read, as the seats named them.
|
||||
|
||||
### 162. Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
|
||||
|
||||
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). Item 161 scripts the steps found before the first edit in item 140's chunk. This audit reads the archived transcripts of the chunks that shipped release 0.2.0 for every step repeated by hand across chunks whose answer a program computes the same way, before, during and after review: a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model.
|
||||
|
||||
The chunk that ships this item files a copy of it in the release after the one it audits, rewording "0.2.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it.
|
||||
|
||||
### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.
|
||||
|
||||
The `worker:` decision is valid while review rounds per pass do not rise. Count the rounds from each PR's `Answer <pass> round <n>:` commits, and take reading cost from `docs/reading-cost.md`. Run it once five chunks have merged after the one that recorded the decision.
|
||||
|
||||
### 175. Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.
|
||||
|
||||
Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong.
|
||||
|
||||
### 112. Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.
|
||||
|
||||
`score-outcomes` counts every item a merge removed from `todo.md` as shipped. A merge that changed only the plan ships nothing, but one that built an item and also dropped another gives the dropped item the built one's outcome, as PR #253 did with item 69. Mark a dropped item in the change that drops it, such as by the commit or merge title, and leave it out.
|
||||
|
||||
### 124. Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.
|
||||
### 116. Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.
|
||||
|
||||
Shape scored 6.25 in PR #257's run. `bin/` held about 30 entries then: 6 launchers, 6 tool packages, 3 shared packages and 15 root modules. Two root modules are tools (`rank_todo.py`, `statusline.py`) and 13 are shared libraries, and nothing in the layout tells them apart; only README's import-root paragraph maps them. Candidate packages: git running and parsing, the todo table with `rank_todo.py`'s formula language and goal weighing, and the comprehension history with round titles. `rank_todo.py` keeps its path, which every project's rules name. The `.gitignore` allowlist and README follow the move. Release 0.3.0's inherited architect named `bin/git_repo.py:8` `git` in the rerun (PR #324 rerun at c713910): "bin/'s root holds about 43 entries, with 13 loose modules … not grouped by purpose". In the first run (PR #324 at c713910) it named `bin/rank_todo.py:196` `read_all`: "a 658-line library as well as a tool, imported by rule_hook and larv_review". Make `git` and `read_all` easier to read.
|
||||
|
||||
### 81. Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.
|
||||
|
||||
"Errors as values", in `principles/technical-principles.md`, raised by the principles audit of PR #224: `bench.py` raises `KeyError` and `CalledProcessError`, and `pool.map` re-raises the first while the other threads run on unreported.
|
||||
|
||||
### 173. Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.
|
||||
|
||||
Raised by the overrides pass of PR #296. The hook imports the main checkout's `rank_todo.py`, so while a branch of this repo changes the table's shape, every commit touching `todo.md` needs a `todo-rank-check` override: 33 log lines across four branches, the score-outcomes, plan-136, plan-148 and item-146 ones. The hook then checks nothing, and the rule rests on the worker chaining the branch's own check. Run another repo's `bin/rank_todo.py` never: that would run its code before every commit.
|
||||
`score-outcomes` reports the median 🔴 count at each guessed R, and how well L orders chunks by 🔴 findings; the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and the rank correlation rests on the few that have one, which tells a scorer little. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known.
|
||||
|
||||
### 101. Have `larv_review/history_commands.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.
|
||||
|
||||
@@ -233,69 +158,46 @@ The repo has no CI, so larv-review's gate is the local run, and larv-review's Ga
|
||||
|
||||
When CI runs a rule check, such as one of `bin/rule-hook`'s, let `<!-- rule-override <rule>: <reason> -->` in the PR body override it.
|
||||
|
||||
### 102. Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.
|
||||
### 81. Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.
|
||||
|
||||
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:117-118` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans, and the audit of PR #376 found the same block swapping `machine_load.memory.MEMINFO` at lines 120-123. An override of each lets the test run the code as production runs it.
|
||||
"Errors as values", in `principles/technical-principles.md`, raised by the principles audit of PR #224: `bench.py` raises `KeyError` and `CalledProcessError`, and `pool.map` re-raises the first while the other threads run on unreported.
|
||||
|
||||
### 135. Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.
|
||||
### 173. Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.
|
||||
|
||||
The maintainability senior and the inherited architect of PR #257's scoring run named `bin/loop_claude/loop/reload.py:38` `fingerprint` and `:50` `exec_if_edited`: the fingerprint covers every `bin/**/*.py`, so editing `statusline.py` or `rank_todo.py` re-execs a running loop. Make `fingerprint` easier to read.
|
||||
Raised by the overrides pass of PR #296. The hook imports the main checkout's `rank_todo.py`, so while a branch of this repo changes the table's shape, every commit touching `todo.md` needs a `todo-rank-check` override: 33 log lines across four branches, the score-outcomes, plan-136, plan-148 and item-146 ones. The hook then checks nothing, and the rule rests on the worker chaining the branch's own check. Run another repo's `bin/rank_todo.py` never: that would run its code before every commit.
|
||||
|
||||
### 270. Compare each review pass's share of chunks that go to a second round, and move each check stability repeats across chunks into the worker's pre-review gate.
|
||||
### 272. Make `deploy-release --cut` say when each step finishes, end on one line saying the release is cut and `~/.claude` is on it, and delete the merged release branch.
|
||||
|
||||
Weak evidence: the review folders under `~/.local/state/larv-review/`, review replays left out, hold a stability round 2 beside 137 of 211 round-1 reports (65%), product-owner 73 of 173 (42%) and prose 8 of 277 (3%), on 2026-11-08. The architecture and principles passes run up to five rounds in a release review, so they don't compare. First check whether stability's round 2s repeat the same kinds of finding, such as a missing test or an unhandled error. Move only a check a program or the worker can run before review; leave judgement with the reviewer.
|
||||
Cutting 0.6.0 printed `waiting for the checks of pull request 418`, then `Cut v0.6.0.` and `Moved from v0.5.0 to v0.6.0.`, then the whole 0.6.0 changelog section. The two lines saying it worked scrolled off behind the changelog, and no line said the checks passed or the pull request merged. So the human couldn't tell whether the cut had finished or was still waiting. Print a line on stderr as each step finishes: branch pushed, pull request opened, checks passed, merged, tagged, tag pushed. End stdout with one line, after the changelog: `Done: v<version> is cut and pushed, and <checkout> is on it.` Once the tag is pushed, delete the remote branch `release-<version>`, which 0.6.0's cut left on origin. A failed delete only warns, since the release is cut by then. Update the tests in `bin/deploy_release/test_deploy_release.py` and `deploy-release --help`.
|
||||
|
||||
### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.
|
||||
### 274. Let an item name a maintain goal it raises confidence in, such as a test leg that guards it, and weigh that move against the achieve goals in `bin/rank_todo.py`.
|
||||
|
||||
Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
|
||||
Today only a `defect` item may name a maintain goal, and only to restore one the project breaks
|
||||
(`docs/decisions.md` → the `todo.md` entry of 2026-10-16). A maintain goal otherwise adds no value to
|
||||
any item, so work that makes a held goal safer to rely on scores V 0 and ranks last: adf-codec's
|
||||
item 170, which bundles the package with four bundlers to back its goal 8, runs on any JavaScript
|
||||
engine, scores 0.0 beside items that move an achieve goal by 2.
|
||||
|
||||
### 196. Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.
|
||||
Settle with the maintainer, and record in `docs/decisions.md`:
|
||||
|
||||
Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records the runs so far. The release review of 0.6.0 deleted the code that lowered a pass, since no rung had qualified; the decision says where it goes back.
|
||||
- How an item says it: a Moves entry naming the maintain goal with how far the item raises
|
||||
confidence in it, 1 to 10, or a separate column.
|
||||
- What it weighs. The maintain goal's weight now is the heaviest achieve goal's, which suits a broken
|
||||
goal and is too much for a confidence gain; it needs its own factor, which the item measures or
|
||||
asks for.
|
||||
- Which items count: a test, a gate leg or a probe that would fail where the goal breaks. A change
|
||||
that only claims the goal does not.
|
||||
|
||||
### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.
|
||||
Then change `bin/rank_todo.py` and its tests, `--help`, and `rules/todo-items.md`'s sentences on
|
||||
maintain goals and Moves. The decision of 2026-10-16 keeps its veto: an item that breaks a maintain
|
||||
goal is still redesigned or dropped.
|
||||
|
||||
Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend.
|
||||
### 275. Make the `Main` tests of `judge-replay` and `review-replay` fail when the replays ignore the project's model, its lowest worker rung or the round's checkout.
|
||||
|
||||
### 269. Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids.
|
||||
Found by the stability review of item 219's chunk, findings 1 and 2; both gaps predate it. Mutants that survive today:
|
||||
|
||||
The `Judge cost:` line is new under `CHANGELOG.md` → "Unreleased", and no outcomes file in the archive holds one yet (2026-11-08). Of the 460 verdicts that name their judge, 48 ran on opus at xhigh, 78 at high and 310 at medium. In this repo the judge reads about 175k characters of records each time: `AGENTS.md`, `docs/decisions.md`, `CLAUDE.md`, `rules/` and larv-review's standards. `bin/routing_figures/measure.py` already adds the lines to the dollars by rung.
|
||||
|
||||
### 267. Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.
|
||||
|
||||
11 runs in the archive ended with "Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed", each leaving its chunk open until the human restarted the loop. That stop comes from `human_typed` in `bin/loop_claude/cycle/interrupt.py`, after the claude opened for `/talk` or for a release ready to cut ends with no human turn. An empty line at the terminal stops the loop the same way, in `first_answer`. Item 268 removes one of the cases that opens claude.
|
||||
|
||||
### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.
|
||||
|
||||
"Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently.
|
||||
|
||||
The tests also cover `workflow-bench/bench.py`'s `permission_flags`, with a probe of a headless claude given its flags. It is denied a read outside the granted trees, a bare `git status`, and wrapper calls with `--output`, `--no-index`, a glued `-aF/abs`, `--fil=/abs` or a path outside the clone. A `cd <elsewhere> && python3 <wrapper> …` acts on the clone only. It is allowed the wrapper's `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m`. `workflow-bench/test_review_git.py` tests the wrapper's refusals directly.
|
||||
|
||||
### 181. Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.
|
||||
|
||||
`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308.
|
||||
|
||||
### 192. Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.
|
||||
|
||||
Found by review of PR #317. `.gitignore:56-58` holds `!bin/rule-hook` above `!bin/routing_figures/` and `!bin/routing_figures/*.py`, but `o` sorts before `u`. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
|
||||
|
||||
### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
Found by review of PR #317. `bin/rank_todo.py`'s `readme_goals` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.
|
||||
|
||||
Found by review of PR #317. `bin/loop_claude/test_black_box.py:569-575` sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it.
|
||||
|
||||
### 202. Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.
|
||||
|
||||
Found by the prose review of PR #329. `prose.md` opens by calling itself the full rules that `CLAUDE.md` → "Prose" keeps a core of, yet it lacks that rule, so a prose reviewer whose bar is the standards files never sees it.
|
||||
|
||||
### 268. End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.
|
||||
|
||||
On 2026-11-08 the human answered notice only: the loop prints that the release is ready to cut and ends; no interrupt, and nothing waits in loop-inbox.
|
||||
|
||||
Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the loop once a release is ready to cut, so the ask settles nothing. 15 interrupts in the archive ask whether the human will cut a release. On 2026-11-08 one of the 4 questions waiting in `~/.local/state/loop-claude/` is such an ask, plainpages-plugin-fastjira's 0.3.0 since 2026-11-03. Today a release ready to cut opens claude's session at once (`bin/loop_claude/cycle/run.py` `ask`), and the loop stops if the human leaves it with nothing typed. The change also touches what an interrupt covers in `CLAUDE.md` → "Vocabulary". Where the change touches `ask`, make it easier to read, as the seats named it.
|
||||
- `bin/judge_replay/main.py` `main`: passing `None` in place of `lowest_worker_rung(project)` to `down_from`, since every `Main` test in `bin/judge_replay/test_judge_replay.py` uses an Opus 5.5 project, whose lowest worker rung already is the ladder's bottom. No test checks that the report's first line names the model passed as `report(project.model, ...)` either. Add a `Main` test with a Fable 5.1 project asserting that the replays stop at Opus 5.5 at max effort and that the first line names the model.
|
||||
- `bin/review_replay/main.py` `findings_found`: passing `None` in place of `found.root` to `match`, since the `Main` tests' fake claude in `bin/review_replay/test_review_replay.py` ignores the folder a match call runs in. The model `main` passes to `report` is unchecked too. Record the folder each match call runs in and assert it is the round's checkout, and assert that the first output line names the model.
|
||||
|
||||
### 77. Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.
|
||||
|
||||
@@ -327,21 +229,13 @@ Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chan
|
||||
|
||||
Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it.
|
||||
|
||||
### 4. Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.
|
||||
### 273. Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.
|
||||
|
||||
Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading-cost` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id `docs/reading-cost.md` holds, so give it a way to match a figure written under the old name.
|
||||
`docs/decisions.md` → `routing: one ladder…` records why lilleman kept the steps on 2026-11-08. Of the 36 chunks it measured, 1 scored an E + I of 6 or more and none 7 or more, so the steps for 6 to 8 are untested. Start once `score-outcomes` shows 10 finished chunks with an E + I of 6 or more. Then read its rank correlation for E + I, and the routed-chunks table of `routing-figures.md` in loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Propose new steps to lilleman, whose call they are.
|
||||
|
||||
### 187. Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.
|
||||
### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.
|
||||
|
||||
Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/measure.py`), so neither sees the report reads. Found by the architecture review of PR #310.
|
||||
|
||||
### 264. Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.
|
||||
|
||||
Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/measure.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with. Item 139 splits `measure.py`; where this change touches `measured`, make it easier to read, as the seats named it.
|
||||
|
||||
### 266. Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.
|
||||
|
||||
The archive holds 98 chunk folders under `home/lilleman/.claude`, from 2026-10-03 to 2026-10-29, and 4 under `claude-config`, from 2026-10-30 on. The routing figures of 2026-11-04 list no project `home/lilleman/.claude`. They find a chunk's later fixes on the default branch of the checkout its key names (`bin/routing_figures/archive.py` `measure_project`), and `/home/lilleman/.claude` is a release checkout on a detached HEAD. Item 5 fixes how keys are derived, not the chunks already archived. `~/.claude/loop-claude-models.json` still holds a `home/lilleman/.claude` entry; it is machine state outside the repo, so removing it is a one-off step on each machine, not part of the change.
|
||||
Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
|
||||
|
||||
### 149. Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.
|
||||
|
||||
@@ -355,10 +249,56 @@ A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tes
|
||||
|
||||
Each case is a question the project settled and the answer it chose. A fresh-context agent given only the README's premises answers each case; a case it answers differently says the goals no longer decide it. Written guidance can fail to change behaviour, which is why the goals get a test.
|
||||
|
||||
### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.
|
||||
|
||||
"Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently.
|
||||
|
||||
The tests also cover `workflow-bench/bench.py`'s `permission_flags`, with a probe of a headless claude given its flags. It is denied a read outside the granted trees, a bare `git status`, and wrapper calls with `--output`, `--no-index`, a glued `-aF/abs`, `--fil=/abs` or a path outside the clone. A `cd <elsewhere> && python3 <wrapper> …` acts on the clone only. It is allowed the wrapper's `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m`. `workflow-bench/test_review_git.py` tests the wrapper's refusals directly.
|
||||
|
||||
### 102. Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.
|
||||
|
||||
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:117-118` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans, and the audit of PR #376 found the same block swapping `machine_load.memory.MEMINFO` at lines 120-123. An override of each lets the test run the code as production runs it.
|
||||
|
||||
### 135. Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.
|
||||
|
||||
The maintainability senior and the inherited architect of PR #257's scoring run named `bin/loop_claude/loop/reload.py:38` `fingerprint` and `:50` `exec_if_edited`: the fingerprint covers every `bin/**/*.py`, so editing `statusline.py` or `rank_todo.py` re-execs a running loop. Make `fingerprint` easier to read.
|
||||
|
||||
### 270. Compare each review pass's share of chunks that go to a second round, and move each check stability repeats across chunks into the worker's pre-review gate.
|
||||
|
||||
Weak evidence: the review folders under `~/.local/state/larv-review/`, review replays left out, hold a stability round 2 beside 137 of 211 round-1 reports (65%), product-owner 73 of 173 (42%) and prose 8 of 277 (3%), on 2026-11-08. The architecture and principles passes run up to five rounds in a release review, so they don't compare. First check whether stability's round 2s repeat the same kinds of finding, such as a missing test or an unhandled error. Move only a check a program or the worker can run before review; leave judgement with the reviewer.
|
||||
|
||||
### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key.
|
||||
|
||||
The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
|
||||
|
||||
`bin/reading-cost` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading-cost` never looks. Derive both keys one way.
|
||||
|
||||
### 156. Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.
|
||||
|
||||
While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `rank_todo.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `rank_todo.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `rank_todo.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too.
|
||||
|
||||
### 196. Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.
|
||||
|
||||
Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records the runs so far. The release review of 0.6.0 deleted the code that lowered a pass, since no rung had qualified; the decision says where it goes back.
|
||||
|
||||
### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.
|
||||
|
||||
Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend.
|
||||
|
||||
### 269. Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids.
|
||||
|
||||
The `Judge cost:` line is new under `CHANGELOG.md` → "Unreleased", and no outcomes file in the archive holds one yet (2026-11-08). Of the 460 verdicts that name their judge, 48 ran on opus at xhigh, 78 at high and 310 at medium. In this repo the judge reads about 175k characters of records each time: `AGENTS.md`, `docs/decisions.md`, `CLAUDE.md`, `rules/` and larv-review's standards. `bin/routing_figures/dollars.py` already adds the lines to the dollars by rung.
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `first_answer`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
|
||||
### 268. End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.
|
||||
|
||||
On 2026-11-08 the human answered notice only: the loop prints that the release is ready to cut and ends; no interrupt, and nothing waits in loop-inbox.
|
||||
|
||||
Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the loop once a release is ready to cut, so the ask settles nothing. 15 interrupts in the archive ask whether the human will cut a release. On 2026-11-08 one of the 4 questions waiting in `~/.local/state/loop-claude/` is such an ask, plainpages-plugin-fastjira's 0.3.0 since 2026-11-03. Today a release ready to cut opens claude's session at once (`bin/loop_claude/cycle/run.py` `ask`), and the loop stops if the human leaves it with nothing typed. The change also touches what an interrupt covers in `CLAUDE.md` → "Vocabulary". Where the change touches `ask`, make it easier to read, as the seats named it.
|
||||
|
||||
### 201. Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.
|
||||
|
||||
The human asked on 2026-10-21 for tmux support, above all for saving tmux setups. Don't build anything until the human has said exactly what they need. Ask them at least:
|
||||
@@ -371,36 +311,62 @@ The human asked on 2026-10-21 for tmux support, above all for saving tmux setups
|
||||
|
||||
Weigh the widely used tmux-resurrect and tmux-continuum plugins against a script of our own. Then re-score this item from the answers and that choice, and split it into items where it is more than one chunk.
|
||||
|
||||
### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key.
|
||||
### 267. Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.
|
||||
|
||||
The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
|
||||
11 runs in the archive ended with "Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed", each leaving its chunk open until the human restarted the loop. That stop comes from `human_typed` in `bin/loop_claude/cycle/interrupt.py`, after the claude opened for `/talk` or for a release ready to cut ends with no human turn. An empty line at the terminal stops the loop the same way, in `first_answer`. Item 268 removes one of the cases that opens claude.
|
||||
|
||||
`bin/reading-cost` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading-cost` never looks. Derive both keys one way.
|
||||
### 4. Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.
|
||||
|
||||
### 155. Lower the reading cost of the files a chunk reads most before its first commit.
|
||||
Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading-cost` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id `docs/reading-cost.md` holds, so give it a way to match a figure written under the old name.
|
||||
|
||||
`bin/reading-cost` on 2026-10-28: the median of the last 5 chunks is 125,323 new input tokens before their first commit, up from 89,103 for the 5 before them. The files read most over the last 5 were `skills/larv-review/SKILL.md`, 2 times, then `bin/transcript_archive/outcomes.py` and `rules/decisions.md`, once each. The chunk that ships this item runs `bin/reading-cost --reset`.
|
||||
### 187. Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/chunk.py`), so neither sees the report reads. Found by the architecture review of PR #310.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `first_answer`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
### 264. Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.
|
||||
|
||||
### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.
|
||||
Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/chunk.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with.
|
||||
|
||||
The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_check.py` compares `todo.md` with the index and HEAD as they stand then. A call that edits `todo.md` and commits it, such as a heredoc script followed by `git commit`, passes unchecked: PR #296's commit 149108e did, and the override marker it carried was never logged. larv-review's gate still runs `rank_todo.py --check`, so an unranked plan stops at merge rather than at commit. A git pre-commit hook would see the staged file.
|
||||
### 266. Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.
|
||||
|
||||
### 265. Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.
|
||||
|
||||
No record holds these waits today. An outcomes file holds verdicts, stops, step-ups and the judge's cost (`bin/transcript_archive/outcomes.py`), and `~/.local/state/run-heavy/` holds only the slots' lock files. loop-claude waits out a usage limit and low memory in `bin/loop_claude/cycle/retry.py`; run-heavy waits for a slot in `bin/run_heavy/`. A heavy slot's wait happens inside a worker's Bash call, so loop-claude doesn't see it; run-heavy would write it where the archive can find it.
|
||||
|
||||
### 174. In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.
|
||||
|
||||
The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker or the judge.
|
||||
The archive holds 98 chunk folders under `home/lilleman/.claude`, from 2026-10-03 to 2026-10-29, and 4 under `claude-config`, from 2026-10-30 on. The routing figures of 2026-11-04 list no project `home/lilleman/.claude`. They find a chunk's later fixes on the default branch of the checkout its key names (`bin/routing_figures/archive.py` `measure_project`), and `/home/lilleman/.claude` is a release checkout on a detached HEAD. Item 5 fixes how keys are derived, not the chunks already archived. `~/.claude/loop-claude-models.json` still holds a `home/lilleman/.claude` entry; it is machine state outside the repo, so removing it is a one-off step on each machine, not part of the change.
|
||||
|
||||
### 52. Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.
|
||||
|
||||
"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory. Claude Code also loads `~/.claude/AGENTS.md`, this checkout's decision titles, as the user's instructions into every session of every project, so a worker on another project reads this repo's decisions as if they held there. That cost about $25 of cache writes and reads at list prices since 2026-10-21: 10.7k characters, about 2.7k tokens, in each of 1,084 threads.
|
||||
|
||||
### 181. Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.
|
||||
|
||||
`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308.
|
||||
|
||||
### 192. Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.
|
||||
|
||||
Found by review of PR #317. `.gitignore:56-58` holds `!bin/rule-hook` above `!bin/routing_figures/` and `!bin/routing_figures/*.py`, but `o` sorts before `u`. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
|
||||
|
||||
### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
Found by review of PR #317. `bin/rank_todo.py`'s `readme_goals` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.
|
||||
|
||||
Found by review of PR #317. `bin/loop_claude/test_black_box.py:569-575` sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it.
|
||||
|
||||
### 202. Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.
|
||||
|
||||
Found by the prose review of PR #329. `prose.md` opens by calling itself the full rules that `CLAUDE.md` → "Prose" keeps a core of, yet it lacks that rule, so a prose reviewer whose bar is the standards files never sees it.
|
||||
|
||||
### 265. Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.
|
||||
|
||||
No record holds these waits today. An outcomes file holds verdicts, stops, step-ups and the judge's cost (`bin/transcript_archive/outcomes.py`), and `~/.local/state/run-heavy/` holds only the slots' lock files. loop-claude waits out a usage limit and low memory in `bin/loop_claude/cycle/retry.py`; run-heavy waits for a slot in `bin/run_heavy/`. A heavy slot's wait happens inside a worker's Bash call, so loop-claude doesn't see it; run-heavy would write it where the archive can find it.
|
||||
|
||||
### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.
|
||||
|
||||
The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_check.py` compares `todo.md` with the index and HEAD as they stand then. A call that edits `todo.md` and commits it, such as a heredoc script followed by `git commit`, passes unchecked: PR #296's commit 149108e did, and the override marker it carried was never logged. larv-review's gate still runs `rank_todo.py --check`, so an unranked plan stops at merge rather than at commit. A git pre-commit hook would see the staged file.
|
||||
|
||||
### 174. In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.
|
||||
|
||||
The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker or the judge.
|
||||
|
||||
### 197. Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.
|
||||
|
||||
`bin/loop_claude/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. loop-claude asks two questions at its terminal. `effects.input` reads the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. `effects.input_or` reads the interrupt's answer, in `cycle/interrupt.py`'s `first_answer`, straight from stdin, since it also watches loop-inbox. Importing `readline` in `effects.py` gives `input` line editing, at two costs; `input_or` would also need to read through `input` while it watches. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
|
||||
|
||||
Reference in New Issue
Block a user