Compare commits
68 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f161ac87b | |||
| 6e6fb88d77 | |||
| 1723469017 | |||
| 01326f41c2 | |||
| 72b7149740 | |||
| 9debeb03cb | |||
| 2eae23fcd1 | |||
| ac9d107066 | |||
| 142959dfd3 | |||
| 0a9fe07084 | |||
| 326866e85b | |||
| 9f71b9aa91 | |||
| 40e8267152 | |||
| dcdb8b5868 | |||
| 9bcfaebb83 | |||
| 8bddfdc282 | |||
| 45439294ea | |||
| a9605317ab | |||
| 2f27e66f50 | |||
| bf78fedc54 | |||
| 74a4a90b10 | |||
| 33834d2b04 | |||
| fb22bc33db | |||
| 5df105033c | |||
| 93d413f5f3 | |||
| 77ab11e6af | |||
| 47bfac2cea | |||
| ad8515b811 | |||
| 9ebd06e748 | |||
| 60cb0dc851 | |||
| 00e0bc223d | |||
| bbb33f5f72 | |||
| 81894f5dac | |||
| 55f151b2c5 | |||
| 13dcef2c6e | |||
| e3cd8ae0cf | |||
| abf4f67ca8 | |||
| 192b36fada | |||
| 4d6926e790 | |||
| ba8a0df807 | |||
| 8a19e6f75f | |||
| 3409ab3d07 | |||
| a7fe878631 | |||
| d13c4fb0db | |||
| 45955a6c49 | |||
| 5e0ed821d6 | |||
| bc62ec4982 | |||
| 81a3372543 | |||
| e9da351e40 | |||
| 862a5cb91e | |||
| 4307240e8c | |||
| b00aa61a88 | |||
| b743228928 | |||
| 115b8a394f | |||
| ae29817dae | |||
| 6e12ee911e | |||
| 6a9af88aed | |||
| 2866b828bc | |||
| 4c552e0e58 | |||
| 9d243ac4bd | |||
| d0d41fc1d1 | |||
| d967219f7e | |||
| f7532827db | |||
| eb06202283 | |||
| a16f0e4625 | |||
| 1a81b55925 | |||
| f2149adc46 | |||
| 77bc635659 |
+8
-3
@@ -18,6 +18,8 @@
|
||||
!agents/
|
||||
!agents/*.md
|
||||
!bin/
|
||||
!bin/branch_chunks/
|
||||
!bin/branch_chunks/*.py
|
||||
!bin/chunk-preflight
|
||||
!bin/chunk_pick.py
|
||||
!bin/chunk_preflight/
|
||||
@@ -40,6 +42,9 @@
|
||||
!bin/loop_claude/
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!bin/loop-inbox
|
||||
!bin/loop_inbox/
|
||||
!bin/loop_inbox/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/markdown_text.py
|
||||
@@ -61,18 +66,18 @@
|
||||
!bin/review_replay/
|
||||
!bin/review_replay/*.py
|
||||
!bin/round_titles.py
|
||||
!bin/rule-hook
|
||||
!bin/routing_figures/
|
||||
!bin/routing_figures/*.py
|
||||
!bin/rule-hook
|
||||
!bin/rule_hook/
|
||||
!bin/rule_hook/*.py
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/run-heavy
|
||||
!bin/run_heavy/
|
||||
!bin/run_heavy/*.py
|
||||
!bin/run_heavy/path_entry/
|
||||
!bin/run_heavy/path_entry/docker
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/score-outcomes
|
||||
!bin/score_outcomes/
|
||||
!bin/score_outcomes/*.py
|
||||
|
||||
@@ -10,12 +10,13 @@ Decisions live in `docs/decisions.md`:
|
||||
- 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
|
||||
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
|
||||
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: before it or loop-inbox opens claude on a terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
- loop-claude: every claude it starts bypasses permissions inside its sandbox
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
|
||||
- loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
|
||||
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
|
||||
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
|
||||
@@ -23,7 +24,8 @@ Decisions live in `docs/decisions.md`:
|
||||
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
|
||||
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
|
||||
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
|
||||
- review: a fix for a 🔴 or 🟡 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: a comment is prose in any file; a branch changing only Markdown no agent follows runs only the prose pass and, for README or docs an outside reader lands on, the product-owner pass; plan rows a chunk files from a finding, re-scores or moves get no review
|
||||
- review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: a pass gets at most two rounds per chunk, with no third and no ask for one; the fixes answering round 2 merge once the gate passes
|
||||
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
|
||||
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
|
||||
@@ -37,7 +39,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- review: the premises chunk's whole review is the human's approval
|
||||
- review: the principles audit runs on every chunk that changes code, config or tests, reads the project whole with one auditor checking the goals and every principles file that applies, and runs on no other chunk
|
||||
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
|
||||
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
|
||||
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass or the branch changes only Markdown no agent follows, which reviews on the project's rung; the seats and the security pass always on the project's
|
||||
- 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, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
|
||||
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
|
||||
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
|
||||
|
||||
@@ -2,6 +2,18 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Haiku 5.5 is off the routing ladder, which now runs from Sonnet 5.5 at high to Fable 5.1 at max. A Sonnet 5.5 project's L 1 and L 2 workers now run on Sonnet 5.5 at high, where they ran on Haiku 5.5 at max: such a chunk took more than two hours and 3.1 million output tokens on a README change. A review replay can now lower a pass only to Sonnet 5.5 at high. `subagent-rung`, `review-replay` and `judge-replay` treat Haiku 5.5 as a model off the ladder.
|
||||
- larv-review runs fewer reviews on changes that hold no code:
|
||||
- A fix for a 🟡 no longer reruns the pass that found it. Only a 🔴 fix does, with each pass whose re-entry row the fix meets.
|
||||
- A comment counts as prose in every file, config included, so a comment in a workflow or compose file fires only the prose pass. Markdown an agent follows counts as config: `CLAUDE.md`, `AGENTS.md`, and files under `agents/`, `principles/`, `rules/` or `skills/`.
|
||||
- A branch that changes only other Markdown, such as `README.md`, `docs/` and `todo.md`, runs the prose pass, and the product-owner pass where an outside reader lands on the change. Its reviewers run on the project's rung, whatever its items' E + I. loop-claude's prompt says so, and rule-hook's `reviewer-rung` allows it.
|
||||
- A `todo.md` row or detail that a chunk files from a finding, re-scores or moves between releases is no longer reviewed. The chunk that ships the item reads it.
|
||||
|
||||
- New tool `loop-inbox` lists the interrupts of every loop-claude on the machine, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines. Pick one to answer the question as on the loop's terminal, except that Enter alone goes back; `/talk` opens claude in loop-inbox's terminal. Of a pasted answer, only the first line is sent, and the rest is dropped. The loop takes the first answer, from its terminal or loop-inbox, so it works as before with no loop-inbox running. A loop that ends drops off the list, even one killed outright. A loop whose claude is already open, such as for a release ready to cut or the routing calls, is listed but answered in that claude. A loop asking for its project's model, as on a project's first run, asks on its own terminal only. Below the questions, loop-inbox lists every running loop, with the ID and tagline of each `todo.md` item its chunk takes. Link it onto `PATH` as README → Install shows.
|
||||
- Ctrl-C in a claude that `loop-claude` opens on its terminal, for `/talk`, a release ready to cut or the routing calls, now reaches only that claude. Before, it also stopped `loop-claude`, which closed that claude a quarter second later.
|
||||
- `reading-cost` now lists the files a chunk read in the worktree `chunk-preflight` made, `<checkout>-item-<ID>`. It listed none, since no transcript command names that worktree.
|
||||
- `larv-review ruling-base` now finds the last measured commit when run in a subfolder of a checkout. Before, it found no change to the comprehension history there and fell back to the merge base.
|
||||
- `score-outcomes` now counts each finished chunk's later fixes: the later chunks on the default branch that fixed code it shipped, each a defect that review let through. A later chunk counts where a change of it rewrites or removes lines that `git blame` traces to the earlier chunk: its whole change where it ships a `todo.md` item marked `defect` or `security`, or one of its round commits whose title counts both a 🔴 and a finding a reviewer marked `[misread]`. Each finished item shows the count beside its guessed scores, and a new list, after the misread findings, names the chunks that fixed each one, newest first. `routing-figures.md` shows the mean per rung, over the chunks whose later fixes are known, in a new column of the routed-chunks table. To find them, loop-claude now reads each archived project's checkout, and the figures name each project whose default branch it could not read.
|
||||
- `loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone.
|
||||
- larv-review now gives each review pass at most two rounds per chunk, where it gave three and then asked for more, and no longer asks: the fixes answering a pass's second round merge once the gate passes. rule-hook's new `round-cap` rule refuses a round commit that would take a pass past round 2, such as `Answer stability round 3: …`, and takes no override. It counts the pass's earlier round commits on the branch, so a third commit titled round 2 is refused too. `larv-review round-count` marks a pass at two rounds as at the cap.
|
||||
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
|
||||
|
||||
@@ -122,7 +122,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md` or the judge's records.
|
||||
- **gate** — the merge gate: the checks a PR passes before it merges.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`, both on loop-claude's terminal.
|
||||
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
|
||||
- **judge's records** — the files the judge reads beside the README's premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
|
||||
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
|
||||
|
||||
@@ -66,7 +66,7 @@ Then pick a model with `/model`.
|
||||
|
||||
After a pick, `git status` may list `settings.json`, and a `git pull` that changes the file refuses to run. `git add settings.json` stages no change and clears both. Once it is staged, such a pull goes through and drops the model: pick it again.
|
||||
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
|
||||
Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt.
|
||||
|
||||
## Update
|
||||
|
||||
@@ -93,19 +93,20 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit
|
||||
|
||||
## Tools
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
|
||||
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.
|
||||
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `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.
|
||||
- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how.
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, code health's counter-signal; `score-outcomes --help` states the measures.
|
||||
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by, and code health's two counter-signals per chunk, misread findings and later fixes; `score-outcomes --help` states the report.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
@@ -125,7 +126,21 @@ pytest_add_cli_args=-k
|
||||
|
||||
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
|
||||
`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; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
`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.
|
||||
- `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.
|
||||
- `loop_inbox` imports `loop_claude`'s question files (`waiting.py`), its effects and paths, and `hand_over.py`, which opens claude for `/talk`.
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `rule_hook` imports `rank_todo.py`'s check.
|
||||
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the rung search, the argument reader, the candidate rungs and the exits. It reads `loop_claude`'s retry count and models file.
|
||||
- `test_env.py` serves the tests.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from comprehension_history import HISTORY
|
||||
from todo_table import Item, items
|
||||
from reading_cost.figures import RECORD
|
||||
from utc_stamp import utc
|
||||
|
||||
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
||||
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
||||
# Each commit as its hash, commit and author times and parents, its short hash and title, then the files it changed; a merge's files are those it changed against its first parent. git refuses a NUL byte in a commit message, so a title can't split a record.
|
||||
LOG = ("log", "--format=%x00%H %ct %at %P%x1f%h%x1f%s", "--name-only", "--diff-merges=first-parent")
|
||||
# One commit's record in LOG's output, without the NUL that opens it.
|
||||
LOG_RECORD = re.compile(r"([0-9a-f]+) ([0-9]+) ([0-9]+) ([0-9a-f ]*)\x1f([0-9a-f]+)\x1f(.*)", re.DOTALL)
|
||||
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
|
||||
Landing = typing.Literal["merge", "rebase", "push"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Commit:
|
||||
"""A commit as LOG prints it; committed and authored are its commit and author times, in seconds since the epoch."""
|
||||
hash: str
|
||||
short: str
|
||||
committed: int
|
||||
authored: int
|
||||
parents: tuple[str, ...]
|
||||
title: str
|
||||
files: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Span:
|
||||
"""A chunk on a default branch, as cut_branch cuts it. before is the commit its change starts from, None for the branch's oldest chunk; tip is its newest commit on the first-parent line. label names it as the reports do, landed says how it reached the branch, and merged is tip's commit time. titles are those of every commit it brought."""
|
||||
before: str | None
|
||||
tip: str
|
||||
label: str
|
||||
landed: Landing
|
||||
merged: str
|
||||
titles: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class BranchChunk(Span):
|
||||
"""A Span with two more fields: shipped holds each todo.md item its change removed, as scored before the change; fixed_by names the later chunks that fixed code it shipped, newest first."""
|
||||
shipped: tuple[Item, ...]
|
||||
fixed_by: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Branch:
|
||||
"""A default branch's commits by hash, its chunks newest first, and each commit's chunk as an index into chunks."""
|
||||
commits: dict[str, Commit]
|
||||
chunks: list[Span]
|
||||
owner: dict[str, int]
|
||||
|
||||
|
||||
def cut_branch(log: str) -> Branch | Failure:
|
||||
"""The branch LOG printed, cut into chunks as chunk_log cuts its first-parent line; a commit belongs to the oldest chunk whose commits reach it."""
|
||||
commits = parsed(log)
|
||||
if isinstance(commits, Failure):
|
||||
return commits
|
||||
if not commits:
|
||||
return Failure("git log printed no commit")
|
||||
# git log prints the commit it starts from first.
|
||||
line = [commits[next(iter(commits))]]
|
||||
while line[-1].parents:
|
||||
line.append(commits[line[-1].parents[0]])
|
||||
runs = chunk_log(line)
|
||||
owner = owners(runs, commits)
|
||||
titles: list[list[str]] = [[] for _ in runs]
|
||||
for commit in commits.values():
|
||||
titles[owner[commit.hash]].append(commit.title)
|
||||
spans = []
|
||||
for index, run in enumerate(runs):
|
||||
spans.append(Span(
|
||||
before=run[-1].parents[0] if run[-1].parents else None,
|
||||
tip=run[0].hash,
|
||||
label=label(run[-1].short, run[0].short),
|
||||
landed=landing(run),
|
||||
merged=utc(run[0].committed),
|
||||
titles=tuple(titles[index]),
|
||||
))
|
||||
return Branch(commits, spans, owner)
|
||||
|
||||
|
||||
def parsed(log: str) -> dict[str, Commit] | Failure:
|
||||
"""Each commit LOG printed, by hash, in the order it printed them."""
|
||||
commits = {}
|
||||
for record in log.split("\x00")[1:]:
|
||||
found = LOG_RECORD.fullmatch(record)
|
||||
if not found:
|
||||
return Failure(f"git log printed a commit it could not read: {record[:200]!r}")
|
||||
full, committed, authored, parents, short, rest = found.groups()
|
||||
title, *files = rest.split("\n")
|
||||
commits[full] = Commit(full, short, int(committed), int(authored), tuple(parents.split()), title, tuple(name for name in files if name))
|
||||
return commits
|
||||
|
||||
|
||||
def chunk_log(line: list[Commit]) -> list[list[Commit]]:
|
||||
"""The first-parent line, newest first, cut into chunks, newest first, each holding its commits newest first. A merge is a chunk of its own; any other commit joins the chunk of the newer commit above it when that is no merge and both share a commit time."""
|
||||
runs: list[list[Commit]] = []
|
||||
for commit in line:
|
||||
if runs and len(commit.parents) < 2 and len(runs[-1][-1].parents) < 2 and runs[-1][-1].committed == commit.committed:
|
||||
runs[-1].append(commit)
|
||||
else:
|
||||
runs.append([commit])
|
||||
return runs
|
||||
|
||||
|
||||
def landing(run: list[Commit]) -> Landing:
|
||||
"""How a run that chunk_log cut reached the branch: by a merge commit, by a rebase that gave a commit a commit time other than its author time, or by commits never replayed."""
|
||||
if len(run[0].parents) > 1:
|
||||
return "merge"
|
||||
return "rebase" if any(commit.committed != commit.authored for commit in run) else "push"
|
||||
|
||||
|
||||
def label(first: str, last: str) -> str:
|
||||
"""How the report names a chunk: its one commit's short hash, or its first and last commits' as a range."""
|
||||
return first if first == last else f"{first}^..{last}"
|
||||
|
||||
|
||||
def owners(runs: list[list[Commit]], commits: dict[str, Commit]) -> dict[str, int]:
|
||||
"""Each commit's chunk, as its index in runs: the oldest chunk whose commits reach it."""
|
||||
owner: dict[str, int] = {}
|
||||
for index in reversed(range(len(runs))):
|
||||
for commit in reversed(runs[index]):
|
||||
unowned = [commit.hash]
|
||||
while unowned:
|
||||
found = unowned.pop()
|
||||
if found not in owner:
|
||||
owner[found] = index
|
||||
unowned += commits[found].parents
|
||||
return owner
|
||||
|
||||
|
||||
def shipped(before: str, after: str) -> list[Item]:
|
||||
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
||||
planned, left = items(before), items(after)
|
||||
if not isinstance(planned, list) or not isinstance(left, list):
|
||||
return []
|
||||
kept = {item.id for item in left}
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def plan_revisions(branch: Branch) -> list[str]:
|
||||
"""The revisions whose todo.md shipped_by needs: for each chunk that brought a commit changing todo.md, other than the branch's oldest chunk, the commit before it and its tip."""
|
||||
changed = sorted({branch.owner[commit.hash] for commit in branch.commits.values() if "todo.md" in commit.files})
|
||||
revisions: dict[str, None] = {}
|
||||
for index in changed:
|
||||
before = branch.chunks[index].before
|
||||
if before is not None:
|
||||
revisions.update(dict.fromkeys((before, branch.chunks[index].tip)))
|
||||
return list(revisions)
|
||||
|
||||
|
||||
def shipped_by(branch: Branch, plans: dict[str, str]) -> list[tuple[Item, ...]]:
|
||||
"""The items each of the branch's chunks shipped, in the order of its chunks. plans holds todo.md's text at each revision plan_revisions names. A chunk with a revision plans lacks changed no plan, so it shipped none."""
|
||||
found: list[tuple[Item, ...]] = []
|
||||
for chunk in branch.chunks:
|
||||
if chunk.before is not None and chunk.before in plans and chunk.tip in plans:
|
||||
found.append(tuple(shipped(plans[chunk.before], plans[chunk.tip])))
|
||||
else:
|
||||
found.append(())
|
||||
return found
|
||||
@@ -0,0 +1,86 @@
|
||||
"""The later chunks that fixed code each chunk on a default branch shipped: its escaped defects.
|
||||
|
||||
A later chunk fixed code an earlier chunk shipped where one of its changes removes or rewrites lines that `git blame` traces to a commit the earlier chunk brought. Two kinds of change count: the chunk's whole change, where it ships a todo.md item marked `defect` or `security`; and a round commit of the chunk whose title counts both a 🔴 and a misread finding. Each later chunk counts at most once against each earlier chunk."""
|
||||
import re
|
||||
import typing
|
||||
|
||||
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
|
||||
from todo_table import Item
|
||||
from round_titles import title_counts
|
||||
|
||||
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
|
||||
FIXES = ("defect", "security")
|
||||
HUNK = re.compile(r"@@ -([0-9]+)(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@")
|
||||
BLAME_HEADER = re.compile(r"([0-9a-f]{40}|[0-9a-f]{64}) [0-9]+ [0-9]+")
|
||||
|
||||
|
||||
class FixingChange(typing.NamedTuple):
|
||||
"""A change that fixes a defect: the index of its chunk, the commit before it and its tip."""
|
||||
chunk: int
|
||||
before: str
|
||||
tip: str
|
||||
|
||||
|
||||
class Traced(typing.NamedTuple):
|
||||
"""The commits that last changed the lines a fixing change removes, with the index of the change's chunk."""
|
||||
chunk: int
|
||||
commits: set[str]
|
||||
|
||||
|
||||
def fixing_changes(branch: Branch, shipped: list[tuple[Item, ...]]) -> list[FixingChange]:
|
||||
"""Each change that fixes a defect: the whole change of each chunk that ships a FIXES item, as shipped_by lists them, and each round commit whose title counts both a 🔴 and a misread finding."""
|
||||
changes = []
|
||||
for index, (chunk, items) in enumerate(zip(branch.chunks, shipped)):
|
||||
if chunk.before is not None and any(item.exempt in FIXES for item in items):
|
||||
changes.append(FixingChange(index, chunk.before, chunk.tip))
|
||||
for commit in branch.commits.values():
|
||||
counts = title_counts(commit.title)
|
||||
# A title counts misread 🔴 and 🟡 findings together, so it takes one with both a 🔴 and a misread finding to answer a misread 🔴.
|
||||
if counts and counts.red and counts.misread and commit.parents:
|
||||
changes.append(FixingChange(branch.owner[commit.hash], commit.parents[0], commit.hash))
|
||||
return changes
|
||||
|
||||
|
||||
def with_fixes(branch: Branch, shipped: list[tuple[Item, ...]], traced: list[Traced]) -> list[BranchChunk]:
|
||||
"""The branch's chunks, each with the items it shipped, as shipped_by lists them, and the later chunks that fixed code it shipped, from the commits each fixing change traced to."""
|
||||
fixed: dict[int, set[int]] = {}
|
||||
for change in traced:
|
||||
for commit in change.commits:
|
||||
# Blame at a commit on the branch should name only commits its log holds; any other counts against no chunk. Chunks run newest first, so > keeps the chunks older than the fixing one.
|
||||
if commit in branch.owner and branch.owner[commit] > change.chunk:
|
||||
fixed.setdefault(branch.owner[commit], set()).add(change.chunk)
|
||||
chunks = []
|
||||
for index, (span, items) in enumerate(zip(branch.chunks, shipped)):
|
||||
fixed_by = tuple(branch.chunks[later].label for later in sorted(fixed.get(index, ())))
|
||||
chunks.append(BranchChunk(**vars(span), shipped=items, fixed_by=fixed_by))
|
||||
return chunks
|
||||
|
||||
|
||||
def removed_work(diff: str) -> dict[str, list[tuple[int, int]]]:
|
||||
"""What removed reads from a `git diff -U0`, less the paths in NOT_WORK: the plan and the records."""
|
||||
return {path: spans for path, spans in removed(diff).items() if path not in NOT_WORK}
|
||||
|
||||
|
||||
def removed(diff: str) -> dict[str, list[tuple[int, int]]]:
|
||||
"""The old lines each hunk of a `git diff -U0` removes or rewrites, as its first line and count, by the path the file had before; none for a path git quotes, as it does one holding a byte it cannot print."""
|
||||
spans: dict[str, list[tuple[int, int]]] = {}
|
||||
path, left = None, 0
|
||||
for row in diff.splitlines():
|
||||
if left and row[:1] in ("-", "+", " "):
|
||||
left -= 1
|
||||
elif row.startswith("diff --git "):
|
||||
path, left = None, 0
|
||||
elif row.startswith("--- "):
|
||||
# Git ends a path holding a space with a tab.
|
||||
path = row[len("--- a/"):].removesuffix("\t") if row.startswith("--- a/") else None
|
||||
elif hunk := HUNK.match(row):
|
||||
start, count = int(hunk.group(1)), int(hunk.group(2) or 1)
|
||||
left = count + int(hunk.group(3) or 1)
|
||||
if path and count:
|
||||
spans.setdefault(path, []).append((start, count))
|
||||
return spans
|
||||
|
||||
|
||||
def blamed(porcelain: str) -> set[str]:
|
||||
"""The commit each line of `git blame --porcelain` output comes from."""
|
||||
return {header.group(1) for row in porcelain.splitlines() if (header := BLAME_HEADER.match(row))}
|
||||
@@ -0,0 +1,61 @@
|
||||
from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes
|
||||
from branch_chunks.cut import BranchChunk, cut_branch, LOG, plan_revisions, shipped_by
|
||||
from failure import Failure
|
||||
from git_repo import Run, text_at
|
||||
|
||||
|
||||
def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure:
|
||||
"""Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.
|
||||
|
||||
run must run git in the checkout's top: the diff names each path from the top, while blame and a pathspec read a path from the current directory."""
|
||||
# The -- keeps a file named like the branch from making it ambiguous.
|
||||
log = run(*LOG, default, "--")
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
branch = cut_branch(log)
|
||||
if isinstance(branch, Failure):
|
||||
return branch
|
||||
plans = plans_at(plan_revisions(branch), run)
|
||||
if isinstance(plans, Failure):
|
||||
return plans
|
||||
shipped = shipped_by(branch, plans)
|
||||
traced = traces(fixing_changes(branch, shipped), run)
|
||||
return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced)
|
||||
|
||||
|
||||
def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure:
|
||||
"""todo.md's text at each revision, empty where the revision holds none."""
|
||||
plans = {}
|
||||
for revision in revisions:
|
||||
plan = text_at(revision, "todo.md", run)
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
plans[revision] = plan
|
||||
return plans
|
||||
|
||||
|
||||
def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure:
|
||||
"""The commits traced_to traces for each change."""
|
||||
found = []
|
||||
for change in changes:
|
||||
traced = traced_to(change.before, change.tip, run)
|
||||
if isinstance(traced, Failure):
|
||||
return traced
|
||||
found.append(Traced(change.chunk, traced))
|
||||
return found
|
||||
|
||||
|
||||
def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure:
|
||||
"""The commits that last changed each line of a chunk's work that the change from before to tip removes or rewrites."""
|
||||
# The prefixes and options keep the checkout's diff config out of the output. Only hunk headers, paths and commits are read, so a file's text that is not UTF-8 is replaced.
|
||||
diff = run("diff", "-U0", "--inter-hunk-context=0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip, errors="replace")
|
||||
if isinstance(diff, Failure):
|
||||
return diff
|
||||
traced: set[str] = set()
|
||||
for path, spans in removed_work(diff).items():
|
||||
# --no-ignore-revs-file drops each revs file the config names, since blame fails on one that is missing. An empty --ignore-revs-file= doesn't: blame opens the configured files first.
|
||||
blame = run("blame", "--porcelain", "--no-textconv", "--no-ignore-revs-file", *(f"-L{start},+{count}" for start, count in spans), before, "--", path, errors="replace")
|
||||
if isinstance(blame, Failure):
|
||||
return blame
|
||||
traced |= blamed(blame)
|
||||
return traced
|
||||
@@ -0,0 +1,286 @@
|
||||
import functools
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from branch_chunks.fixes import blamed, fixing_changes, removed, removed_work, Traced, with_fixes
|
||||
from branch_chunks.cut import Branch, chunk_log, Commit, cut_branch, landing, NOT_WORK, shipped, Span
|
||||
from branch_chunks.read import branch_chunks, traced_to
|
||||
from failure import Failure
|
||||
from git_repo import git
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item
|
||||
|
||||
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
FIRST = "| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 10 | 6 | 7 | 1 | 9.0 |"
|
||||
SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |"
|
||||
FIX = "| 6 | 0.1.0 | defect | **Fix it.** | 1 | 1 | 1 | 6 | 7 | 1 | 9.0 |"
|
||||
|
||||
|
||||
def todo(*rows: str, header: str = HEADER) -> str:
|
||||
return "# todo\n\n## Items\n\n" + header + "".join(f"{row}\n" for row in rows)
|
||||
|
||||
|
||||
def item(id_: int, exempt: str = "") -> Item:
|
||||
return Item(id_, (0, 1, 0), exempt, f"**Item {id_}.**", {}, (), ())
|
||||
|
||||
|
||||
def span(label: str) -> Span:
|
||||
return Span(f"{label}-before", f"{label}-tip", label, "merge", "2026-10-13T10:00:00Z", ())
|
||||
|
||||
|
||||
def commit(hash_: str, committed: int, authored: int, *parents: str, title: str = "") -> Commit:
|
||||
return Commit(hash_, hash_, committed, authored, parents, title, ())
|
||||
|
||||
|
||||
def cut(*line: Commit) -> list[tuple[str, str, int, str]]:
|
||||
"""Each chunk chunk_log cuts the first-parent line into: its oldest and newest commit, its commit time and how it landed."""
|
||||
return [(run[-1].hash, run[0].hash, run[0].committed, landing(run)) for run in chunk_log(list(line))]
|
||||
|
||||
|
||||
class Shipped(unittest.TestCase):
|
||||
def test_ships_each_item_the_change_removed_with_the_scores_it_had_before(self):
|
||||
self.assertEqual([found.id for found in shipped(todo(FIRST, SECOND), todo(SECOND))], [4])
|
||||
self.assertEqual(shipped(todo(FIRST, SECOND), todo(SECOND))[0].scores, {"R": 2, "S": 3, "C": 10, "A": 6, "G": 7})
|
||||
|
||||
def test_lists_the_shipped_items_by_id(self):
|
||||
self.assertEqual([found.id for found in shipped(todo(SECOND, FIRST), todo())], [4, 5])
|
||||
|
||||
def test_reads_a_table_from_before_c_joined_it(self):
|
||||
older = "| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |"
|
||||
self.assertEqual(shipped(todo(older, header=WITHOUT_C), todo(header=WITHOUT_C))[0].scores, {"R": 2, "S": 3, "A": 6, "G": 7})
|
||||
|
||||
def test_ships_nothing_where_either_plan_has_no_table_it_can_read(self):
|
||||
self.assertEqual(shipped(todo(FIRST), "# todo\n\n- [ ] Do it.\n"), [])
|
||||
self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), [])
|
||||
|
||||
|
||||
class CutBranch(unittest.TestCase):
|
||||
def test_reads_a_title_that_holds_a_control_character(self):
|
||||
found = cut_branch(f"\x00{'a' * 40} 100 100 \x1faaaaaaa\x1fTake \x1e and \x1f\n\nb.py\n")
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual([found.titles for found in found.chunks], [("Take \x1e and \x1f",)])
|
||||
|
||||
def test_fails_on_a_commit_it_cannot_read(self):
|
||||
self.assertIsInstance(cut_branch(f"\x00{'a' * 40} 100\x1faaaaaaa\n"), Failure)
|
||||
|
||||
def test_fails_on_a_log_that_holds_no_commit(self):
|
||||
self.assertIsInstance(cut_branch(""), Failure)
|
||||
|
||||
|
||||
class ChunkLog(unittest.TestCase):
|
||||
def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self):
|
||||
self.assertEqual(cut(commit("m", 100, 100, "a", "b"), commit("c", 100, 100, "a")), [("m", "m", 100, "merge"), ("c", "c", 100, "push")])
|
||||
self.assertEqual(cut(commit("c", 100, 100, "m"), commit("m", 100, 100, "a", "b")), [("c", "c", 100, "push"), ("m", "m", 100, "merge")])
|
||||
|
||||
def test_commits_sharing_a_commit_time_form_one_run_labelled_rebase_when_any_differs(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 150, "c1"), commit("c1", 200, 100, "r")), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_run_of_commits_that_all_kept_their_author_time_is_labelled_push(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 200, "c1"), commit("c1", 200, 200, "r")), [("c1", "c2", 200, "push")])
|
||||
|
||||
def test_a_run_is_rebase_when_only_its_older_commit_was_replayed(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 200, "c1"), commit("c1", 200, 100, "r")), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_run_is_rebase_when_only_its_newer_commit_was_replayed(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 100, "c1"), commit("c1", 200, 200, "r")), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_commit_at_another_time_starts_a_new_chunk(self):
|
||||
self.assertEqual(cut(commit("c2", 300, 300, "c1"), commit("c1", 200, 200, "r")), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
|
||||
|
||||
|
||||
class FixingChanges(unittest.TestCase):
|
||||
def test_takes_the_whole_change_of_each_chunk_that_ships_a_defect_or_a_security_item(self):
|
||||
branch = Branch({}, [span("d"), span("c"), span("b"), span("a")], {})
|
||||
shipped = [(item(9, "security"),), (item(8),), (item(6, "defect"), item(7)), ()]
|
||||
self.assertEqual(fixing_changes(branch, shipped), [(0, "d-before", "d-tip"), (2, "b-before", "b-tip")])
|
||||
|
||||
def test_takes_each_round_commit_whose_title_counts_both_a_red_and_a_misread_finding(self):
|
||||
titles = {
|
||||
"r1": "Answer stability round 1: 1 🔴, 0 🟡 (1 misread); keep y's caller",
|
||||
"r2": "Answer stability round 2: 1 🔴, 0 🟡 (0 misread); fix",
|
||||
"r3": "Answer prose round 1: 0 🔴, 1 🟡 (1 misread); fix",
|
||||
"r4": "Answer principles round 1: 1 🔴, 0 🟡; fix",
|
||||
"r5": "Do the work",
|
||||
}
|
||||
commits = {name: commit(name, 100, 100, f"{name}-parent", title=title) for name, title in titles.items()}
|
||||
branch = Branch(commits, [span("b"), span("a")], {"r1": 1, "r2": 0, "r3": 0, "r4": 0, "r5": 0})
|
||||
self.assertEqual(fixing_changes(branch, [(), ()]), [(1, "r1-parent", "r1")])
|
||||
|
||||
|
||||
class WithFixes(unittest.TestCase):
|
||||
def test_names_each_later_chunk_once_against_each_chunk_whose_commits_its_fixes_traced_to_newest_first(self):
|
||||
branch = Branch({}, [span("d"), span("c"), span("b"), span("a")], {"a1": 3, "a2": 3, "b1": 2, "c1": 1, "d1": 0})
|
||||
found = with_fixes(branch, [()] * 4, [Traced(1, {"a1", "a2"}), Traced(0, {"a1", "b1", "c1"}), Traced(1, {"a2"}), Traced(0, {"a2"})])
|
||||
self.assertEqual([found.fixed_by for found in found], [(), ("d",), ("d",), ("d", "c")])
|
||||
|
||||
def test_counts_no_fix_of_its_own_chunks_commit_a_newer_chunks_or_one_no_chunk_brought(self):
|
||||
branch = Branch({}, [span("b"), span("a")], {"b1": 0, "a1": 1})
|
||||
self.assertEqual([found.fixed_by for found in with_fixes(branch, [(), ()], [Traced(1, {"a1", "b1", "elsewhere"})])], [(), ()])
|
||||
|
||||
def test_keeps_each_chunk_as_cut_with_the_items_it_shipped(self):
|
||||
(found,) = with_fixes(Branch({}, [span("a")], {}), [(item(4),)], [])
|
||||
self.assertEqual((found.before, found.tip, found.label, found.landed, found.merged, found.titles), ("a-before", "a-tip", "a", "merge", "2026-10-13T10:00:00Z", ()))
|
||||
self.assertEqual([shipped.id for shipped in found.shipped], [4])
|
||||
|
||||
|
||||
class Removed(unittest.TestCase):
|
||||
def test_reads_the_old_lines_each_hunk_removes_or_rewrites_by_the_path_they_had(self):
|
||||
diff = "\n".join([
|
||||
"diff --git a/a.py b/a.py",
|
||||
"--- a/a.py",
|
||||
"+++ b/a.py",
|
||||
"@@ -2 +2 @@ def f():",
|
||||
"-x",
|
||||
"+y",
|
||||
"@@ -5,3 +4,0 @@",
|
||||
"@@ -9,0 +8,2 @@",
|
||||
"diff --git a/old.py b/new.py",
|
||||
"--- a/old.py",
|
||||
"+++ b/new.py",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"diff --git a/gone.py b/gone.py",
|
||||
"--- a/gone.py",
|
||||
"+++ /dev/null",
|
||||
"@@ -1,4 +0,0 @@",
|
||||
"diff --git a/born.py b/born.py",
|
||||
"--- /dev/null",
|
||||
"+++ b/born.py",
|
||||
"@@ -0,0 +1,3 @@",
|
||||
"diff --git \"a/tab\\there.py\" \"b/tab\\there.py\"",
|
||||
"--- \"a/tab\\there.py\"",
|
||||
"+++ \"b/tab\\there.py\"",
|
||||
"@@ -1 +1 @@",
|
||||
"diff --git a/my file.py b/my file.py",
|
||||
"--- a/my file.py\t",
|
||||
"+++ b/my file.py\t",
|
||||
"@@ -7,2 +7 @@",
|
||||
])
|
||||
self.assertEqual(removed(diff), {"a.py": [(2, 1), (5, 3)], "old.py": [(1, 2)], "gone.py": [(1, 4)], "my file.py": [(7, 2)]})
|
||||
|
||||
def test_reads_a_changed_line_that_looks_like_a_header_as_text(self):
|
||||
# The second removed line was `-- a/other` in the file.
|
||||
diff = "--- a/q.sql\n+++ b/q.sql\n@@ -3,2 +3 @@\n-x\n--- a/other\n+z\n@@ -9 +8,0 @@\n-y\n"
|
||||
self.assertEqual(removed(diff), {"q.sql": [(3, 2), (9, 1)]})
|
||||
|
||||
|
||||
class RemovedWork(unittest.TestCase):
|
||||
def test_leaves_out_the_plan_and_the_records(self):
|
||||
diff = "".join(f"--- a/{path}\n+++ b/{path}\n@@ -2 +2 @@\n-x\n+y\n" for path in ("a.py", *NOT_WORK))
|
||||
self.assertEqual(removed_work(diff), {"a.py": [(2, 1)]})
|
||||
|
||||
|
||||
class Blamed(unittest.TestCase):
|
||||
def test_reads_the_commit_of_each_line_from_porcelain_output(self):
|
||||
first, second = "a" * 40, "b" * 40
|
||||
porcelain = f"{first} 2 2 1\nauthor t\nfilename a.py\n\tx\n{second} 5 5 2\nauthor t\n\ty\n{second} 6 6\n\t{first} 1 1 1\n"
|
||||
self.assertEqual(blamed(porcelain), {first, second})
|
||||
|
||||
|
||||
class TracedTo(unittest.TestCase):
|
||||
DIFF = "--- a/a.py\n+++ b/a.py\n@@ -2 +2 @@\n-x\n+y\n--- a/todo.md\n+++ b/todo.md\n@@ -5 +4,0 @@\n-| 6 |\n"
|
||||
|
||||
def test_names_the_commits_blame_names_for_the_work_a_change_removes(self):
|
||||
blames = {"a.py": f"{'a' * 40} 2 2 1\n\tx\n", "todo.md": f"{'b' * 40} 5 5 1\n\t| 6 |\n"}
|
||||
self.assertEqual(traced_to("before", "tip", lambda *args, **options: self.DIFF if args[0] == "diff" else blames[args[-1]]), {"a" * 40})
|
||||
|
||||
def test_fails_where_git_cannot_blame(self):
|
||||
self.assertEqual(traced_to("before", "tip", lambda *args, **options: self.DIFF if args[0] == "diff" else Failure("no blame")), Failure("no blame"))
|
||||
|
||||
|
||||
class BranchChunks(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.checkout = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.checkout)}
|
||||
self.git("init", "-q", "-b", "main")
|
||||
self.commit("Start", {"todo.md": todo(FIRST, SECOND, FIX), "a.py": "1\n"})
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
|
||||
|
||||
def commit(self, title, files):
|
||||
for name, text in files.items():
|
||||
(self.checkout / name).write_bytes(text if isinstance(text, bytes) else text.encode())
|
||||
self.git("add", name)
|
||||
self.git("commit", "-q", "-m", title)
|
||||
|
||||
def merge(self, branch, title, files, at):
|
||||
"""Merges a branch holding one commit, at the given time, and returns the merge commit's short hash."""
|
||||
self.git("switch", "-q", "-c", branch)
|
||||
self.commit(title, files)
|
||||
self.git("switch", "-q", "main")
|
||||
self.env.update({"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": at})
|
||||
self.git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
|
||||
for name in ("GIT_COMMITTER_DATE", "GIT_AUTHOR_DATE"):
|
||||
self.env.pop(name)
|
||||
return self.git("rev-parse", "--short", "HEAD").strip()
|
||||
|
||||
def read(self, run=None):
|
||||
"""branch_chunks over main, run by git_repo's git, or else by run."""
|
||||
with unittest.mock.patch.dict(os.environ, self.env, clear=True):
|
||||
return branch_chunks("main", functools.partial(run or git, cwd=str(self.checkout)))
|
||||
|
||||
def fixing_history(self):
|
||||
"""Merges seven chunks onto main, then checks out a branch off it. Returns each of main's chunks by label, with the chunks that fixed it.
|
||||
|
||||
The defect chunk six rewrites the lines around one that an unfixed chunk wrote, renames a file and rewrites a line of it, rewrites a line that is not UTF-8, and moves a gitlink. Chunk seven fixes nothing."""
|
||||
start = self.git("rev-parse", "--short", "HEAD").strip()
|
||||
one = self.merge("one", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-10T10:00:00Z")
|
||||
two = self.merge("two", "Do five", {"b.py": "x\nn\ny\n", "todo.md": todo(FIX)}, "2026-10-11T10:00:00Z")
|
||||
self.git("update-index", "--add", "--cacheinfo", f"160000,{'1' * 40},sub")
|
||||
three = self.merge("three", "Add old.py and sub", {"old.py": "k1\nk2\nk3\nk4\nk5\n"}, "2026-10-12T10:00:00Z")
|
||||
four = self.merge("four", "Rewrite k5", {"old.py": "k1\nk2\nk3\nk4\nr\n"}, "2026-10-13T10:00:00Z")
|
||||
five = self.merge("five", "Add d.txt", {"d.txt": "café\n".encode("latin-1")}, "2026-10-14T10:00:00Z")
|
||||
self.git("rm", "-q", "old.py")
|
||||
self.git("update-index", "--cacheinfo", f"160000,{'2' * 40},sub")
|
||||
six = self.merge("six", "Fix six", {"b.py": "X\nn\nY\n", "new.py": "k1\nk2\nk3\nk4\nR\n", "d.txt": "cafè\n".encode("latin-1"), "todo.md": todo()}, "2026-10-15T10:00:00Z")
|
||||
seven = self.merge("seven", "Add c.py", {"c.py": "1\n"}, "2026-10-16T10:00:00Z")
|
||||
self.git("switch", "-q", "-c", "side")
|
||||
self.commit("Side", {"a.py": "2\n"})
|
||||
return {start: (), one: (six,), two: (), three: (), four: (six,), five: (six,), six: (), seven: ()}
|
||||
|
||||
def test_traces_a_fix_across_files_renames_text_that_is_not_utf_8_and_gitlinks(self):
|
||||
expected = self.fixing_history()
|
||||
found = self.read()
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual({chunk.label: chunk.fixed_by for chunk in found}, expected)
|
||||
|
||||
def test_keeps_the_checkouts_diff_and_blame_config_out_of_the_trace(self):
|
||||
expected = self.fixing_history()
|
||||
for setting in ("diff.noprefix=true", "color.ui=always", "diff.external=false", "diff.interHunkContext=5", "diff.renames=false", "blame.ignoreRevsFile=missing", "diff.doubled.textconv=sed p"):
|
||||
self.git("config", *setting.split("=", 1))
|
||||
(self.checkout / ".git" / "info" / "attributes").write_text("*.py diff=doubled\n")
|
||||
found = self.read()
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual({chunk.label: chunk.fixed_by for chunk in found}, expected)
|
||||
|
||||
def test_fails_where_git_cannot_blame_a_fixing_change(self):
|
||||
self.merge("four", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-13T10:00:00Z")
|
||||
self.merge("six", "Fix six", {"b.py": "x\nY\n", "todo.md": todo(SECOND)}, "2026-10-14T10:00:00Z")
|
||||
self.assertEqual(self.read(lambda *args, **options: Failure("no blame") if args[0] == "blame" else git(*args, **options)), Failure("no blame"))
|
||||
|
||||
def test_reads_each_chunk_with_the_items_it_shipped_and_the_later_chunks_that_fixed_it(self):
|
||||
shipped = self.merge("four", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-13T10:00:00Z")
|
||||
fixed = self.merge("six", "Fix six", {"b.py": "x\nY\n", "todo.md": todo(SECOND)}, "2026-10-14T10:00:00Z")
|
||||
found = self.read()
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual([(found.label, found.landed, found.merged, [item.id for item in found.shipped], found.fixed_by) for found in found[:2]], [(fixed, "merge", "2026-10-14T10:00:00Z", [6], ()), (shipped, "merge", "2026-10-13T10:00:00Z", [4], (fixed,))])
|
||||
self.assertEqual(sorted(found[1].titles), ["Do four", "Merge four"])
|
||||
self.assertEqual((found[1].tip, found[2].tip), (self.git("rev-parse", "HEAD^").strip(), self.git("rev-parse", "HEAD^^").strip()))
|
||||
self.assertEqual((found[1].before, found[2].before), (found[2].tip, None))
|
||||
|
||||
def test_fails_where_git_cannot_read_the_branch(self):
|
||||
self.assertEqual(branch_chunks("main", lambda *args: Failure("no log")), Failure("no log"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+30
-12
@@ -1,9 +1,11 @@
|
||||
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files.
|
||||
|
||||
Every tool in bin/ starts git through `git` here."""
|
||||
import functools
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
@@ -21,10 +23,11 @@ GUARD_SETTINGS = [
|
||||
]
|
||||
|
||||
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
|
||||
"""What git printed, run in cwd, else in the current directory.
|
||||
|
||||
A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it.
|
||||
errors "replace" reads each byte that is not UTF-8 as U+FFFD instead of failing. It is for output, such as a diff, whose file text the caller skips.
|
||||
guarded turns off the fsmonitor, the signature check, each transport GUARD_SETTINGS names and a partial clone's fetch of its missing objects. It is for a checkout whose config may name a program.
|
||||
"""
|
||||
command = " ".join(args)
|
||||
@@ -32,7 +35,7 @@ def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarde
|
||||
# GIT_NO_LAZY_FETCH needs git 2.44.
|
||||
env = {**os.environ, "GIT_NO_LAZY_FETCH": "1"} if guarded else None
|
||||
try:
|
||||
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", env=env, timeout=timeout)
|
||||
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", errors=errors, env=env, timeout=timeout)
|
||||
except UnicodeDecodeError as failure:
|
||||
return Failure(f"git {command} printed text that is not UTF-8: {failure}")
|
||||
except (OSError, ValueError) as failure:
|
||||
@@ -42,6 +45,16 @@ def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarde
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {command}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
class Git(typing.Protocol):
|
||||
"""Runs git as `git` does."""
|
||||
|
||||
def __call__(self, *args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure: ...
|
||||
|
||||
|
||||
# Runs git with the given arguments, in the checkout and with the options its caller bound, as functools.partial(git, cwd=...) does.
|
||||
Run = typing.Callable[..., str | Failure]
|
||||
|
||||
|
||||
def top() -> str | Failure:
|
||||
found = git("rev-parse", "--show-toplevel")
|
||||
return found if isinstance(found, Failure) else found.strip()
|
||||
@@ -60,20 +73,20 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s
|
||||
return ref if isinstance(ref, Failure) else (ref, note)
|
||||
|
||||
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master.
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. run runs git.
|
||||
|
||||
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
|
||||
remotes = git("remote", cwd=cwd, guarded=guarded)
|
||||
remotes = run("remote", cwd=cwd, guarded=guarded)
|
||||
if isinstance(remotes, Failure):
|
||||
return remotes
|
||||
if "origin" in remotes.split():
|
||||
recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
|
||||
recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
|
||||
if not isinstance(recorded, Failure):
|
||||
return recorded.strip()
|
||||
return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout)
|
||||
return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout, run)
|
||||
for branch in ("main", "master"):
|
||||
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure):
|
||||
if not isinstance(run("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure):
|
||||
return branch
|
||||
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
||||
|
||||
@@ -86,9 +99,9 @@ def branch_titles(default: str, cwd: str | None = None, timeout: float | None =
|
||||
return titles if isinstance(titles, Failure) else titles.splitlines()
|
||||
|
||||
|
||||
def origin_head(cwd: str | None, timeout: float | None) -> str | Failure:
|
||||
def origin_head(cwd: str | None, timeout: float | None, run: Git) -> str | Failure:
|
||||
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
|
||||
listed = git("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
|
||||
listed = run("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
|
||||
@@ -117,10 +130,15 @@ def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure:
|
||||
"""A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
|
||||
if not commit_exists(revision, cwd):
|
||||
return ""
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd)
|
||||
return text_at(revision, path, functools.partial(git, cwd=cwd))
|
||||
|
||||
|
||||
def text_at(revision: str, path: str, run: Run) -> str | Failure:
|
||||
"""A file's text at a commit, as run reads it; empty where the commit holds no such file. ls-tree reads path from the directory run runs in, and show from the checkout's top."""
|
||||
listed = run("ls-tree", "--name-only", revision, "--", path)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
return git("show", f"{revision}:{path}", cwd=cwd) if listed.strip() else ""
|
||||
return run("show", f"{revision}:{path}") if listed.strip() else ""
|
||||
|
||||
|
||||
def full_history() -> Failure | None:
|
||||
|
||||
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
@@ -122,7 +122,7 @@ class Main(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def verdict(interrupt, evidence):
|
||||
output = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
|
||||
output = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
|
||||
return {"type": "result", "structured_output": output}
|
||||
|
||||
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
@@ -175,9 +175,9 @@ class Main(unittest.TestCase):
|
||||
self.assertIn("usage limit: You've hit your limit", err)
|
||||
for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["claude-haiku-5-5"], unused)
|
||||
code, _, err = self.run_main(["claude-fable-5-1"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived verdicts of projects on claude-haiku-5-5", err)
|
||||
self.assertIn("no archived verdicts of projects on claude-fable-5-1", err)
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text("[")
|
||||
self.assertEqual(self.run_main(["claude-opus-5-5"], unused)[0], 1)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from failure import Failure
|
||||
from git_repo import file_at, full_history, git
|
||||
from git_repo import file_at, full_history, git, top
|
||||
from comprehension_history import HISTORY, HistoryChange
|
||||
|
||||
|
||||
@@ -7,24 +7,28 @@ def history_changes(default: str) -> list[HistoryChange] | Failure:
|
||||
"""Each merged change on the default branch that touched the history, newest first."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
|
||||
# HISTORY names the file from the checkout's top, and git reads a path from the directory it runs in.
|
||||
root = top()
|
||||
if isinstance(root, Failure):
|
||||
return root
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY, cwd=root)
|
||||
if isinstance(commits, Failure):
|
||||
return commits
|
||||
changes = []
|
||||
for commit in commits.split():
|
||||
change = history_change(commit)
|
||||
change = history_change(commit, root)
|
||||
if isinstance(change, Failure):
|
||||
return change
|
||||
changes.append(change)
|
||||
return changes
|
||||
|
||||
|
||||
def history_change(commit: str) -> HistoryChange | Failure:
|
||||
"""The history before and after commit. A merge commit counts as one change, against its first parent."""
|
||||
before = file_at(f"{commit}^1", HISTORY)
|
||||
def history_change(commit: str, root: str) -> HistoryChange | Failure:
|
||||
"""The history before and after commit, read in the checkout at root. A merge commit counts as one change, against its first parent."""
|
||||
before = file_at(f"{commit}^1", HISTORY, root)
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
after = file_at(commit, HISTORY)
|
||||
after = file_at(commit, HISTORY, root)
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
return HistoryChange(commit, before, after)
|
||||
|
||||
@@ -364,15 +364,15 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.git("add", name)
|
||||
self.git("commit", "-q", "--allow-empty", "-m", title)
|
||||
|
||||
def run_tool(self, *args):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
|
||||
def run_tool(self, *args, cwd=None):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True)
|
||||
|
||||
def seats_file(self, text, name="seats.md"):
|
||||
path = self.checkout.parent / name
|
||||
path.write_text(textwrap.dedent(text))
|
||||
return str(path)
|
||||
|
||||
def test_takes_the_merge_base_until_a_merged_change_records_an_entry(self):
|
||||
def test_takes_the_merge_base_until_a_merged_change_records_an_entry_and_finds_it_from_a_subfolder(self):
|
||||
start = self.git("rev-parse", "HEAD").strip()
|
||||
self.commit("work")
|
||||
ran = self.run_tool("ruling-base")
|
||||
@@ -381,8 +381,12 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.commit("Merge a scoring run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
measured = self.git("rev-parse", "HEAD").strip()
|
||||
self.commit("Fix a typo", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING + "\nA note.\n"})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.git("switch", "-q", "chunk")
|
||||
self.assertEqual(self.run_tool("ruling-base").stdout.splitlines()[0], measured)
|
||||
(self.checkout / "docs").mkdir(exist_ok=True)
|
||||
self.assertEqual(self.run_tool("ruling-base", cwd=self.checkout / "docs").stdout.splitlines()[0], measured)
|
||||
|
||||
def test_counts_rounds_on_this_branch_alone(self):
|
||||
self.commit("Answer stability round 1: a")
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_inbox import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], pathlib.Path.home()))
|
||||
@@ -1,65 +1,105 @@
|
||||
import dataclasses
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_claude.waiting import Answer, answered, Ask, Asking, claude_ended, ClaudeOpening, listed, make_way, OpenInInbox, OpenOnTerminal, shown, TALK, Typed
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens."""
|
||||
class WorkerSession:
|
||||
"""The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox."""
|
||||
root: str
|
||||
id: uuid.UUID
|
||||
rung: Rung
|
||||
transcript_path: str
|
||||
# Added to the environment of the worker's claude, and of the claude /talk opens.
|
||||
env: dict[str, str]
|
||||
|
||||
def claude_command(self) -> ClaudeCommand:
|
||||
return ClaudeCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
|
||||
with listed(paths.waiting, ask, effects):
|
||||
answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal()
|
||||
if isinstance(answer, OpenOnTerminal | OpenInInbox):
|
||||
return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, paths, effects)) or Talked()
|
||||
return answer
|
||||
|
||||
|
||||
def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop:
|
||||
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type nothing, or the input ends."""
|
||||
try:
|
||||
answer = effects.input(ASK_ANSWER).strip()
|
||||
# Annotated since mypy infers input_or's T as object from the lambda.
|
||||
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
|
||||
except EOFError:
|
||||
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
|
||||
return needs_human(ANSWER_QUESTION, "the input ended")
|
||||
if not answer:
|
||||
match answer:
|
||||
case ClaudeOpening(pid):
|
||||
return OpenInInbox(pid)
|
||||
case Typed(text):
|
||||
say(f"Answered in loop-inbox: {text}", effects)
|
||||
case str(text):
|
||||
pass
|
||||
case _:
|
||||
typing.assert_never(answer)
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return needs_human(ANSWER_QUESTION, "nothing was typed")
|
||||
return Talk() if answer == TALK else answer
|
||||
return OpenOnTerminal() if text == TALK else text
|
||||
|
||||
|
||||
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
|
||||
entries = read_transcript(path)
|
||||
def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Lists ask in loop-inbox as having claude open where, then returns once that claude has ended: the one it opens on the terminal, or the one loop-inbox opened."""
|
||||
match where:
|
||||
case OpenOnTerminal():
|
||||
shown(paths.waiting, dataclasses.replace(ask, state=where), effects)
|
||||
if unstarted := hand_over(session.claude_command(), paths, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
case OpenInInbox(pid):
|
||||
make_way(paths.waiting, ask, pid, effects)
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not claude_ended(paths.waiting, ask) and effects.alive(pid):
|
||||
effects.sleep(POLL_SECONDS)
|
||||
case _:
|
||||
typing.assert_never(where)
|
||||
return None
|
||||
|
||||
|
||||
def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None]) -> Stop | None:
|
||||
"""Runs held_open, which returns once the claude the human answers in has ended, then checks that the human typed something there."""
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
entries = read_transcript(path)
|
||||
if stop := held_open():
|
||||
return stop
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects))
|
||||
try:
|
||||
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
@@ -8,7 +8,7 @@ from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished, Verdict
|
||||
from todo_table import LEVELS
|
||||
from model_routing.route import on_its_scale
|
||||
from claude_code.transcript import plain, verbatim
|
||||
@@ -67,6 +67,8 @@ class Reply:
|
||||
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
|
||||
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Lists the chunk's items in loop-inbox: running_loops.py.
|
||||
items_taken_in: list[int] = dataclasses.field(metadata={"description": "The IDs of the todo.md items the worker states this chunk takes, the item the chunk was routed on included, never an item it only filed in todo.md for later; empty when it states none."})
|
||||
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
|
||||
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
|
||||
@@ -78,10 +80,10 @@ class Reply:
|
||||
|
||||
|
||||
REPLY_TYPES = typing.get_type_hints(Reply)
|
||||
JSON_TYPES = {bool: "boolean", int: "integer", str: "string"}
|
||||
JSON_TYPES: dict[object, dict[str, typing.Any]] = {bool: {"type": "boolean"}, int: {"type": "integer"}, str: {"type": "string"}, list[int]: {"type": "array", "items": {"type": "integer"}}}
|
||||
HIGHEST_L = LEVELS["L"]
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
||||
"properties": {field.name: {**field.metadata, **JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
||||
"required": list(REPLY_TYPES),
|
||||
"type": "object",
|
||||
}
|
||||
@@ -107,23 +109,42 @@ def verdict_from(output: object) -> Verdict | Failure:
|
||||
if not isinstance(output, dict):
|
||||
return Failure("the judge returned no reply")
|
||||
for name, kind in REPLY_TYPES.items():
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
if type(output.get(name)) is not kind:
|
||||
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
||||
# An L taken in off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
||||
likelihood = output["highest_likelihood_taken_in"] if 0 <= output["highest_likelihood_taken_in"] <= HIGHEST_L else 0
|
||||
if not fits(output.get(name), kind):
|
||||
return Failure(f"the judge's reply has no {name} of type {type_name(JSON_TYPES[kind])}")
|
||||
taken_in = taken_in_from(output)
|
||||
if output["interrupt"]:
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, release_ready=output["release_ready"])
|
||||
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], taken_in=taken_in, release_ready=output["release_ready"])
|
||||
if output["answer"].strip():
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge quoted an answer without a question")
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood)
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], taken_in=taken_in)
|
||||
if output["finished"]:
|
||||
return Finished(output["evidence"])
|
||||
escape_and_impact = output["highest_escape_and_impact_taken_in"] if on_its_scale(output["highest_escape_and_impact_taken_in"]) else 0
|
||||
return Unfinished(output["evidence"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, highest_escape_and_impact_taken_in=escape_and_impact)
|
||||
return Unfinished(output["evidence"], escalation=output["escalation"], taken_in=taken_in)
|
||||
|
||||
|
||||
def type_name(schema: dict[str, typing.Any]) -> str:
|
||||
return f"array of {schema['items']['type']}s" if schema["type"] == "array" else schema["type"]
|
||||
|
||||
|
||||
def fits(value: object, kind: object) -> bool:
|
||||
"""Whether value, read from the judge's JSON, is of kind. type(), not isinstance(): JSON true is no integer."""
|
||||
if typing.get_origin(kind) is list:
|
||||
return type(value) is list and all(fits(each, typing.get_args(kind)[0]) for each in value)
|
||||
return type(value) is kind
|
||||
|
||||
|
||||
def taken_in_from(output: dict) -> TakenIn:
|
||||
"""The reply's readings of the items taken in. An ID below 1 is left out, and an L or E + I off its scale counts as 0. Neither fails the reply: three failures would stop an unattended loop, and holding the rung is safe."""
|
||||
likelihood = output["highest_likelihood_taken_in"]
|
||||
escape_and_impact = output["highest_escape_and_impact_taken_in"]
|
||||
return TakenIn(
|
||||
tuple(item for item in output["items_taken_in"] if item > 0),
|
||||
likelihood if 0 <= likelihood <= HIGHEST_L else 0,
|
||||
escape_and_impact if on_its_scale(escape_and_impact) else 0,
|
||||
)
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
||||
@@ -164,7 +185,7 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
|
||||
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
|
||||
"""The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop."""
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
|
||||
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in)
|
||||
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, taken_in=verdict.taken_in)
|
||||
return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown)
|
||||
|
||||
|
||||
|
||||
@@ -58,9 +58,10 @@ def review_launches(route: Route, project: Rung | None) -> list[str]:
|
||||
- the rung of each pass a replay lowered;
|
||||
- where the security pass runs on another rung than the worker's, that a full scan runs only from its subagent;
|
||||
- where the worker runs below the project's rung, where to launch a subagent that files or scores todo.md items;
|
||||
- the reviewers' rung each higher E + I picks.
|
||||
- the reviewers' rung each higher E + I picks;
|
||||
- where the reviewers run above the project's rung, that a branch changing only Markdown no agent follows reviews on it, as rule-hook's reviewer-rung allows.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: `Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Sonnet 5.5 at high, and the E + I steps no review up, a sentence follows: `Launch each prose-reviewer instead with the Agent tool set to model sonnet, effort high, the rung the replay of its pass chose.`
|
||||
"""
|
||||
if project is None:
|
||||
return []
|
||||
@@ -68,7 +69,8 @@ def review_launches(route: Route, project: Rung | None) -> list[str]:
|
||||
lowered = [f"Launch each {REVIEWERS[kind]} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for kind, rung in choice.lowered.items()]
|
||||
scan = ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
|
||||
planning = [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
|
||||
return [*shared_launches(choice, route, project), *lowered, *scan, *planning, *taken_in_launches(choice)]
|
||||
markdown = [f"Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {project.agent_args()}."] if position(choice.reviewers) > position(project) else []
|
||||
return [*shared_launches(choice, route, project), *lowered, *scan, *planning, *taken_in_launches(choice), *markdown]
|
||||
|
||||
|
||||
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
|
||||
@@ -127,7 +129,7 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
def reruns(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. None off the ladder.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.` and `Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Sonnet 5.5 at high, routed by an item of E + I 4, they read: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.` and `Rerun each prose-reviewer that asks with the Agent tool set to `model opus, effort medium` instead.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER:
|
||||
return []
|
||||
|
||||
@@ -2,7 +2,7 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.routing import after_ruling, judge_rung
|
||||
from transcript_archive.write import archive
|
||||
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
@@ -10,11 +10,11 @@ from claude_code.session import delete_session, Session, session_open, transcrip
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
|
||||
from loop_claude.cycle.judge import judge, Rejected
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
@@ -42,6 +42,8 @@ class Cycle:
|
||||
project: Rung | None
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
# Lists in loop-inbox the items the chunk takes, given the IDs an unfinished ruling found taken in.
|
||||
show_taken_in: typing.Callable[[tuple[int, ...]], None]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -61,6 +63,8 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
|
||||
# Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states.
|
||||
if isinstance(event, Ruled) and event.step_up:
|
||||
cycle = dataclasses.replace(cycle, route=event.step_up.after)
|
||||
if isinstance(event, Ruled) and not isinstance(event.verdict, Finished):
|
||||
cycle.show_taken_in(event.verdict.taken_in.items)
|
||||
state = transition(state, event)
|
||||
except KeyboardInterrupt:
|
||||
return stopped(cycle, Stop(130, ""), "Ctrl-C")
|
||||
@@ -99,8 +103,6 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, _):
|
||||
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
@@ -124,6 +126,10 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
|
||||
|
||||
|
||||
def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
|
||||
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle))
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
@@ -160,7 +166,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | HumanTalked | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
@@ -168,11 +174,14 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st
|
||||
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
|
||||
if isinstance(answer, Stop):
|
||||
return answer
|
||||
answer = interrupt(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.paths, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
case Talked():
|
||||
return HumanTalked()
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
return HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
|
||||
|
||||
@@ -9,7 +9,7 @@ QUOTED_ANSWERS_PER_CYCLE = 3
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TypedAnswer:
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal or in loop-inbox."""
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
@@ -32,7 +32,7 @@ class Judging:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupting:
|
||||
"""The human answers; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
"""The human answers, by typing or in the worker's claude session; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
transcript_path: str
|
||||
ruling: Interrupt | QuotedAnswer
|
||||
quoted_answers: int = 0
|
||||
@@ -40,13 +40,6 @@ class Interrupting:
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal."""
|
||||
transcript_path: str
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Closing:
|
||||
transcript_path: str
|
||||
@@ -58,7 +51,7 @@ class Ended:
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
Active = Working | Judging | Interrupting | Talking | Closing
|
||||
Active = Working | Judging | Interrupting | Closing
|
||||
State = Active | Ended
|
||||
|
||||
|
||||
@@ -79,14 +72,9 @@ class HumanTyped:
|
||||
typed: TypedAnswer
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk, or the interrupt is for a release ready to cut."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
"""The human typed in the worker's claude session, which /talk opens, or a release ready to cut opens at once."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -94,7 +82,7 @@ class Archived:
|
||||
pass
|
||||
|
||||
|
||||
Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | Archived
|
||||
Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived
|
||||
|
||||
|
||||
def transition(state: State, event: Event) -> State:
|
||||
@@ -111,10 +99,8 @@ def transition(state: State, event: Event) -> State:
|
||||
return Closing(transcript_path, verdict)
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
|
||||
return Talking(transcript_path, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, quoted_answers), HumanTalked():
|
||||
case Interrupting(transcript_path, _, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from failure import Failure
|
||||
import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# Seconds between a loop's looks for an answer from loop-inbox while it reads its terminal, and for the end of the claude loop-inbox opened.
|
||||
POLL_SECONDS = 0.5
|
||||
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
PYTHON_TIMEOUT = 600
|
||||
|
||||
|
||||
class Git(typing.Protocol):
|
||||
"""Runs git in cwd, as git_repo.git does."""
|
||||
class InputOr(typing.Protocol):
|
||||
"""Prints a prompt, then returns the line typed at the terminal, or the first answer that other returns, called every POLL_SECONDS. Raises EOFError where the input ends."""
|
||||
|
||||
def __call__(self, *args: str, cwd: str) -> str | Failure: ...
|
||||
def __call__[T](self, prompt: str, other: typing.Callable[[], T | None]) -> str | T: ...
|
||||
|
||||
|
||||
class Streaming(typing.Protocol):
|
||||
@@ -30,19 +34,24 @@ class Streaming(typing.Protocol):
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Effects:
|
||||
# Whether the process with this pid still runs.
|
||||
alive: typing.Callable[[int], bool]
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: Git
|
||||
git: git_repo.Git
|
||||
input: typing.Callable[[str], str]
|
||||
input_or: InputOr
|
||||
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
|
||||
local_time: typing.Callable[[float], str]
|
||||
# The machine's memory; None where it cannot be read.
|
||||
memory: typing.Callable[[], Memory | None]
|
||||
new_id: typing.Callable[[], str]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
pid: typing.Callable[[], int]
|
||||
# Runs a Python script in a directory, as run_python does.
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
@@ -63,22 +72,46 @@ class StreamingClaude:
|
||||
|
||||
def system_effects() -> Effects:
|
||||
return Effects(
|
||||
alive=alive,
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
input=input,
|
||||
input_or=input_or,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
|
||||
memory=read_memory,
|
||||
new_id=lambda: str(uuid.uuid4()),
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
pid=os.getpid,
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
|
||||
|
||||
def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
|
||||
"""Runs claude on the terminal in cwd, with env added to its environment, and returns its exit code. While claude runs, Ctrl-C belongs to it: this process shares its terminal, and ignores the key."""
|
||||
# A Python handler, unlike SIG_IGN, is reset to the default as claude starts, so Ctrl-C still reaches claude.
|
||||
previous = signal.signal(signal.SIGINT, lambda number, frame: None)
|
||||
try:
|
||||
return subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, previous)
|
||||
|
||||
|
||||
def alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr."""
|
||||
command = [sys.executable, *args]
|
||||
@@ -90,6 +123,21 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T:
|
||||
# On stderr, where input prints its prompt on a terminal.
|
||||
print(prompt, end="", file=sys.stderr, flush=True)
|
||||
while True:
|
||||
if select.select([sys.stdin], [], [], POLL_SECONDS)[0]:
|
||||
# On a terminal, one read returns at most one line, so nothing typed after it is buffered here, out of discard_typed's reach.
|
||||
line = os.read(sys.stdin.fileno(), 65536)
|
||||
if not line:
|
||||
raise EOFError
|
||||
return line.decode("utf-8", "replace").removesuffix("\n")
|
||||
if (got := other()) is not None:
|
||||
print(file=sys.stderr, flush=True) # Ends the prompt's line.
|
||||
return got
|
||||
|
||||
|
||||
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
|
||||
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
|
||||
body = text.lstrip("\n")
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Opens claude on the terminal for the human. It sits outside cycle/, since loop-inbox's /talk and the loop's routing calls open claude too."""
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeCommand:
|
||||
"""How claude opens on a terminal: its arguments, its folder and what it adds to the environment."""
|
||||
args: list[str]
|
||||
cwd: str
|
||||
env: dict[str, str]
|
||||
|
||||
|
||||
def claude_args(rung: Rung, args: list[str]) -> list[str]:
|
||||
return [*rung.flags(), "--permission-mode", "bypassPermissions", *args]
|
||||
|
||||
|
||||
def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None:
|
||||
"""Marks trusted the checkout that command runs in, and each of its worktrees, then runs claude on the terminal as command says; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects))
|
||||
try:
|
||||
effects.claude_on_terminal(command.args, command.cwd, command.env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
@@ -22,13 +22,19 @@ is shown the passage the judge quoted as the work remaining. The next chunk star
|
||||
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 and reads a one-line answer on its terminal. The worker resumes
|
||||
headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the
|
||||
answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session
|
||||
on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits,
|
||||
the judge rules on what was typed there. A release ready to cut opens that session at once, since
|
||||
only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
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. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json. 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 (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
@@ -54,9 +60,9 @@ 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. 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.
|
||||
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
|
||||
@@ -75,9 +81,10 @@ Once 20 cycles have closed across all projects in the archive since the last mea
|
||||
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 ~/.claude, asked to put the calls to the human. 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.
|
||||
on the terminal in ~/.claude, 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.
|
||||
@@ -110,7 +117,8 @@ 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, or for a release ready to cut, ends with nothing 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.
|
||||
|
||||
@@ -127,7 +135,7 @@ from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from chunk_pick import default_plan, DefaultPlan
|
||||
from git_repo import default_ref
|
||||
from git_repo import default_ref, file_at
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Unfinished
|
||||
@@ -144,6 +152,7 @@ from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from model_routing.route import Route, route_from
|
||||
from claude_code.session import Session, session_named, session_open, transcript_file
|
||||
from loop_claude.running_loops import Show, shown_running, taken_items
|
||||
|
||||
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
|
||||
ORIGIN_TIMEOUT = 60
|
||||
@@ -170,33 +179,49 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
archive_folder = project_archive(loop_run.root, paths.home, env)
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
session = session_named(f"A {key} loop-claude", paths.claude_code_transcripts)
|
||||
while True:
|
||||
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||
return stop
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
premises = read_premises(loop_run.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
records = read_records(loop_run.root, paths.claude_dir)
|
||||
if isinstance(records, Stop):
|
||||
return records
|
||||
models = get_or_ask_models(key, paths, env, effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
# After the reads above, so a loop that stops on one makes no worktree.
|
||||
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
project = project_rung(models.worker)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
|
||||
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
|
||||
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects)
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as listed:
|
||||
paths = dataclasses.replace(paths, waiting=listed.folder)
|
||||
while True:
|
||||
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||
return stop
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
premises = read_premises(loop_run.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
records = read_records(loop_run.root, paths.claude_dir)
|
||||
if isinstance(records, Stop):
|
||||
return records
|
||||
models = get_or_ask_models(key, paths, env, effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
# After the reads above, so a loop that stops on one makes no worktree.
|
||||
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
project = project_rung(models.worker)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
|
||||
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
|
||||
show_taken_in = shown_items(listed.show, loop_run.root, route.item)
|
||||
show_taken_in(loop_run.items_taken_in)
|
||||
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, show_taken_in=show_taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
closed = closed_cycle(loop_run, project, concluded, archive_folder, session, effects)
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
|
||||
|
||||
def shown_items(show: Show, root: str, routed: int) -> typing.Callable[[tuple[int, ...]], None]:
|
||||
"""A function that lists in loop-inbox the items a chunk takes, given the IDs the judge found taken in. routed is the item the chunk was routed on, 0 for none. shown_items reads todo.md once, as the cycle starts, and the function shows those taglines."""
|
||||
todo = fetched_todo(root)
|
||||
return lambda taken_in: show(taken_items(todo, routed, taken_in))
|
||||
|
||||
|
||||
def fetched_todo(root: str) -> str | Failure:
|
||||
"""todo.md on the default branch, as last fetched. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which the listing doesn't need."""
|
||||
ref = default_ref(root, ORIGIN_TIMEOUT)
|
||||
return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", root)
|
||||
|
||||
|
||||
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
@@ -229,12 +254,12 @@ def reached_limit(loop_run: LoopRun) -> Stop | None:
|
||||
|
||||
|
||||
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict, and counts the verdict."""
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route, its run of unfinished verdicts and the items it took in. An unfinished one takes the route stepped_route makes, the evidence the judge gave for the verdict and the items it found taken in, and counts the verdict."""
|
||||
verdict = concluded.verdict
|
||||
if isinstance(verdict, Finished):
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0, items_taken_in=())
|
||||
route = stepped_route(project, concluded.route, verdict)
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1, items_taken_in=verdict.taken_in.items)
|
||||
|
||||
|
||||
def stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route:
|
||||
|
||||
@@ -26,6 +26,8 @@ class LoopRun:
|
||||
route: Route | None = None
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
# The IDs of the items the last unfinished verdict found the chunk takes, which loop-inbox lists until the next ruling.
|
||||
items_taken_in: tuple[int, ...] = ()
|
||||
|
||||
|
||||
def decode_handed(handed: str, kind: type[T]) -> T | None:
|
||||
@@ -43,7 +45,7 @@ RETIRED = object()
|
||||
|
||||
|
||||
def decoded_as(value: object, kind: typing.Any) -> typing.Any:
|
||||
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind."""
|
||||
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, a tuple of one type from a list, else a value of exactly kind."""
|
||||
if isinstance(kind, types.UnionType):
|
||||
found = [decoded_as(value, option) for option in typing.get_args(kind)]
|
||||
fits = [each for each in found if each is not REJECTED and each is not RETIRED]
|
||||
@@ -64,6 +66,10 @@ def decoded_as(value: object, kind: typing.Any) -> typing.Any:
|
||||
if any(field in (REJECTED, RETIRED) for field in fields.values()) or not getattr(kind, "fits", lambda _: True)(fields):
|
||||
return REJECTED
|
||||
return kind(**fields)
|
||||
if typing.get_origin(kind) is tuple:
|
||||
element = typing.get_args(kind)[0]
|
||||
found = [decoded_as(each, element) for each in value] if isinstance(value, list) else [REJECTED]
|
||||
return REJECTED if REJECTED in found or RETIRED in found else tuple(found)
|
||||
return value if type(value) is kind else REJECTED
|
||||
|
||||
|
||||
|
||||
@@ -2,24 +2,25 @@
|
||||
import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from loop_claude.waiting import Ask, listed, OpenOnTerminal
|
||||
from routing_figures.measure import calls, due, render, 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.cycle.interrupt import hand_over
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from utc_stamp import utc
|
||||
|
||||
|
||||
def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. rung is the rung of the claude that puts the calls to the human."""
|
||||
def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, session is its worker's session id, which loop-inbox lists the calls under, and rung is the rung of the claude that puts the calls to the human."""
|
||||
with archive.locked(root) as held:
|
||||
new = new_calls(root, paths, effects) if held else []
|
||||
if isinstance(new, Failure):
|
||||
say(f"routing figures: {new.reason}", effects)
|
||||
return None
|
||||
return raise_calls(root, new, rung, paths, effects) if new else None
|
||||
return raise_calls(root, checkout, session, new, rung, paths, effects) if new else None
|
||||
|
||||
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
|
||||
@@ -32,25 +33,29 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
|
||||
if isinstance(kept, Failure):
|
||||
return kept
|
||||
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)
|
||||
measured = archive.measure_archive(root, str(paths.home), kept.since, effects.git)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
figures = totals(measured.chunks, measured.skipped)
|
||||
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)):
|
||||
return unwritten
|
||||
return [call for call in found if call not in kept.calls]
|
||||
|
||||
|
||||
def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
listed = "".join(f"- {call}\n" for call in new)
|
||||
say(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", effects)
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives; 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)
|
||||
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():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal())
|
||||
with listed(paths.waiting, ask, effects):
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects)
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls: {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())):
|
||||
|
||||
@@ -10,6 +10,8 @@ class Paths:
|
||||
home: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
# Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting.py).
|
||||
waiting: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home: pathlib.Path) -> Paths:
|
||||
@@ -21,4 +23,5 @@ def paths_from(home: pathlib.Path) -> Paths:
|
||||
home=home,
|
||||
model_catalog=claude / "cache" / "model-catalog",
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
waiting=home / ".local" / "state" / "loop-claude",
|
||||
)
|
||||
|
||||
@@ -78,13 +78,13 @@ def after_unfinished(project: Rung, route: Route, verdict: Unfinished) -> Route:
|
||||
|
||||
Its rung never falls. It first rises to the rung that the verdict's highest L taken in picks, where that is higher. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the mark, as loop_claude/escalation_mark.py says; a step on the count of unfinished verdicts alone keeps it. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
|
||||
"""
|
||||
rung = raised(project, route, verdict.highest_likelihood_taken_in)
|
||||
rung = raised(project, route, verdict.taken_in.highest_likelihood)
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(project, route, rung)):
|
||||
after = one_rung_up(route, rung, route.escalated_at if mark is None else mark)
|
||||
else:
|
||||
after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
|
||||
return after.taking_in(verdict.highest_escape_and_impact_taken_in)
|
||||
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
|
||||
|
||||
|
||||
def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
|
||||
@@ -92,7 +92,7 @@ def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer)
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if mark is None:
|
||||
return route
|
||||
rung = raised(project, route, verdict.highest_likelihood_taken_in)
|
||||
rung = raised(project, route, verdict.taken_in.highest_likelihood)
|
||||
return one_rung_up(route, rung, mark) if below_cap(project, route, rung) else dataclasses.replace(route, rung=rung)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""The files by which a loop-claude shows loop-inbox that it runs, and the todo.md items its chunk takes.
|
||||
|
||||
A running loop holds its session's lock (session_lock.py) in Paths.waiting for its whole run. Beside the lock it keeps
|
||||
<session>.running, which holds the loop's checkout and each item its chunk takes, by ID and by its tagline on the default
|
||||
branch as last fetched. The items are the one the chunk was routed on, then those the judge's latest ruling found the
|
||||
worker took in, each listed once. loop-inbox lists a loop, and its question (waiting.py), only while the loop holds its
|
||||
lock. So a killed loop drops off the list, though its files stay until loop-inbox removes them: <session>.running
|
||||
through drop_ended_loops here, and the question through waiting.drop_ended.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_claude.session_lock import ended, held, running
|
||||
from failure import Failure
|
||||
from todo_table import items
|
||||
from file_writes import replace_json
|
||||
|
||||
# How many times, 0.1 s apart, a loop tries to take its lock: loop-inbox takes it for a moment each time it checks whether the loop has ended.
|
||||
LOCK_TRIES = 10
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Taken:
|
||||
"""A todo.md item a chunk takes."""
|
||||
id: int
|
||||
# The item's tagline without its bold marks; empty where the default branch's todo.md can't be read or holds no such item.
|
||||
tagline: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class RunningLoop:
|
||||
session: str
|
||||
# The checkout the loop runs in.
|
||||
root: str
|
||||
# The routed item first; empty until the chunk has an item.
|
||||
items: tuple[Taken, ...]
|
||||
|
||||
|
||||
Show = typing.Callable[[tuple[Taken, ...]], None]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listed:
|
||||
"""How a running loop shows itself in loop-inbox."""
|
||||
# Where the loop keeps its questions: Paths.waiting where it holds its session's lock. Where another loop on the session holds the lock, a folder of its own that loop-inbox doesn't read, so this loop never touches the other's questions.
|
||||
folder: pathlib.Path
|
||||
show: Show
|
||||
|
||||
|
||||
def running_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.running"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def shown_running(folder: pathlib.Path, session: str, root: str, effects: Effects) -> typing.Iterator[Listed]:
|
||||
"""Lists the loop in loop-inbox as running while the with block runs, at first with no item. A failure only warns: the loop runs unlisted, and its questions are answered on its terminal."""
|
||||
with contextlib.ExitStack() as stack:
|
||||
if unlocked := locked_soon(stack, folder, session, effects):
|
||||
say(f"loop-inbox cannot list this loop or its questions: {unlocked.reason}", effects)
|
||||
unlisted = folder / "unlisted" / effects.new_id()
|
||||
try:
|
||||
yield Listed(unlisted, lambda items: None)
|
||||
finally:
|
||||
shutil.rmtree(unlisted, ignore_errors=True)
|
||||
return
|
||||
def show(items: tuple[Taken, ...]) -> None:
|
||||
if unshown := replace_json(running_file(folder, session), {"root": root, "items": [dataclasses.asdict(item) for item in items]}):
|
||||
say(f"loop-inbox cannot list this loop's items: {unshown.reason}", effects)
|
||||
show(())
|
||||
try:
|
||||
yield Listed(folder, show)
|
||||
finally:
|
||||
# A file this fails to remove stays until loop-inbox removes it, once the lock is let go.
|
||||
with contextlib.suppress(OSError):
|
||||
running_file(folder, session).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def locked_soon(stack: contextlib.ExitStack, folder: pathlib.Path, session: str, effects: Effects) -> Failure | None:
|
||||
"""Holds the session's lock until stack closes, trying LOCK_TRIES times; returns None once it holds the lock, else the last try's failure."""
|
||||
for _ in range(LOCK_TRIES):
|
||||
attempt = contextlib.ExitStack()
|
||||
unlocked = attempt.enter_context(held(folder, session))
|
||||
if not unlocked:
|
||||
stack.enter_context(attempt)
|
||||
return None
|
||||
attempt.close()
|
||||
effects.sleep(0.1)
|
||||
return unlocked
|
||||
|
||||
|
||||
def running_loops(folder: pathlib.Path) -> list[RunningLoop]:
|
||||
"""The loops that hold their lock, by checkout. A file that cannot be read or parsed is left out."""
|
||||
try:
|
||||
paths = list(folder.glob("*.running"))
|
||||
except OSError:
|
||||
return []
|
||||
loops = [loop for path in paths if (loop := read_running(path)) and running(folder, loop.session)]
|
||||
return sorted(loops, key=lambda loop: loop.root)
|
||||
|
||||
|
||||
def drop_ended_loops(folder: pathlib.Path) -> None:
|
||||
"""Removes each running file whose session's lock no loop holds: a loop that was killed leaves it behind. A file it cannot remove stays on disk, and running_loops leaves it out all the same."""
|
||||
for session in ended(folder, "*.running"):
|
||||
with contextlib.suppress(OSError):
|
||||
running_file(folder, session).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_running(path: pathlib.Path) -> RunningLoop | None:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
match data:
|
||||
case {"root": str(root), "items": list(items)} if all(is_item(item) for item in items):
|
||||
return RunningLoop(path.name.removesuffix(".running"), root, tuple(Taken(item["id"], item["tagline"]) for item in items))
|
||||
return None
|
||||
|
||||
|
||||
def is_item(item: object) -> bool:
|
||||
match item:
|
||||
# type(), not isinstance(): JSON true is no ID.
|
||||
case {"id": id_, "tagline": str()} if type(id_) is int:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def taken_items(todo: str | Failure, routed: int, taken_in: tuple[int, ...]) -> tuple[Taken, ...]:
|
||||
"""The items a chunk takes, as the module docstring says, with their taglines from todo, the default branch's todo.md. routed, the item the chunk was routed on, is 0 for none."""
|
||||
found = items(todo) if isinstance(todo, str) else []
|
||||
taglines = {item.id: item.tagline.removeprefix("**").removesuffix("**") for item in found} if isinstance(found, list) else {}
|
||||
ids = dict.fromkeys(([routed] if routed else []) + list(taken_in))
|
||||
return tuple(Taken(id_, taglines.get(id_, "")) for id_ in ids)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""The lock by which loop-inbox tells whether a loop-claude still runs.
|
||||
|
||||
A loop holds <session>.lock for its whole run (running_loops.py), with flock, which the kernel frees however the loop
|
||||
ends, killed included. The lock file stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why.
|
||||
"""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from file_writes import make_private
|
||||
|
||||
|
||||
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.lock"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def held(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]:
|
||||
"""Holds the session's lock while the with block runs, or yields a Failure where it cannot. loop-inbox takes the lock for a moment through ended, on each session whose files are still on disk, so a loop may find it held."""
|
||||
path = lock_file(folder, session)
|
||||
try:
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot make {folder}: {failure.strerror}")
|
||||
return
|
||||
try:
|
||||
handle = open(path, "a")
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot open {path}: {failure.strerror}")
|
||||
return
|
||||
with handle:
|
||||
try:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
yield Failure(f"another process holds {path}")
|
||||
return
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot lock {path}: {failure.strerror}")
|
||||
return
|
||||
yield None
|
||||
|
||||
|
||||
def ended(folder: pathlib.Path, pattern: str) -> typing.Iterator[str]:
|
||||
"""Each session with a file in folder that matches pattern, such as "*.json", and whose lock no loop holds. It yields each while holding that lock, so a loop that starts meanwhile keeps its files."""
|
||||
try:
|
||||
sessions = {path.stem for path in folder.glob(pattern)}
|
||||
except OSError:
|
||||
return
|
||||
for session in sessions:
|
||||
with held(folder, session) as unlocked:
|
||||
if not unlocked:
|
||||
yield session
|
||||
|
||||
|
||||
def running(folder: pathlib.Path, session: str) -> bool:
|
||||
"""Whether a loop holds the session's lock; False also where the lock file cannot be opened or locked."""
|
||||
try:
|
||||
with open(lock_file(folder, session)) as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
return False
|
||||
@@ -18,6 +18,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from loop_claude import session_lock, waiting
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
@@ -36,7 +37,9 @@ argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role, "ctrl_c_ignored": signal.getsignal(signal.SIGINT) == signal.SIG_IGN}}
|
||||
# The items each loop lists in loop-inbox as this claude starts.
|
||||
call["running"] = [json.loads(path.read_text())["items"] for path in sorted((pathlib.Path.home() / ".local" / "state" / "loop-claude").glob("*.running"))]
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
@@ -97,8 +100,12 @@ if role == "worker":
|
||||
elif role == "judge":
|
||||
print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}}))
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
elif "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
else:
|
||||
if step.get("ctrl_c"):
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. kill returns once the signal is pending in loop-claude, before this process exits and loop-claude stops waiting for it.
|
||||
os.kill(os.getppid(), signal.SIGINT)
|
||||
if "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
if step.get("unreadable"):
|
||||
transcript().chmod(0)
|
||||
if step.get("vanish"):
|
||||
@@ -138,8 +145,8 @@ def worker(**step):
|
||||
return {"role": "worker", **step}
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
|
||||
verdict = {"answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", items_taken_in=(), highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
|
||||
verdict = {"items_taken_in": list(items_taken_in), "answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -465,6 +472,16 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("item 6, L 4, E + I 5", prompt)
|
||||
self.assertTrue((checkout.home / "code" / "proj-item-6").is_dir())
|
||||
|
||||
def test_lists_itself_in_loop_inbox_with_its_routed_item_then_those_the_judge_finds_taken_in_until_the_chunk_finishes(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([worker(), judge(items_taken_in=[7, 4]), worker(), judge(finished=True), worker()])
|
||||
self.assertEqual(run.code, 130)
|
||||
routed, taken_in = {"id": 4, "tagline": "Do it."}, {"id": 7, "tagline": ""}
|
||||
self.assertEqual([call["running"] for call in run.calls], [[[routed]], [[routed]], [[routed, taken_in]], [[routed, taken_in]], [[routed]], [[routed]]])
|
||||
self.assertEqual(list((checkout.home / ".local" / "state" / "loop-claude").glob("*.running")), [])
|
||||
|
||||
def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
@@ -726,6 +743,34 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertNotIn("stray", run.calls[3]["stdin"])
|
||||
|
||||
def test_resumes_the_worker_headless_with_the_answer_typed_in_loop_inbox(self):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
def answered_in_inbox():
|
||||
[ask] = waiting.waiting(folder)
|
||||
waiting.send(folder, ask, waiting.Typed("B"))
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
|
||||
self.assertIn("Answer (/talk opens claude, Enter stops the loop): \nAnswered in loop-inbox: B\n", run.stderr)
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertEqual([path for path in folder.iterdir() if path.suffix != ".lock"], [])
|
||||
|
||||
def test_a_second_loop_on_the_session_runs_unlisted_and_keeps_its_question_out_of_the_first_loops_folder(self):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
session = argument(checkout.run(asked).calls[0], "--session-id")
|
||||
# The first loop on the session, still running.
|
||||
self.enterContext(session_lock.held(folder, session))
|
||||
asks = []
|
||||
run = checkout.run(asked, terminal_input="\n", before_typing=("Answer (", lambda: asks.extend(folder.glob("*.json"))))
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(folder, session)}", run.stderr)
|
||||
self.assertEqual((asks, run.calls[0]["running"]), ([], []))
|
||||
self.assertFalse((folder / "unlisted").exists() and any((folder / "unlisted").iterdir()))
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
|
||||
@@ -760,6 +805,14 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_leaves_ctrl_c_to_the_claude_open_for_talk(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, interrupt(type="B", ctrl_c=True), judge(evidence="B")], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "interrupt", "judge", "worker"]))
|
||||
self.assertFalse(run.calls[2]["ctrl_c_ignored"])
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
@@ -912,7 +965,7 @@ class Reload(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
|
||||
self.assertIn("keeping the running script", run.stderr)
|
||||
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle} for cycle in (2, 3, 4)])
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "items_taken_in": []} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import ast
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import errno
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import signal
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -20,11 +22,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from routing_figures import archive, measure
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from chunk_pick import DefaultPlan, LastCut
|
||||
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from claude_code import entries, reply, session
|
||||
from loop_claude import escalation_mark, paths, routing
|
||||
from loop_claude import escalation_mark, hand_over, paths, routing, running_loops, session_lock, waiting
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from model_routing import ladder
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
@@ -35,6 +37,7 @@ from transcript_archive import outcomes, write
|
||||
from transcript_archive.location import project_archive
|
||||
from model_routing.route import Route, route_from, WorkerLine
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.running_loops import Taken
|
||||
from utc_stamp import utc
|
||||
from loop_claude.cycle.judge import verdict_from
|
||||
|
||||
@@ -49,6 +52,12 @@ CWD = pathlib.Path("/c")
|
||||
NOW = 1790000000
|
||||
# How a line said at NOW opens, with FakeEffects' local_time.
|
||||
STAMP = f"<{NOW}>"
|
||||
# How git answers in a project's checkout it cannot read, such as one that is gone.
|
||||
UNREAD = Failure("not a git repository")
|
||||
# The id FakeEffects gives each new ask, and its pid for loop-claude's process.
|
||||
ASK_ID, PID = "ask-1", 4242
|
||||
# The pid of a loop-inbox that opens claude for an ask.
|
||||
INBOX = 4343
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -59,6 +68,11 @@ def human(content):
|
||||
return {"type": "user", "message": {"content": content}}
|
||||
|
||||
|
||||
def asks_and_answers(folder):
|
||||
"""folder's files but the session's lock file, which stays once the loop lets go of the lock."""
|
||||
return [path for path in sorted(folder.iterdir()) if path.suffix != ".lock"]
|
||||
|
||||
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
@@ -73,16 +87,20 @@ class FakeEffects:
|
||||
|
||||
def effects(self):
|
||||
return Effects(
|
||||
alive=lambda pid: True,
|
||||
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
||||
claude_on_terminal=self.on_terminal_claude,
|
||||
discard_typed=lambda: self.calls.append(("discard_typed", None)),
|
||||
execv=self.execv,
|
||||
git=lambda *args, cwd: self.answer("git", list(args)),
|
||||
git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)),
|
||||
input=lambda prompt: self.answer("input", prompt),
|
||||
input_or=self.input_or,
|
||||
local_time=lambda seconds: f"<{seconds}>",
|
||||
memory=self.memory,
|
||||
new_id=lambda: ASK_ID,
|
||||
now=lambda: NOW,
|
||||
on_terminal=lambda: self.terminal,
|
||||
pid=lambda: PID,
|
||||
python=lambda args, cwd: self.answer("python", (args, cwd)),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
stream_claude=self.stream,
|
||||
@@ -92,6 +110,14 @@ class FakeEffects:
|
||||
self.calls.append(("memory", None))
|
||||
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
|
||||
|
||||
def input_or(self, prompt, other):
|
||||
"""Answers from the input script as input does; a callable in the script gets other, the source of loop-inbox's answer."""
|
||||
self.calls.append(("input", prompt))
|
||||
answer = self.scripts["input"].pop(0)
|
||||
if isinstance(answer, BaseException):
|
||||
raise answer
|
||||
return answer(other) if callable(answer) else answer
|
||||
|
||||
def on_terminal_claude(self, args, cwd, env):
|
||||
self.terminal_environments.append(env)
|
||||
return self.answer("claude_on_terminal", args)
|
||||
@@ -119,8 +145,8 @@ def ran(stdout="", code=0, stderr=""):
|
||||
return subprocess.CompletedProcess([], code, stdout, stderr)
|
||||
|
||||
|
||||
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False):
|
||||
reply = {"answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
|
||||
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, items_taken_in=()):
|
||||
reply = {"items_taken_in": list(items_taken_in), "answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
|
||||
return ran(json.dumps({"structured_output": reply}))
|
||||
|
||||
|
||||
@@ -176,10 +202,8 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(), states.Talking("/t", 3)),
|
||||
(states.Talking("/t"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
@@ -189,8 +213,8 @@ class Transitions(unittest.TestCase):
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t"), states.Talking("/t", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
@@ -205,7 +229,7 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
|
||||
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
):
|
||||
with self.subTest(state=state, event=event):
|
||||
@@ -228,7 +252,7 @@ class Cycles(unittest.TestCase):
|
||||
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
|
||||
|
||||
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
|
||||
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
|
||||
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", paths=self.paths, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", unfinished_evidence=unfinished_evidence)
|
||||
|
||||
def archived_outcomes(self):
|
||||
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
|
||||
@@ -239,6 +263,20 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIsNone(session.transcript_file(self.session))
|
||||
|
||||
def test_shows_the_items_each_ruling_finds_the_chunk_takes_as_the_judge_gave_them(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent)
|
||||
fake = FakeEffects(streams=[worker], claude=[judged("unfinished", items_taken_in=(14, 3))])
|
||||
shown = []
|
||||
run.run_cycle(dataclasses.replace(self.cycle(fake), show_taken_in=shown.append))
|
||||
self.assertEqual(shown, [(14, 3)])
|
||||
|
||||
def test_shows_no_items_for_a_finished_chunk(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent)
|
||||
fake = FakeEffects(streams=[worker], claude=[judged("finished", items_taken_in=(3,))])
|
||||
shown = []
|
||||
run.run_cycle(dataclasses.replace(self.cycle(fake), show_taken_in=shown.append))
|
||||
self.assertEqual(shown, [])
|
||||
|
||||
def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent)
|
||||
fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")])
|
||||
@@ -411,7 +449,7 @@ class Cycles(unittest.TestCase):
|
||||
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
|
||||
with self.subTest(ruling=ruling):
|
||||
self.assertIsNone(run.ruling_step_up(cycle, ruling))
|
||||
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", 4, entries_read=3)), escalation_mark.StepUp(cycle.route, Route(Routing.XHIGH, 3, 3, 4, escalated_at=3)))
|
||||
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), escalation_mark.StepUp(cycle.route, Route(Routing.XHIGH, 3, 3, 4, escalated_at=3)))
|
||||
|
||||
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
|
||||
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
|
||||
@@ -424,7 +462,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "high"])
|
||||
|
||||
def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self):
|
||||
for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", 0, "working", entries_read=4))):
|
||||
for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", "working", entries_read=4))):
|
||||
with self.subTest(escalation=escalation):
|
||||
self.session = session.session_named(f"A proj {escalation} loop-claude", self.paths.claude_code_transcripts)
|
||||
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)]
|
||||
@@ -636,10 +674,39 @@ class MemoryWait(unittest.TestCase):
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def put(self, fake, answer_here=True):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
put = interrupt.put_question("Which one?", answer_here, fake.effects())
|
||||
return put, said.getvalue()
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.home)
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.transcript = self.home / "t.jsonl"
|
||||
self.transcript.write_text(json.dumps(human("a")) + "\n")
|
||||
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
|
||||
def put(self, fake, answer_here=True, effects=None, question="Which one?"):
|
||||
"""interrupt's answer and what it said, run while the session's lock is held, as a running loop holds it."""
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, session_lock.held(self.paths.waiting, str(self.session.id)):
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, self.paths, effects or fake.effects())
|
||||
return answer, said.getvalue()
|
||||
|
||||
def asked(self):
|
||||
return waiting.waiting(self.paths.waiting)
|
||||
|
||||
def ask(self, question="Which one?", state=None):
|
||||
"""The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
|
||||
resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or waiting.Asking(resumed))
|
||||
|
||||
def opening(self, other):
|
||||
"""loop-inbox's /talk, as the loop's input sees it: loop-inbox claims the one ask listed, and the claim is the first answer."""
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.ClaudeOpening(INBOX))
|
||||
return other()
|
||||
|
||||
def typed_there(self, args):
|
||||
"""The claude opened on the terminal: the human types a line in the worker's session, and it ends."""
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
return 0
|
||||
|
||||
def test_stops_off_a_terminal_before_asking(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
@@ -654,8 +721,8 @@ class Interrupts(unittest.TestCase):
|
||||
def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed)
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk())
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[self.typed_there], git=[""])
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talked())
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
@@ -663,24 +730,90 @@ class Interrupts(unittest.TestCase):
|
||||
for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
|
||||
with self.subTest(why=why):
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}"))
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self):
|
||||
def typed(_):
|
||||
self.assertEqual(self.asked(), [self.ask()])
|
||||
return "Use B."
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.")
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_takes_a_line_typed_in_loop_inbox_for_this_question_and_no_other(self):
|
||||
def answered(_, other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, dataclasses.replace(ask, id="an earlier ask"), waiting.Typed("Use A."))
|
||||
self.assertIsNone(other())
|
||||
waiting.send(self.paths.waiting, ask, waiting.Typed(" Use C. "))
|
||||
return other()
|
||||
fake = FakeEffects()
|
||||
effects = dataclasses.replace(fake.effects(), input_or=answered)
|
||||
self.assertEqual(self.put(fake, effects=effects), ("Use C.", f"\n{STAMP} Which one?\n{STAMP} Answered in loop-inbox: Use C. \n"))
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_takes_the_answer_typed_on_its_terminal_where_loop_inbox_cannot_list_the_question(self):
|
||||
self.paths.waiting.parent.mkdir(parents=True)
|
||||
self.paths.waiting.write_text("")
|
||||
answer, said = self.put(FakeEffects(inputs=["Use B."]))
|
||||
self.assertEqual(answer, "Use B.")
|
||||
self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said)
|
||||
stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""]))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self):
|
||||
def claude_ran(_):
|
||||
# loop-inbox opens claude only once the loop lists it as open there.
|
||||
self.assertEqual(self.asked(), [self.ask(state=waiting.OpenInInbox(INBOX))])
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual((fake.made("claude_on_terminal"), asks_and_answers(self.paths.waiting)), ([], []))
|
||||
|
||||
def test_stops_when_loop_inbox_ends_its_claude_with_nothing_typed(self):
|
||||
looked, slept = [], []
|
||||
def alive(pid):
|
||||
looked.append(pid)
|
||||
return pid == INBOX
|
||||
def ended(seconds):
|
||||
slept.append(seconds)
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive, sleep=ended))
|
||||
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX], [POLL_SECONDS]))
|
||||
|
||||
def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self):
|
||||
looked = []
|
||||
def alive(pid):
|
||||
looked.append(pid)
|
||||
# loop-inbox's process ends while the loop waits for its claude.
|
||||
return pid == INBOX and len(looked) == 1
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive))
|
||||
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX, INBOX], [POLL_SECONDS]))
|
||||
|
||||
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
def ran(args):
|
||||
self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[ran], git=[""])
|
||||
self.put(fake, answer_here, question="Cut 0.4.0?")
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
stop = interrupt.talk(home, uuid.uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
|
||||
stop, _ = self.put(fake)
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
|
||||
interrupt.talk(home, uuid.uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [handed])
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}])
|
||||
|
||||
|
||||
class RoutingCheck(unittest.TestCase):
|
||||
@@ -705,21 +838,39 @@ class RoutingCheck(unittest.TestCase):
|
||||
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"}))
|
||||
|
||||
def check(self, fake):
|
||||
"""What check_routing returns and says for a loop in /code/log."""
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.paths, fake.effects())
|
||||
self.enterContext(session_lock.held(self.paths.waiting, "s1"))
|
||||
stop = routing_check.check_routing(self.root, "/code/log", "s1", Rung("m", "high"), self.paths, fake.effects())
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_lists_the_calls_in_loop_inbox_while_their_claude_is_open(self):
|
||||
self.chunks(5, 4)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n- Explore subagents' reports took more of the worker's context than their searches would have.\nThe figures: {self.root / 'routing-figures.md'}"
|
||||
def ran(args):
|
||||
self.assertEqual(waiting.waiting(self.paths.waiting), [waiting.Ask(ASK_ID, "s1", "/code/log", question, NOW, waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""]))
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
|
||||
self.chunks(5, 3)
|
||||
self.assertEqual(self.check(FakeEffects()), (None, ""))
|
||||
self.assertFalse((self.root / "routing-figures.md").exists())
|
||||
self.chunks(6, 1, "other")
|
||||
self.assertEqual(self.check(FakeEffects(on_terminal=False))[0], None)
|
||||
self.assertEqual(self.check(FakeEffects(on_terminal=False, git=[UNREAD, UNREAD]))[0], None)
|
||||
self.assertIn("at cycle 21 across", (self.root / "routing-figures.md").read_text())
|
||||
|
||||
def test_reads_each_projects_history_through_the_loops_git_and_names_each_it_cannot_read(self):
|
||||
self.chunks(5, 4)
|
||||
fake = FakeEffects(on_terminal=False, git=[UNREAD])
|
||||
self.check(fake)
|
||||
self.assertEqual(fake.made("git"), [["remote"]])
|
||||
self.assertIn("## Default branches unread\n\n- log: not a git repository\n", (self.root / "routing-figures.md").read_text())
|
||||
|
||||
def test_hands_the_terminal_over_once_for_each_new_call(self):
|
||||
self.chunks(5, 4)
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[UNREAD, ""])
|
||||
stop, said = self.check(fake)
|
||||
self.assertIsNone(stop)
|
||||
call = "Explore subagents' reports took more of the worker's context than their searches would have."
|
||||
@@ -730,13 +881,13 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.assertIn(f"change nothing until they answer:\n- {call}", args[6])
|
||||
self.assertEqual(fake.terminal_environments, [{}])
|
||||
(self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across")
|
||||
self.assertEqual(self.check(FakeEffects())[0], None)
|
||||
self.assertEqual(self.check(FakeEffects(git=[UNREAD]))[0], None)
|
||||
self.assertNotIn(call, self.check(FakeEffects())[1])
|
||||
|
||||
def test_stamps_the_figures_and_the_calls_raised_when_it_measures(self):
|
||||
self.chunks(5, 4)
|
||||
(self.root / "routing-calls-raised.md").write_text("# Routing calls raised\n\n- 2026-10-14T10:02:00Z Reset\n")
|
||||
self.check(FakeEffects(on_terminal_claude=[0], git=[""]))
|
||||
self.check(FakeEffects(on_terminal_claude=[0], git=[UNREAD, ""]))
|
||||
figures = (self.root / "routing-figures.md").read_text()
|
||||
self.assertIn(f"Measured {utc(NOW)}, at cycle 20 across", figures)
|
||||
self.assertIn("that finished after the reset of 2026-10-14T10:02:00Z", figures)
|
||||
@@ -749,11 +900,11 @@ class RoutingCheck(unittest.TestCase):
|
||||
|
||||
def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self):
|
||||
self.chunks(5, 4)
|
||||
stop, said = self.check(FakeEffects(on_terminal=False))
|
||||
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.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False))[1])
|
||||
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):
|
||||
self.chunks(5, 4)
|
||||
@@ -762,8 +913,9 @@ class RoutingCheck(unittest.TestCase):
|
||||
|
||||
def test_stops_when_claude_cannot_start_for_the_calls(self):
|
||||
self.chunks(5, 4)
|
||||
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[""]))
|
||||
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD, ""]))
|
||||
self.assertEqual(stop, Stop(1, "could not start claude for the routing calls: No such file or directory"))
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_says_a_figure_it_cannot_write_and_goes_on(self):
|
||||
@@ -771,7 +923,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
(self.root / "routing-figures.lock").touch()
|
||||
self.root.chmod(0o555)
|
||||
self.addCleanup(self.root.chmod, 0o755)
|
||||
stop, said = self.check(FakeEffects())
|
||||
stop, said = self.check(FakeEffects(git=[UNREAD]))
|
||||
self.assertIsNone(stop)
|
||||
self.assertIn("routing figures: could not write", said)
|
||||
|
||||
@@ -811,12 +963,12 @@ TODO = """# todo
|
||||
|
||||
def unfinished(likelihood=0, escalated_at=None):
|
||||
"""An unfinished verdict: the worker took in an item of that L, 0 for none, and the judge found an escalation after reading escalated_at transcript entries, None for none."""
|
||||
return Unfinished("e", escalation="round 2: 🔴" if escalated_at is not None else "", highest_likelihood_taken_in=likelihood, entries_read=escalated_at)
|
||||
return Unfinished("e", escalation="round 2: 🔴" if escalated_at is not None else "", taken_in=TakenIn(highest_likelihood=likelihood), entries_read=escalated_at)
|
||||
|
||||
|
||||
def interrupted(likelihood=0, escalated_at=None):
|
||||
"""An interrupt, its arguments as unfinished's."""
|
||||
return Interrupt("e", "q", escalation="round 2: 🔴" if escalated_at is not None else "", highest_likelihood_taken_in=likelihood, entries_read=escalated_at)
|
||||
return Interrupt("e", "q", escalation="round 2: 🔴" if escalated_at is not None else "", taken_in=TakenIn(highest_likelihood=likelihood), entries_read=escalated_at)
|
||||
|
||||
|
||||
class Routing(unittest.TestCase):
|
||||
@@ -1040,7 +1192,12 @@ class Steps(unittest.TestCase):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
|
||||
self.assertEqual(main.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 4), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
|
||||
|
||||
def test_an_unfinished_chunk_keeps_the_items_its_verdict_found_taken_in_and_a_finished_one_drops_them(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS), items_taken_in=(3,))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn((3, 12))), run_with.route)).items_taken_in, (3, 12))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)).items_taken_in, ())
|
||||
|
||||
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
|
||||
@@ -1050,11 +1207,11 @@ class Steps(unittest.TestCase):
|
||||
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
|
||||
off_ladder = Route(Rung("worker-model"))
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
|
||||
self.assertEqual(main.after_verdict(run_with, None, run.Concluded(Unfinished("new", 4, "round 2: 🔴", entries_read=9), off_ladder)).route, off_ladder)
|
||||
self.assertEqual(main.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder)
|
||||
|
||||
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 0, "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
|
||||
|
||||
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
|
||||
@@ -1067,7 +1224,7 @@ class Steps(unittest.TestCase):
|
||||
before = Route(self.OPUS, 3, 3, 4)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", 4), before))
|
||||
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before))
|
||||
self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
|
||||
self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, after.route, FakeEffects().effects()))
|
||||
@@ -1089,12 +1246,18 @@ class Steps(unittest.TestCase):
|
||||
before = Route(self.OPUS, 3, 3, 4)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", highest_escape_and_impact_taken_in=6), before))
|
||||
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before))
|
||||
self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
|
||||
self.assertEqual(main.archived_route(archive, opened, FakeEffects().effects()), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
|
||||
|
||||
|
||||
class ChunkFacts(unittest.TestCase):
|
||||
def test_names_the_routed_item_then_each_taken_in_once_by_its_tagline_on_the_default_branch(self):
|
||||
self.assertEqual(running_loops.taken_items(TODO, 3, (99, 3, 99)), (Taken(3, "Do the next thing."), Taken(99, "")))
|
||||
self.assertEqual(running_loops.taken_items(TODO, 0, (3,)), (Taken(3, "Do the next thing."),))
|
||||
self.assertEqual(running_loops.taken_items(Failure("no todo.md"), 3, ()), (Taken(3, ""),))
|
||||
self.assertEqual(running_loops.taken_items(TODO, 0, ()), ())
|
||||
|
||||
PREFLIGHT = pathlib.Path("/b/chunk-preflight")
|
||||
|
||||
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
|
||||
@@ -1136,6 +1299,57 @@ class LocalTime(unittest.TestCase):
|
||||
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
|
||||
|
||||
|
||||
class Alive(unittest.TestCase):
|
||||
def test_a_process_that_runs_is_alive_and_one_that_ended_is_not(self):
|
||||
ended = subprocess.Popen([sys.executable, "-c", "pass"])
|
||||
ended.wait()
|
||||
# Unless this process runs as root, it may not signal pid 1, which still runs.
|
||||
self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True])
|
||||
|
||||
|
||||
class SessionLock(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
self.path = session_lock.lock_file(self.folder, "s1")
|
||||
|
||||
def test_a_held_lock_refuses_a_second_taker_and_reads_as_running_until_let_go(self):
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
with session_lock.held(self.folder, "s1") as first:
|
||||
self.assertIsNone(first)
|
||||
with session_lock.held(self.folder, "s1") as second:
|
||||
self.assertEqual(second, Failure(f"another process holds {self.path}"))
|
||||
self.assertTrue(session_lock.running(self.folder, "s1"))
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
|
||||
def test_a_lock_that_cannot_be_opened_is_a_failure_and_no_loop_running(self):
|
||||
self.path.mkdir()
|
||||
with session_lock.held(self.folder, "s1") as unlocked:
|
||||
self.assertEqual(unlocked, Failure(f"cannot open {self.path}: Is a directory"))
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
|
||||
def test_a_lock_the_kernel_refuses_is_a_failure_and_no_loop_running(self):
|
||||
self.path.touch()
|
||||
with unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")):
|
||||
with session_lock.held(self.folder, "s1") as unlocked:
|
||||
self.assertEqual(unlocked, Failure(f"cannot lock {self.path}: No locks available"))
|
||||
self.assertFalse(session_lock.running(self.folder, "s1"))
|
||||
|
||||
|
||||
class ClaudeOnTerminal(unittest.TestCase):
|
||||
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
|
||||
caught = []
|
||||
self.addCleanup(signal.signal, signal.SIGINT, signal.signal(signal.SIGINT, lambda number, frame: caught.append(number)))
|
||||
before = signal.getsignal(signal.SIGINT)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
claude = pathlib.Path(folder, "claude")
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns.
|
||||
claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n")
|
||||
claude.chmod(0o755)
|
||||
code = system_effects().claude_on_terminal([], folder, {"PATH": folder})
|
||||
self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before))
|
||||
|
||||
|
||||
class PythonEffect(unittest.TestCase):
|
||||
def test_runs_a_script_in_the_given_directory(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
@@ -1174,6 +1388,7 @@ class TypedAnswers(unittest.TestCase):
|
||||
class WorkerArgs(unittest.TestCase):
|
||||
SCAN = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."
|
||||
SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung."
|
||||
MARKDOWN = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
|
||||
# What the preflight found, as the fresh prompt quotes it.
|
||||
FACTS = "- A preflight fact."
|
||||
|
||||
@@ -1211,7 +1426,7 @@ class WorkerArgs(unittest.TestCase):
|
||||
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, self.FACTS)
|
||||
self.assertIn("whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", level)
|
||||
self.assertIn(f"whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", level)
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, self.FACTS)
|
||||
self.assertIn(f"whether or not it is item 3. Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
|
||||
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 6), opus))
|
||||
@@ -1227,17 +1442,17 @@ class WorkerArgs(unittest.TestCase):
|
||||
|
||||
def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort max, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort max` from 8. When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
|
||||
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort max, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
|
||||
|
||||
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus, self.FACTS)
|
||||
stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)
|
||||
self.assertIn(f"{prompts.ANSWERS_RECORDED}. loop-claude runs you on claude-opus-5-5 at high effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", stepped_up)
|
||||
self.assertIn(f"{prompts.ANSWERS_RECORDED}. loop-claude runs you on claude-opus-5-5 at high effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
|
||||
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus))
|
||||
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertIn(f"whether or not it is item 3.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", above)
|
||||
self.assertIn(f"whether or not it is item 3.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", above)
|
||||
|
||||
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
@@ -1259,17 +1474,24 @@ class WorkerArgs(unittest.TestCase):
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
|
||||
|
||||
def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
|
||||
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), opus, self.FACTS))
|
||||
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus))
|
||||
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
|
||||
def test_launches_each_pass_a_replay_lowered_on_its_replays_rung_and_reruns_it_one_above(self):
|
||||
opus, haiku = Rung("claude-opus-5-5", "medium"), Rung("claude-haiku-5-5", "low")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku}):
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
|
||||
on_it = prompts.resumed("", Route(haiku, 3, 1, 4), opus)
|
||||
launched = " Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung. Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose."
|
||||
rerun = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead."
|
||||
opus, sonnet = Rung("claude-opus-5-5", "medium"), Rung("claude-sonnet-5-5", "high")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): sonnet}):
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(sonnet, 3, 2, 4), opus, self.FACTS)
|
||||
on_it = prompts.resumed("", Route(sonnet, 3, 1, 4), opus)
|
||||
launched = " Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung. Launch each prose-reviewer instead with the Agent tool set to model sonnet, effort high, the rung the replay of its pass chose."
|
||||
rerun = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model opus, effort medium` instead."
|
||||
self.assertIn(f"whether or not it is item 3.{launched}", below)
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5,", below)
|
||||
self.assertIn(f"{rerun} After your first read", below)
|
||||
self.assertIn(f"loop-claude runs you on claude-haiku-5-5 at low effort.{launched}", on_it)
|
||||
self.assertIn(f"loop-claude runs you on claude-sonnet-5-5 at high effort.{launched}", on_it)
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 5 or more,", on_it)
|
||||
self.assertTrue(on_it.endswith(rerun))
|
||||
|
||||
@@ -1376,8 +1598,8 @@ class JudgePrompt(unittest.TestCase):
|
||||
def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
|
||||
_, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "old x", entries_read=3), grounds), Unfinished("e", entries_read=3))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "new", entries_read=3), grounds), Unfinished("e", 0, "new", entries_read=3))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", "old x", entries_read=3), grounds), Unfinished("e", entries_read=3))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3))
|
||||
|
||||
def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self):
|
||||
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
|
||||
@@ -1407,58 +1629,68 @@ class Grounded(unittest.TestCase):
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_needs_every_field_the_schema_requires(self):
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"items_taken_in": [], "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
def test_takes_the_highest_l_taken_in_on_its_scale_and_counts_any_other_as_none(self):
|
||||
reply = {"answer": "", "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Unfinished("e", 4))
|
||||
reply = {"items_taken_in": [], "answer": "", "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Unfinished("e", taken_in=TakenIn(highest_likelihood=4)))
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": True}), Failure("the judge's reply has no highest_likelihood_taken_in of type integer"))
|
||||
for highest_likelihood_taken_in in (5, 13, -1):
|
||||
with self.subTest(highest_likelihood_taken_in=highest_likelihood_taken_in):
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": highest_likelihood_taken_in}), Unfinished("e", 0))
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": highest_likelihood_taken_in}), Unfinished("e"))
|
||||
|
||||
|
||||
def test_takes_the_highest_e_plus_i_taken_in_on_its_scale_and_counts_any_other_as_none(self):
|
||||
reply = {"answer": "", "highest_likelihood_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 6}), Unfinished("e", 0, highest_escape_and_impact_taken_in=6))
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 2}), Unfinished("e", 0, highest_escape_and_impact_taken_in=2))
|
||||
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 6}), Unfinished("e", taken_in=TakenIn(highest_escape_and_impact=6)))
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 2}), Unfinished("e", taken_in=TakenIn(highest_escape_and_impact=2)))
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": False}), Failure("the judge's reply has no highest_escape_and_impact_taken_in of type integer"))
|
||||
for escape_and_impact in (1, 9, -1):
|
||||
with self.subTest(escape_and_impact=escape_and_impact):
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": escape_and_impact}), Unfinished("e", 0))
|
||||
self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": escape_and_impact}), Unfinished("e"))
|
||||
|
||||
def test_takes_the_items_taken_in_as_the_judge_gives_them_leaving_out_ids_below_1(self):
|
||||
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": [12, 14, 12]}), Unfinished("e", taken_in=TakenIn((12, 14, 12))))
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": [7, 0]}), Unfinished("e", taken_in=TakenIn((7,))))
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": [3], "interrupt": True, "question": "Which one?"}), Interrupt("e", "Which one?", taken_in=TakenIn((3,))))
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": [3], "answer": "A.", "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.", taken_in=TakenIn((3,))))
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": [3], "finished": True}), Finished("e"))
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": "3"}), Failure("the judge's reply has no items_taken_in of type array of integers"))
|
||||
self.assertEqual(verdict_from({**reply, "items_taken_in": ["3"]}), Failure("the judge's reply has no items_taken_in of type array of integers"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
|
||||
reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Unfinished("e", 0, "round 2: 🔴"))
|
||||
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴"))
|
||||
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
|
||||
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_interrupt(self):
|
||||
reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
|
||||
reply = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4))
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 4}), Interrupt("e", "Which one?", "round 2: 🔴", TakenIn(highest_likelihood=4)))
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
|
||||
shown = "The agent: round 2: 🔴. Which one?"
|
||||
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q", "round 2: 🔴"))
|
||||
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q"))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
|
||||
|
||||
def test_takes_an_escalation_quote_and_the_highest_l_taken_in_on_a_quoted_answer(self):
|
||||
reply = {"answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", 4))
|
||||
reply = {"items_taken_in": [], "answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", TakenIn(highest_likelihood=4)))
|
||||
self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
|
||||
@@ -1467,7 +1699,8 @@ class Verdict(unittest.TestCase):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A."))
|
||||
|
||||
def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", 4), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", 4))
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", taken_in=TakenIn((3,))), judge.Grounds("shown", "shown", "A.")), Interrupt("e", "q", taken_in=TakenIn((3,))))
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", TakenIn(highest_likelihood=4)), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4)))
|
||||
|
||||
def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("e", "q"))
|
||||
@@ -1477,9 +1710,9 @@ class Verdict(unittest.TestCase):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})]
|
||||
def judged_on(mark, escalation):
|
||||
return judge.judge_once("/r", "Do it.", "## Goals", "", entries, mark, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects())
|
||||
self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", 0, "round 2: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", "round 2: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", 0, "round 3: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", "round 3: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 2: 🔴\n\nround 3: 🔴"), Unfinished("working", entries_read=3))
|
||||
self.assertEqual(judged_on(3, "round 3: 🔴"), Unfinished("working", entries_read=3))
|
||||
|
||||
@@ -1539,6 +1772,13 @@ class LoopRuns(unittest.TestCase):
|
||||
def test_decodes_a_state_from_before_a_field_with_a_default_joined_it(self):
|
||||
self.assertEqual(reload.decode_handed(json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": ""}), main.LoopRun), main.LoopRun(3, "/r", "do it", ""))
|
||||
|
||||
def test_decodes_the_items_taken_in_as_a_tuple_of_ids(self):
|
||||
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", items_taken_in=(12, 14))
|
||||
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state)), main.LoopRun), state)
|
||||
for taken_in in ([12, "14"], [True], "12", {"12": 1}):
|
||||
with self.subTest(taken_in=taken_in):
|
||||
self.assertIsNone(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": taken_in}), main.LoopRun))
|
||||
|
||||
def test_stops_when_the_reload_cannot_start_python(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
launcher = pathlib.Path(root, "loop-claude")
|
||||
@@ -1570,9 +1810,9 @@ class ExitContract(unittest.TestCase):
|
||||
unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
|
||||
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("cycle/interrupt.py", "talk", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/interrupt.py", "claude_open", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "human_typed", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
|
||||
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
|
||||
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
|
||||
|
||||
@@ -2,14 +2,24 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TakenIn:
|
||||
"""What the judge read in the transcript about the todo.md items the worker took into the chunk, the item the chunk was routed on included."""
|
||||
# Their IDs; loop-inbox lists them.
|
||||
items: tuple[int, ...] = ()
|
||||
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
|
||||
highest_likelihood: int = 0
|
||||
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's judge and reviewers.
|
||||
highest_escape_and_impact: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
||||
escalation: str = ""
|
||||
# The highest L the judge saw the worker take into the chunk, 0 for none: an escalation steps up from the rung that L picks.
|
||||
highest_likelihood_taken_in: int = 0
|
||||
taken_in: TakenIn = TakenIn()
|
||||
release_ready: bool = False
|
||||
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
|
||||
entries_read: int | None = None
|
||||
@@ -23,7 +33,7 @@ class QuotedAnswer:
|
||||
answer: str
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
highest_likelihood_taken_in: int = 0
|
||||
taken_in: TakenIn = TakenIn()
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
@@ -35,13 +45,9 @@ class Finished:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unfinished:
|
||||
evidence: str
|
||||
# As on Interrupt; the worker also rises to the rung that L picks.
|
||||
highest_likelihood_taken_in: int = 0
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
# The highest E + I the judge saw the worker take into the chunk, 0 for none.
|
||||
highest_escape_and_impact_taken_in: int = 0
|
||||
# As on Interrupt.
|
||||
taken_in: TakenIn = TakenIn()
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
|
||||
|
||||
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
|
||||
<session> is the worker's session id, so a loop lists one question at a time. The loop removes the ask once the question
|
||||
is answered or the loop stops. loop-inbox lists an ask only while the loop holds the session's lock (running_loops.py),
|
||||
and removes one whose lock is free. The ask's state says whether the loop waits for an answer, or has claude open for
|
||||
it, on the loop's own terminal or in loop-inbox. loop-inbox answers by replacing <session>.answer, which names the
|
||||
ask's id. So an answer meant for an earlier question, or sent as the loop took an answer on its terminal,
|
||||
never answers a later one.
|
||||
|
||||
/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
|
||||
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
|
||||
2. The loop stops reading its terminal, and its make_way lists the ask as OpenInInbox with that pid. claim_talk
|
||||
returns True once it reads that, and loop-inbox opens claude.
|
||||
3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with claude_ended. The loop also stops waiting
|
||||
if loop-inbox's process is gone.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from loop_claude.session_lock import ended, running
|
||||
from failure import Failure
|
||||
from file_writes import make_private, replace_json
|
||||
|
||||
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
|
||||
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
|
||||
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
|
||||
TALK = "/talk"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Asking:
|
||||
"""The ask waits for an answer; talk opens the worker's claude session for /talk."""
|
||||
talk: ClaudeCommand
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class OpenOnTerminal:
|
||||
"""claude is open for the ask on the loop's own terminal; the loop takes no answer from loop-inbox."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class OpenInInbox:
|
||||
"""claude is open for the ask in the loop-inbox whose process is pid."""
|
||||
pid: int
|
||||
|
||||
|
||||
AskState = Asking | OpenOnTerminal | OpenInInbox
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ask:
|
||||
"""An interrupt's question, as loop-inbox lists it."""
|
||||
id: str
|
||||
session: str
|
||||
# The checkout the loop runs in.
|
||||
root: str
|
||||
question: str
|
||||
# When the loop asked, in seconds since the epoch.
|
||||
asked: float
|
||||
state: AskState
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Typed:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeOpening:
|
||||
"""loop-inbox, whose process is pid, asks the loop to make way for the claude it opens for /talk."""
|
||||
pid: int
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeEnded:
|
||||
"""The claude loop-inbox opened for the ask has ended."""
|
||||
|
||||
|
||||
# What answers a waiting ask.
|
||||
Answer = Typed | ClaudeOpening
|
||||
Message = Answer | ClaudeEnded
|
||||
|
||||
|
||||
def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.json"
|
||||
|
||||
|
||||
def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.answer"
|
||||
|
||||
|
||||
def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
|
||||
try:
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot make {folder}: {failure.strerror}")
|
||||
return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask) | {"state": tagged(ask.state)})
|
||||
|
||||
|
||||
def withdraw(folder: pathlib.Path, session: str) -> Failure | None:
|
||||
"""Removes the session's ask and any answer to it."""
|
||||
for path in (ask_file(folder, session), answer_file(folder, session)):
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot remove {path}: {failure.strerror}")
|
||||
return None
|
||||
|
||||
|
||||
def shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
|
||||
"""Lists ask in loop-inbox, in its state. A failure only warns: the question is still answered on the loop's terminal."""
|
||||
if unshown := publish(folder, ask):
|
||||
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
|
||||
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to list it only warns: the question is still answered on the loop's terminal.
|
||||
|
||||
listed doesn't take the session's lock, which loop-inbox needs held to list the ask. Pass the folder running_loops.shown_running yields: shown_running holds the lock for the loop's whole run.
|
||||
"""
|
||||
shown(folder, ask, effects)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
# An ask this fails to remove is left to loop-inbox, which stops listing it once the lock is let go, and removes it.
|
||||
withdraw(folder, ask.session)
|
||||
|
||||
|
||||
def waiting(folder: pathlib.Path) -> list[Ask]:
|
||||
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
|
||||
try:
|
||||
paths = sorted(folder.glob("*.json"))
|
||||
except OSError:
|
||||
return []
|
||||
asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)]
|
||||
return sorted(asks, key=lambda ask: ask.asked)
|
||||
|
||||
|
||||
def drop_ended(folder: pathlib.Path) -> None:
|
||||
"""Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. An ask it cannot remove stays on disk, and waiting leaves it out all the same."""
|
||||
for session in ended(folder, "*.json"):
|
||||
withdraw(folder, session)
|
||||
|
||||
|
||||
def read_ask(path: pathlib.Path) -> Ask | None:
|
||||
"""The ask in path; None where a field has the wrong type, or names another session than path does."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
ask = Ask(**{**data, "state": ask_state(data["state"])})
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return None
|
||||
texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question))
|
||||
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) else None
|
||||
|
||||
|
||||
def ask_state(data: object) -> AskState:
|
||||
match data:
|
||||
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}} if all(isinstance(text, str) for text in [*args, *env.values()]):
|
||||
return Asking(ClaudeCommand(args, cwd, env))
|
||||
case {"kind": "OpenOnTerminal"}:
|
||||
return OpenOnTerminal()
|
||||
case {"kind": "OpenInInbox", "pid": int(pid)}:
|
||||
return OpenInInbox(pid)
|
||||
raise ValueError(f"not an ask's state: {data!r}")
|
||||
|
||||
|
||||
def send(folder: pathlib.Path, ask: Ask, message: Message) -> Failure | None:
|
||||
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **tagged(message)})
|
||||
|
||||
|
||||
def tagged(value: AskState | Message) -> dict[str, object]:
|
||||
"""value's fields, with its kind, which read_ask and received read it back by."""
|
||||
return dataclasses.asdict(value) | {"kind": type(value).__name__}
|
||||
|
||||
|
||||
def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
|
||||
"""The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session."""
|
||||
message = received(folder, ask)
|
||||
return message if isinstance(message, Typed | ClaudeOpening) else None
|
||||
|
||||
|
||||
def claude_ended(folder: pathlib.Path, ask: Ask) -> bool:
|
||||
"""Whether loop-inbox said the claude it opened for this ask has ended."""
|
||||
return isinstance(received(folder, ask), ClaudeEnded)
|
||||
|
||||
|
||||
def received(folder: pathlib.Path, ask: Ask) -> Message | None:
|
||||
try:
|
||||
data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, dict) or data.get("ask") != ask.id:
|
||||
return None
|
||||
match data:
|
||||
case {"kind": "Typed", "text": str(text)}:
|
||||
return Typed(text)
|
||||
# alive is always True for a pid of 0 or below, which names a process group or every process, so the loop would wait for claude forever.
|
||||
case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0:
|
||||
return ClaudeOpening(pid)
|
||||
case {"kind": "ClaudeEnded"}:
|
||||
return ClaudeEnded()
|
||||
return None
|
||||
|
||||
|
||||
def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure:
|
||||
"""loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, stopped, made way for another loop-inbox, or didn't make way in time."""
|
||||
if unsent := send(folder, ask, ClaudeOpening(pid)):
|
||||
return unsent
|
||||
deadline = now() + MAKE_WAY_SECONDS
|
||||
while now() < deadline:
|
||||
current = read_ask(ask_file(folder, ask.session))
|
||||
if current is None or current.id != ask.id:
|
||||
return False
|
||||
if current.state == OpenInInbox(pid):
|
||||
return True
|
||||
if not isinstance(current.state, Asking):
|
||||
return False
|
||||
sleep(0.1)
|
||||
# Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait.
|
||||
send(folder, ask, ClaudeEnded())
|
||||
return False
|
||||
|
||||
|
||||
def make_way(folder: pathlib.Path, ask: Ask, pid: int, effects: Effects) -> None:
|
||||
"""The loop's side of /talk from loop-inbox, once it has stopped reading its terminal: lists ask as having claude open in the loop-inbox whose process is pid, which claim_talk waits for. A failure only warns: claim_talk then gives up, and the loop stops."""
|
||||
shown(folder, dataclasses.replace(ask, state=OpenInInbox(pid)), effects)
|
||||
@@ -0,0 +1,178 @@
|
||||
"""What loop-inbox shows, and what each key does there: the core that main.py's curses screen runs.
|
||||
|
||||
How it shows the loops and a question was picked on 2026-10-28 by a bench of three readers seated as the README's
|
||||
audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it: a block per
|
||||
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone doesn't stop the loop.
|
||||
A second bench, on 2026-10-29, picked the running loops' section: below the waiting loops, a line per loop with its
|
||||
checkout and its number in the list above where it waits for an answer, then a line per item its chunk takes, with its ID and tagline.
|
||||
"""
|
||||
import dataclasses
|
||||
import textwrap
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, TALK
|
||||
from loop_claude.running_loops import RunningLoop, Taken
|
||||
|
||||
ENTER = "enter"
|
||||
BACKSPACE = "backspace"
|
||||
ESCAPE = "escape"
|
||||
# Lines of a question the list shows; the answer screen shows as much as fits.
|
||||
SHOWN_LINES = 2
|
||||
QUIT = "q"
|
||||
ANSWER_PROMPT = f"Answer ({TALK} opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting):"
|
||||
INDENT = " "
|
||||
ELLIPSIS = "…"
|
||||
NARROWEST = 20
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listing:
|
||||
"""The waiting and running loops as they were when the human began typing a number, so a loop's number doesn't change while they type it."""
|
||||
shown: tuple[Ask, ...] = ()
|
||||
typed: str = ""
|
||||
note: str = ""
|
||||
running: tuple[RunningLoop, ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Answering:
|
||||
ask: Ask
|
||||
typed: str = ""
|
||||
|
||||
|
||||
Screen = Listing | Answering
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Send:
|
||||
ask: Ask
|
||||
text: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Open:
|
||||
"""Opens the worker's claude session for /talk."""
|
||||
ask: Ask
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Quit:
|
||||
pass
|
||||
|
||||
|
||||
def pressed(screen: Screen, key: str) -> Screen | Send | Open | Quit:
|
||||
"""What follows key, which is ENTER, BACKSPACE, ESCAPE or one character typed."""
|
||||
match screen:
|
||||
case Listing(shown, typed):
|
||||
if key == QUIT and not typed:
|
||||
return Quit()
|
||||
if key == ENTER:
|
||||
return picked(shown, typed)
|
||||
if key == BACKSPACE:
|
||||
return dataclasses.replace(screen, typed=typed[:-1], note="")
|
||||
# isdigit would also take "²", which int() rejects.
|
||||
return dataclasses.replace(screen, typed=typed + key, note="") if key.isdecimal() else screen
|
||||
case Answering(ask, typed):
|
||||
if key == ESCAPE or (key == ENTER and not typed.strip()):
|
||||
return Listing()
|
||||
if key == ENTER:
|
||||
return Open(ask) if typed.strip() == TALK else Send(ask, typed.strip())
|
||||
if key == BACKSPACE:
|
||||
return Answering(ask, typed[:-1])
|
||||
return Answering(ask, typed + key) if len(key) == 1 and key.isprintable() else screen
|
||||
case _:
|
||||
typing.assert_never(screen)
|
||||
|
||||
|
||||
def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering:
|
||||
if not typed:
|
||||
return Listing()
|
||||
number = int(typed)
|
||||
if not 1 <= number <= len(shown):
|
||||
return Listing(note=f"No loop has the number {number}.")
|
||||
ask = shown[number - 1]
|
||||
if not isinstance(ask.state, Asking):
|
||||
return Listing(note=f"{ask.root}: claude is open {where_open(ask.state)}; answer there.")
|
||||
return Answering(ask)
|
||||
|
||||
|
||||
def where_open(state: OpenOnTerminal | OpenInInbox) -> str:
|
||||
return "in loop-inbox" if isinstance(state, OpenInInbox) else "on its terminal"
|
||||
|
||||
|
||||
def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]:
|
||||
"""The list, in lines of at most width characters, and its foot: the note, what the keys do, and the prompt for a number."""
|
||||
count = len(screen.shown)
|
||||
head = "No loop waits for you." if not count else "1 loop waits for you." if count == 1 else f"{count} loops wait for you, oldest first."
|
||||
lines = [*wrapped(head, width), ""]
|
||||
for number, ask in enumerate(screen.shown, 1):
|
||||
state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}"
|
||||
lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width)
|
||||
lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES)
|
||||
lines.append("")
|
||||
lines += running_lines(screen.running, screen.shown, width)
|
||||
ask_for = "Type a number and Enter to answer that loop; " if count else ""
|
||||
return lines, [*wrapped(screen.note, width), *wrapped(f"{ask_for}{QUIT} quits loop-inbox, and the loops keep waiting.", width), *typed_after(">", screen.typed, width)]
|
||||
|
||||
|
||||
def running_lines(running: tuple[RunningLoop, ...], shown: tuple[Ask, ...], width: int) -> list[str]:
|
||||
"""Each running loop's checkout, with its number in the waiting list where it waits for an answer, and a line per item its chunk takes."""
|
||||
if not running:
|
||||
return ["No loop runs."]
|
||||
numbers = {ask.session: number for number, ask in enumerate(shown, 1)}
|
||||
lines = wrapped(f"Running: {len(running)} loop{'s' if len(running) > 1 else ''}", width)
|
||||
for loop in running:
|
||||
waits_as = f", waiting as [{numbers[loop.session]}]" if loop.session in numbers else ""
|
||||
lines += wrapped(f"- {loop.root}{waits_as}", width)
|
||||
for item in loop.items or (None,):
|
||||
lines += cut(wrapped(item_line(item), width - len(INDENT) - len(ELLIPSIS)), 1)
|
||||
return lines
|
||||
|
||||
|
||||
def item_line(item: Taken | None) -> str:
|
||||
if item is None:
|
||||
return "no todo.md item yet"
|
||||
return f"item {item.id}: {item.tagline}" if item.tagline else f"item {item.id}"
|
||||
|
||||
|
||||
def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]:
|
||||
"""The question, in lines of at most width characters, and its foot, the prompt for the answer."""
|
||||
ask = screen.ask
|
||||
head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):"
|
||||
return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width)
|
||||
|
||||
|
||||
def fitted(lines: list[str], foot: list[str], height: int) -> list[str]:
|
||||
"""lines, then foot, cut to height: lines lose their end first, and the cut is marked with an ellipsis."""
|
||||
if len(lines) + len(foot) <= height:
|
||||
return [*lines, *foot]
|
||||
return [*lines[: max(height - len(foot) - 1, 0)], ELLIPSIS, *foot][-height:]
|
||||
|
||||
|
||||
def wrapped(text: str, width: int) -> list[str]:
|
||||
return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, NARROWEST)) or [""]]
|
||||
|
||||
|
||||
def typed_after(prompt: str, typed: str, width: int) -> list[str]:
|
||||
"""prompt wrapped to width, then what the human typed after it, cut every width characters so that each space typed shows."""
|
||||
*lines, last = wrapped(prompt, width)
|
||||
line = f"{last} {typed}"
|
||||
step = max(width, NARROWEST)
|
||||
return [*lines, *(line[start : start + step] for start in range(0, len(line), step))]
|
||||
|
||||
|
||||
def cut(lines: list[str], count: int) -> list[str]:
|
||||
"""The first count lines, indented; a cut is marked with an ellipsis."""
|
||||
shown = [f"{INDENT}{line}" for line in lines[:count]]
|
||||
return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown
|
||||
|
||||
|
||||
def waited(seconds: float) -> str:
|
||||
minutes = int(seconds // 60)
|
||||
if minutes < 60:
|
||||
return f"{minutes} min"
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
if hours < 24:
|
||||
return f"{hours} h {minutes} min"
|
||||
days, hours = divmod(hours, 24)
|
||||
return f"{days} d {hours} h"
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Show the interrupts of every loop-claude on this machine, oldest first, and answer each one here.
|
||||
Below them, list every loop-claude that runs and the todo.md items its chunk takes.
|
||||
|
||||
usage: loop-inbox
|
||||
|
||||
Each loop-claude lists its interrupt here, as well as on its own terminal, until it is answered or
|
||||
the loop stops. The list shows each loop's checkout, when it asked and how long it has waited, and
|
||||
the question's first lines; it refreshes every second. Type a loop's number and Enter to see as much
|
||||
of its question as fits; the loop's terminal shows it whole. Answer as on the loop's terminal:
|
||||
|
||||
- A line and Enter sends it to that loop, which goes on with it. Of a pasted answer, only the first
|
||||
line is sent, and the rest is dropped; a longer answer goes through /talk.
|
||||
- /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's
|
||||
terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what
|
||||
you typed; if you typed nothing, the loop stops.
|
||||
- Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop.
|
||||
|
||||
The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no
|
||||
loop-inbox running. A loop with claude open, for a release ready to cut, the routing calls or a
|
||||
/talk, says where, and is answered there. A loop whose process is gone drops off the list. A loop
|
||||
asking for its project's model, as on a project's first run, asks on its own terminal only. q quits
|
||||
loop-inbox; the loops keep waiting.
|
||||
|
||||
Below the questions, loop-inbox lists each running loop: its checkout, its number in the list
|
||||
above where it waits for an answer, and a line per todo.md item its chunk takes, with the item's
|
||||
tagline on the default branch. A loop whose process is gone drops off this list too.
|
||||
|
||||
The loops' questions are files in ~/.local/state/loop-claude, read and written as
|
||||
bin/loop_claude/waiting.py describes; the running loops are files beside them, as
|
||||
bin/loop_claude/running_loops.py describes.
|
||||
|
||||
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
|
||||
"""
|
||||
import contextlib
|
||||
import curses
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
|
||||
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, drop_ended, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
|
||||
from loop_claude.running_loops import drop_ended_loops, running_loops
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from loop_claude.hand_over import hand_over
|
||||
from loop_claude.paths import Paths, paths_from
|
||||
from loop_claude.session_lock import running
|
||||
|
||||
USAGE = "usage: loop-inbox"
|
||||
# Milliseconds between refreshes of the list while no key is pressed.
|
||||
REFRESH_MS = 1000
|
||||
KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE}
|
||||
|
||||
|
||||
def main(argv: list[str], home: pathlib.Path) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if argv:
|
||||
print(f"loop-inbox: unknown argument {argv[0]}; {USAGE}", file=sys.stderr)
|
||||
return 2
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr)
|
||||
return 2
|
||||
# curses may hold keys it has read ahead, which only flushinp drops.
|
||||
effects = dataclasses.replace(system_effects(), discard_typed=curses.flushinp)
|
||||
try:
|
||||
curses.wrapper(lambda window: run(window, lambda: off_screen(window), paths_from(home), effects))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, effects: Effects) -> None:
|
||||
folder = paths.waiting
|
||||
window.timeout(REFRESH_MS)
|
||||
screen: Screen = Listing()
|
||||
while True:
|
||||
drop_ended(folder)
|
||||
drop_ended_loops(folder)
|
||||
screen = entered(screen, refreshed(screen, folder), effects)
|
||||
draw(window, screen, effects)
|
||||
try:
|
||||
key = window.get_wch()
|
||||
except curses.error:
|
||||
continue # No key within REFRESH_MS.
|
||||
after: Screen
|
||||
match pressed(screen, key_name(key)):
|
||||
case Quit():
|
||||
return
|
||||
case Send(ask, text):
|
||||
after = Listing(note=sent(folder, ask, text))
|
||||
case Open(ask):
|
||||
after = Listing(note=opened(screen_off, paths, ask, effects))
|
||||
case Listing() | Answering() as next_screen:
|
||||
after = next_screen
|
||||
screen = entered(screen, after, effects)
|
||||
|
||||
|
||||
def entered(before: Screen, after: Screen, effects: Effects) -> Screen:
|
||||
"""after, the screen that follows before. Leaving the answer screen drops the keys typed ahead, since on the list the rest of a pasted answer would pick a loop and answer it."""
|
||||
if isinstance(before, Answering) and isinstance(after, Listing):
|
||||
effects.discard_typed()
|
||||
return after
|
||||
|
||||
|
||||
def key_name(key: str | int) -> str:
|
||||
"""inbox's name for a key curses read; an empty string for a key loop-inbox has no use for, such as an arrow."""
|
||||
return KEYS.get(key, key if isinstance(key, str) else "")
|
||||
|
||||
|
||||
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
|
||||
"""screen with the loops as they wait and run now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
|
||||
match screen:
|
||||
case Listing(_, "", note):
|
||||
return Listing(tuple(waiting(folder)), "", note, tuple(running_loops(folder)))
|
||||
case Answering(ask) if not still_waits(folder, ask):
|
||||
return Listing(note=no_longer_waits(ask))
|
||||
return screen
|
||||
|
||||
|
||||
def draw(window: curses.window, screen: Screen, effects: Effects) -> None:
|
||||
height, columns = window.getmaxyx()
|
||||
# The screen's last cell cannot be written without an error, so lines leave the last column empty.
|
||||
width = columns - 1
|
||||
now = effects.now()
|
||||
lines, foot = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width)
|
||||
window.erase()
|
||||
for row, line in enumerate(fitted(lines, foot, height)):
|
||||
# addnstr counts characters, not cells, so a line of wide characters, such as emoji, can still run into the last cell.
|
||||
with contextlib.suppress(curses.error):
|
||||
window.addnstr(row, 0, line, width)
|
||||
window.refresh()
|
||||
|
||||
|
||||
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
|
||||
"""Whether ask's loop still runs and still waits for an answer from loop-inbox."""
|
||||
now = read_ask(ask_file(folder, ask.session))
|
||||
return now is not None and now.id == ask.id and isinstance(now.state, Asking) and running(folder, ask.session)
|
||||
|
||||
|
||||
def no_longer_waits(ask: Ask) -> str:
|
||||
return f"{ask.root} no longer waits for that answer: it was answered elsewhere, or stopped."
|
||||
|
||||
|
||||
def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
|
||||
"""Sends text to the loop that asked ask, and says what came of it."""
|
||||
if not still_waits(folder, ask):
|
||||
return no_longer_waits(ask)
|
||||
if unsent := send(folder, ask, Typed(text)):
|
||||
return f"Could not send the answer to {ask.root}: {unsent.reason}"
|
||||
return f"Sent to {ask.root}."
|
||||
|
||||
|
||||
def opened(screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, ask: Ask, effects: Effects) -> str:
|
||||
"""Opens the worker's claude session on this terminal, inside screen_off, once the loop has made way for it, and says what came of it."""
|
||||
folder = paths.waiting
|
||||
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
|
||||
return no_longer_waits(ask)
|
||||
claimed = claim_talk(folder, ask, effects.pid(), effects.now, effects.sleep)
|
||||
if isinstance(claimed, Failure):
|
||||
return f"Could not open claude for {ask.root}: {claimed.reason}"
|
||||
if not claimed:
|
||||
return f"Could not open claude for {ask.root}: the loop was answered elsewhere or stopped, or didn't respond within {MAKE_WAY_SECONDS:g} s. If it is still listed, pick it again."
|
||||
with screen_off():
|
||||
try:
|
||||
unstarted = hand_over(ask.state.talk, paths, effects)
|
||||
finally:
|
||||
unsent = send(folder, ask, ClaudeEnded())
|
||||
# The loop goes on only where the human typed in the worker's session, as interrupt.human_typed checks.
|
||||
said = f"Could not start claude for {ask.root}: {unstarted.reason}. The loop stops." if unstarted else f"claude for {ask.root} has ended; the loop goes on if you typed there, and stops if you didn't."
|
||||
# The loop also stops waiting for claude once loop-inbox's process ends.
|
||||
return f"{said} Could not tell the loop that claude ended: {unsent.reason}; it waits until you quit loop-inbox." if unsent else said
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def off_screen(window: curses.window) -> typing.Iterator[None]:
|
||||
"""Hands the terminal to another program, and draws loop-inbox again once it ends."""
|
||||
curses.def_prog_mode()
|
||||
curses.endwin()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
curses.reset_prog_mode()
|
||||
window.refresh()
|
||||
@@ -0,0 +1,600 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, Typed
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from failure import Failure
|
||||
from loop_inbox import inbox, main
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_claude import running_loops, session_lock, waiting
|
||||
from loop_claude.running_loops import RunningLoop, Taken
|
||||
from loop_claude.effects import system_effects
|
||||
|
||||
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
|
||||
# The pid of this loop-inbox.
|
||||
INBOX = 4343
|
||||
ANSWERED_ON_TERMINAL = object()
|
||||
|
||||
|
||||
def asked(session, root, question="Which one?", at=100.0, state=ASKING):
|
||||
return Ask(f"ask-{session}", session, root, question, at, state)
|
||||
|
||||
|
||||
def loops_hold(test, folder, *sessions):
|
||||
"""Holds each session's lock until the test ends, as a running loop does."""
|
||||
for session in sessions:
|
||||
test.enterContext(session_lock.held(folder, session))
|
||||
|
||||
|
||||
def asks_and_answers(folder):
|
||||
return sorted(path.name for path in folder.iterdir() if path.suffix != ".lock")
|
||||
|
||||
|
||||
def keyed(screen, *keys):
|
||||
for key in keys:
|
||||
screen = inbox.pressed(screen, key)
|
||||
return screen
|
||||
|
||||
|
||||
class OutOfKeys(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Window:
|
||||
"""A curses window that records the lines drawn on it, and hands out keys in turn, running each callable among them as it comes."""
|
||||
|
||||
def __init__(self, keys=(), height=24, width=80):
|
||||
self.keys, self.height, self.width = list(keys), height, width
|
||||
self.lines = {}
|
||||
|
||||
def getmaxyx(self):
|
||||
return self.height, self.width
|
||||
|
||||
def timeout(self, milliseconds):
|
||||
pass
|
||||
|
||||
def get_wch(self):
|
||||
while self.keys and callable(self.keys[0]):
|
||||
self.keys.pop(0)()
|
||||
if not self.keys:
|
||||
raise OutOfKeys
|
||||
return self.keys.pop(0)
|
||||
|
||||
def drop_typed(self):
|
||||
"""Drops the keys not yet read, as curses.flushinp does."""
|
||||
self.keys.clear()
|
||||
|
||||
def erase(self):
|
||||
self.lines = {}
|
||||
|
||||
def addnstr(self, row, column, text, count):
|
||||
self.lines[row] = text[:count]
|
||||
|
||||
def refresh(self):
|
||||
pass
|
||||
|
||||
|
||||
class Answers(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
loops_hold(self, self.folder, "s1", "s2")
|
||||
|
||||
def answer(self, number, text):
|
||||
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
|
||||
action = keyed(Listing(tuple(waiting.waiting(self.folder))), *number, ENTER, *text, ENTER)
|
||||
self.assertIsInstance(action, Send)
|
||||
return main.sent(self.folder, action.ask, action.text)
|
||||
|
||||
def test_two_waiting_loops_each_get_their_own_answer(self):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
for ask in (bender, log):
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(self.answer("2", "Use B."), "Sent to /code/bender.")
|
||||
self.assertEqual(self.answer("1", "Use A."), "Sent to /code/log.")
|
||||
self.assertEqual((waiting.answered(self.folder, log), waiting.answered(self.folder, bender)), (Typed("Use A."), Typed("Use B.")))
|
||||
|
||||
def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
for ask in (log, bender):
|
||||
waiting.publish(self.folder, ask)
|
||||
picked = keyed(Listing(tuple(waiting.waiting(self.folder))), "1", ENTER, "A", ENTER)
|
||||
# log is answered on its terminal before the answer typed here is sent; bender is now first.
|
||||
waiting.withdraw(self.folder, "s1")
|
||||
self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
|
||||
self.assertEqual(asks_and_answers(self.folder), ["s2.json"])
|
||||
|
||||
def test_the_list_shows_the_loops_still_waiting_and_keeps_its_note(self):
|
||||
log = asked("s1", "/code/log")
|
||||
for ask in (log, asked("s3", "/code/bender")):
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder), Listing((log,), "", "Sent to /a."))
|
||||
|
||||
def test_the_list_shows_the_loops_running_now(self):
|
||||
self.enterContext(running_loops.shown_running(self.folder, "s9", "/code/web", system_effects()))
|
||||
self.assertEqual(main.refreshed(Listing(), self.folder), Listing(running=(RunningLoop("s9", "/code/web", ()),)))
|
||||
|
||||
def test_a_number_picks_the_loop_it_had_when_the_human_began_typing_it(self):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
typing = keyed(Listing((log, bender)), "2")
|
||||
waiting.publish(self.folder, bender)
|
||||
self.assertEqual(main.refreshed(typing, self.folder), typing)
|
||||
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
|
||||
|
||||
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
|
||||
for state, where in ((OpenOnTerminal(), "on its terminal"), (OpenInInbox(7), "in loop-inbox")):
|
||||
with self.subTest(where=where):
|
||||
self.assertEqual(keyed(Listing((asked("s1", "/code/log", state=state),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
|
||||
|
||||
def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us"))
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped."))
|
||||
|
||||
def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self):
|
||||
ask = asked("s3", "/code/bender")
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped."))
|
||||
|
||||
def claim(self, ask, loop_does):
|
||||
"""claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait."""
|
||||
tenths = [0]
|
||||
def sleep(seconds):
|
||||
if not tenths[0]:
|
||||
loop_does()
|
||||
tenths[0] += round(seconds * 10)
|
||||
return waiting.claim_talk(self.folder, ask, INBOX, lambda: tenths[0] / 10, sleep), tenths[0] / 10
|
||||
|
||||
def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
def made_way_for_the_claim():
|
||||
claim = waiting.answered(self.folder, ask)
|
||||
if isinstance(claim, waiting.ClaudeOpening):
|
||||
waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid)))
|
||||
for loop_does, claimed in (
|
||||
(made_way_for_the_claim, (True, 0.1)),
|
||||
(lambda: waiting.withdraw(self.folder, "s1"), (False, 0.1)),
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)),
|
||||
(lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)),
|
||||
(lambda: None, (False, waiting.MAKE_WAY_SECONDS)),
|
||||
):
|
||||
with self.subTest(claimed=claimed):
|
||||
waiting.publish(self.folder, ask)
|
||||
self.assertEqual(self.claim(ask, loop_does), claimed)
|
||||
|
||||
def test_a_claim_the_loop_did_not_make_way_for_in_time_is_taken_back(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
waiting.publish(self.folder, ask)
|
||||
self.claim(ask, lambda: None)
|
||||
# A loop that reads it late ends its wait at once, as for a claude that has ended.
|
||||
self.assertEqual((waiting.answered(self.folder, ask), waiting.claude_ended(self.folder, ask)), (None, True))
|
||||
|
||||
|
||||
def never_opens(args, cwd, env):
|
||||
raise AssertionError("claude opened")
|
||||
|
||||
|
||||
class Opens(unittest.TestCase):
|
||||
def setUp(self):
|
||||
home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, home)
|
||||
self.paths = paths_from(home)
|
||||
self.ask = asked("s1", "/code/log")
|
||||
loops_hold(self, self.paths.waiting, "s1")
|
||||
waiting.publish(self.paths.waiting, self.ask)
|
||||
|
||||
def open(self, claude, loop_shows=OpenInInbox(INBOX)):
|
||||
"""What /talk in loop-inbox says for self.ask, whose loop shows loop_shows once claim_talk has asked it to make way; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended."""
|
||||
def loop_looks(_):
|
||||
waiting.publish(self.paths.waiting, dataclasses.replace(self.ask, state=loop_shows))
|
||||
effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=loop_looks)
|
||||
try:
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
return main.opened(contextlib.nullcontext, self.paths, self.ask, effects)
|
||||
finally:
|
||||
self.ended = waiting.claude_ended(self.paths.waiting, self.ask)
|
||||
|
||||
def test_tells_the_loop_once_claude_ends_or_cannot_start_and_says_what_the_loop_does(self):
|
||||
def unstarted(args, cwd, env):
|
||||
raise OSError(2, "No such file or directory")
|
||||
for claude, said in (
|
||||
(lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't."),
|
||||
(unstarted, "Could not start claude for /code/log: No such file or directory. The loop stops."),
|
||||
):
|
||||
with self.subTest(said=said):
|
||||
waiting.publish(self.paths.waiting, self.ask)
|
||||
self.assertEqual(self.open(claude), said)
|
||||
self.assertTrue(self.ended)
|
||||
|
||||
def test_says_the_loop_waits_for_loop_inbox_to_quit_where_it_cannot_tell_it_that_claude_ended(self):
|
||||
def folder_lost(args, cwd, env):
|
||||
shutil.rmtree(self.paths.waiting)
|
||||
self.paths.waiting.write_text("")
|
||||
said = "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't. Could not tell the loop that claude ended: Not a directory; it waits until you quit loop-inbox."
|
||||
self.assertEqual(self.open(folder_lost), said)
|
||||
|
||||
def test_opens_no_claude_for_a_loop_that_takes_talk_on_its_terminal_first(self):
|
||||
said = "Could not open claude for /code/log: the loop was answered elsewhere or stopped, or didn't respond within 5 s. If it is still listed, pick it again."
|
||||
self.assertEqual(self.open(never_opens, loop_shows=OpenOnTerminal()), said)
|
||||
|
||||
def test_opens_no_claude_and_sends_nothing_to_a_loop_that_no_longer_waits(self):
|
||||
waiting.withdraw(self.paths.waiting, "s1")
|
||||
self.assertEqual(self.open(never_opens), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_tells_the_loop_when_claude_is_interrupted(self):
|
||||
def interrupted(args, cwd, env):
|
||||
raise KeyboardInterrupt
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
self.open(interrupted)
|
||||
self.assertTrue(self.ended)
|
||||
|
||||
|
||||
class Typing(unittest.TestCase):
|
||||
def typed(self, *keys):
|
||||
"""What the log and bender loops get once keys are typed into loop-inbox, which lists log first. ANSWERED_ON_TERMINAL among the keys stands for log being answered on its terminal. Fails where loop-inbox quits before the keys run out."""
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
paths = paths_from(pathlib.Path(home))
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
loops_hold(self, paths.waiting, "s1", "s2")
|
||||
for ask in (log, bender):
|
||||
waiting.publish(paths.waiting, ask)
|
||||
def answered_on_terminal():
|
||||
waiting.withdraw(paths.waiting, "s1")
|
||||
window = Window(answered_on_terminal if key is ANSWERED_ON_TERMINAL else key for key in keys)
|
||||
def made_way(seconds):
|
||||
waiting.publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX)))
|
||||
effects = dataclasses.replace(system_effects(), claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way)
|
||||
with self.assertRaises(OutOfKeys), contextlib.redirect_stderr(io.StringIO()):
|
||||
main.run(window, contextlib.nullcontext, paths, effects)
|
||||
return waiting.answered(paths.waiting, log), waiting.answered(paths.waiting, bender)
|
||||
|
||||
def test_keys_typed_ahead_are_dropped_once_the_answer_screen_is_left(self):
|
||||
# Each case types, after leaving log's answer screen, a line that would pick bender and one that would answer it, or a line that would quit.
|
||||
for case, keys, got in (
|
||||
("a pasted answer", "1\nYes.\nSee item 2.\nThen release.\n", (Typed("Yes."), None)),
|
||||
("a pasted answer with a line that would quit", "1\nOk.\nquick check first\n", (Typed("Ok."), None)),
|
||||
("/talk", "1\n/talk\n2\nUse B.\n", (None, None)),
|
||||
("a paste that opens with an empty line", "1\n\nSee item 2.\nThen release.\n", (None, None)),
|
||||
("an answer typed as log is answered on its terminal", ["1", "\n", "U", "s", "e", ANSWERED_ON_TERMINAL, *" option 1.\nThen release.\n"], (None, None)),
|
||||
):
|
||||
with self.subTest(case):
|
||||
self.assertEqual(self.typed(*keys), got)
|
||||
|
||||
|
||||
class Keys(unittest.TestCase):
|
||||
def test_the_list_takes_a_number_and_quits_on_q(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
for keys, after in (
|
||||
(("q",), Quit()),
|
||||
(("1", "q"), Listing((ask,), "1")),
|
||||
(("1", "2", "3", BACKSPACE), Listing((ask,), "12")),
|
||||
(("x",), Listing((ask,))),
|
||||
(("²",), Listing((ask,))),
|
||||
((ENTER,), Listing()),
|
||||
(("2", ENTER), Listing(note="No loop has the number 2.")),
|
||||
(("1", ENTER), Answering(ask)),
|
||||
):
|
||||
with self.subTest(keys=keys):
|
||||
self.assertEqual(keyed(Listing((ask,)), *keys), after)
|
||||
|
||||
def test_a_number_typed_keeps_the_running_loops_shown_and_clears_the_note(self):
|
||||
running = (RunningLoop("s1", "/code/log", ()),)
|
||||
self.assertEqual(keyed(Listing(note="No loop has the number 7.", running=running), "1", "2", BACKSPACE), Listing((), "1", "", running))
|
||||
self.assertEqual(keyed(Listing(typed="1", note="No loop has the number 7.", running=running), BACKSPACE), Listing((), "", "", running))
|
||||
|
||||
def test_an_answer_is_sent_stripped_talk_opens_claude_and_enter_alone_or_esc_goes_back(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
for keys, after in (
|
||||
((*" Use B. ", ENTER), Send(ask, "Use B.")),
|
||||
((*" /talk", ENTER), Open(ask)),
|
||||
(("U", "s", "e", "x", BACKSPACE), Answering(ask, "Use")),
|
||||
((" ", ENTER), Listing()),
|
||||
(("U", ESCAPE), Listing()),
|
||||
(("\t",), Answering(ask)),
|
||||
):
|
||||
with self.subTest(keys=keys):
|
||||
self.assertEqual(keyed(Answering(ask), *keys), after)
|
||||
|
||||
def test_curses_keys_get_inboxs_names(self):
|
||||
for key, name in (("\n", ENTER), (main.curses.KEY_ENTER, ENTER), ("\x7f", BACKSPACE), (main.curses.KEY_BACKSPACE, BACKSPACE), ("\x1b", ESCAPE), ("a", "a"), (main.curses.KEY_LEFT, "")):
|
||||
with self.subTest(key=key):
|
||||
self.assertEqual(main.key_name(key), name)
|
||||
|
||||
|
||||
class Waiting(unittest.TestCase):
|
||||
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal())
|
||||
loops_hold(self, pathlib.Path(folder), "s1", "s2")
|
||||
for ask in (late, early, stopped):
|
||||
waiting.publish(pathlib.Path(folder), ask)
|
||||
pathlib.Path(folder, "s4.json").write_text("{")
|
||||
pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}')
|
||||
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
|
||||
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
|
||||
|
||||
def test_drops_and_removes_the_ask_a_killed_loop_left_behind(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, session_lock, system_effects, waiting\nwith session_lock.held(pathlib.Path(sys.argv[1]), 's1'), waiting.listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)"
|
||||
loop = subprocess.Popen([sys.executable, "-c", lists_and_waits, temp], cwd=pathlib.Path(__file__).parent, stdout=subprocess.PIPE)
|
||||
self.addCleanup(loop.wait)
|
||||
self.addCleanup(loop.kill)
|
||||
loop.stdout.readline()
|
||||
waiting.send(folder, asked("s1", "/a"), Typed("Use A."))
|
||||
self.assertEqual(waiting.waiting(folder), [asked("s1", "/a")])
|
||||
# SIGKILL runs none of the loop's cleanup.
|
||||
loop.kill()
|
||||
loop.wait()
|
||||
self.assertEqual(waiting.waiting(folder), [])
|
||||
waiting.drop_ended(folder)
|
||||
self.assertEqual(asks_and_answers(folder), [])
|
||||
|
||||
def test_loop_inbox_removes_a_killed_loops_ask_answer_and_running_file_as_it_looks(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
paths = paths_from(pathlib.Path(home))
|
||||
ask = asked("s1", "/a")
|
||||
waiting.publish(paths.waiting, ask)
|
||||
waiting.send(paths.waiting, ask, Typed("Use A."))
|
||||
running_loops.running_file(paths.waiting, "s1").write_text(json.dumps({"root": "/a", "items": []}))
|
||||
main.run(Window("q"), contextlib.nullcontext, paths, system_effects())
|
||||
self.assertEqual(asks_and_answers(paths.waiting), [])
|
||||
|
||||
def test_removes_only_the_asks_answers_and_running_files_whose_loop_has_ended_each_by_its_own_module(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
loops_hold(self, folder, "s1")
|
||||
for ask in (asked("s1", "/a"), asked("s2", "/b")):
|
||||
waiting.publish(folder, ask)
|
||||
waiting.send(folder, ask, Typed("Use A."))
|
||||
for session in ("s1", "s2", "s3"):
|
||||
running_loops.running_file(folder, session).write_text(json.dumps({"root": "/a", "items": []}))
|
||||
waiting.drop_ended(folder)
|
||||
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running", "s2.running", "s3.running"])
|
||||
running_loops.drop_ended_loops(folder)
|
||||
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running"])
|
||||
|
||||
def test_a_talk_claim_from_pid_0_or_below_is_no_answer_since_it_would_name_a_process_group(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
ask = asked("s1", "/a")
|
||||
for pid in (0, -1):
|
||||
with self.subTest(pid=pid):
|
||||
waiting.send(pathlib.Path(temp), ask, waiting.ClaudeOpening(pid))
|
||||
self.assertIsNone(waiting.answered(pathlib.Path(temp), ask))
|
||||
|
||||
def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
path = waiting.ask_file(pathlib.Path(temp), "s1")
|
||||
waiting.publish(path.parent, asked("s1", "/a"))
|
||||
good = json.loads(path.read_text())
|
||||
self.assertEqual(waiting.read_ask(path), asked("s1", "/a"))
|
||||
for field, value in (
|
||||
("id", 1),
|
||||
("session", "s2"),
|
||||
("root", None),
|
||||
("question", 3),
|
||||
("asked", "noon"),
|
||||
("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}),
|
||||
("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}),
|
||||
):
|
||||
with self.subTest(field=field, value=value):
|
||||
path.write_text(json.dumps(good | {field: value}))
|
||||
self.assertIsNone(waiting.read_ask(path))
|
||||
|
||||
def test_withdraw_says_what_it_cannot_remove(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp, "a file")
|
||||
folder.write_text("")
|
||||
self.assertEqual(waiting.withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory"))
|
||||
|
||||
def test_a_message_reaches_only_the_ask_it_names(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder, ask = pathlib.Path(temp), asked("s1", "/a")
|
||||
another = dataclasses.replace(ask, id="another")
|
||||
for message, answer, ended in ((Typed("A"), Typed("A"), False), (waiting.ClaudeOpening(7), waiting.ClaudeOpening(7), False), (waiting.ClaudeEnded(), None, True)):
|
||||
with self.subTest(message=message):
|
||||
waiting.send(folder, ask, message)
|
||||
self.assertEqual((waiting.answered(folder, ask), waiting.claude_ended(folder, ask)), (answer, ended))
|
||||
self.assertEqual((waiting.answered(folder, another), waiting.claude_ended(folder, another)), (None, False))
|
||||
|
||||
|
||||
class RunningLoops(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
self.effects = dataclasses.replace(system_effects(), sleep=lambda seconds: None)
|
||||
|
||||
def test_lists_a_loop_with_the_items_it_shows_until_it_ends(self):
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as listed:
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
|
||||
listed.show((Taken(255, "Have loop-inbox list every running loop."),))
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", (Taken(255, "Have loop-inbox list every running loop."),))])
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [])
|
||||
|
||||
def test_lists_the_loops_by_checkout_and_leaves_out_one_that_was_killed_or_whose_file_cannot_be_read(self):
|
||||
# Five, so the order the files are found in is unlikely to be the order by checkout.
|
||||
for session, root in (("s1", "/code/web"), ("s2", "/code/c"), ("s7", "/code/a"), ("s8", "/code/z"), ("s9", "/code/m")):
|
||||
self.enterContext(running_loops.shown_running(self.folder, session, root, self.effects))
|
||||
# A killed loop leaves its file behind, and its lock free.
|
||||
(self.folder / "s3.running").write_text(json.dumps({"root": "/code/old", "items": []}))
|
||||
for session, content in (("s4", "{"), ("s5", json.dumps({"root": "/code/x", "items": [{"id": "1", "tagline": ""}]})), ("s6", json.dumps({"root": "/code/x"})), ("s10", json.dumps({"root": "/code/x", "items": [{"id": True, "tagline": ""}]}))):
|
||||
self.enterContext(session_lock.held(self.folder, session))
|
||||
(self.folder / f"{session}.running").write_text(content)
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s7", "/code/a", ()), RunningLoop("s2", "/code/c", ()), RunningLoop("s9", "/code/m", ()), RunningLoop("s1", "/code/web", ()), RunningLoop("s8", "/code/z", ())])
|
||||
|
||||
def test_a_second_loop_on_the_session_warns_and_leaves_the_first_listed_with_its_question(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as first:
|
||||
waiting.publish(first.folder, ask)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as second:
|
||||
second.show((Taken(1, "Do it."),))
|
||||
with waiting.listed(second.folder, asked("s1", "/code/log", question="Mine?"), self.effects):
|
||||
self.assertEqual(waiting.waiting(self.folder), [ask])
|
||||
self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(self.folder, 's1')}", said.getvalue())
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
|
||||
self.assertEqual(waiting.waiting(self.folder), [ask])
|
||||
self.assertEqual(list((self.folder / "unlisted").iterdir()), [])
|
||||
|
||||
def test_takes_the_lock_once_loop_inbox_lets_go_of_it(self):
|
||||
# loop-inbox holds the lock for a moment as it checks whether the loop runs.
|
||||
looking = contextlib.ExitStack()
|
||||
looking.enter_context(session_lock.held(self.folder, "s1"))
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", dataclasses.replace(self.effects, sleep=lambda seconds: looking.close())):
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
|
||||
|
||||
|
||||
class Shown(unittest.TestCase):
|
||||
def drawn(self, screen, window):
|
||||
"""The lines draw puts on window for screen, 3700 s after the epoch."""
|
||||
main.draw(window, screen, dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: 3700))
|
||||
return [window.lines[row] for row in range(len(window.lines))]
|
||||
|
||||
def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self):
|
||||
log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0)
|
||||
cut = asked("s2", "/code/c", "Cut 0.4.0?\nIts changelog is ready.", at=3600 * 25, state=OpenInInbox(INBOX))
|
||||
lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 50)
|
||||
self.assertEqual(lines, ([
|
||||
"2 loops wait for you, oldest first.",
|
||||
"",
|
||||
"[1] /code/log, waiting since <0> (1 d 2 h)",
|
||||
" Which store should the cache use: Redis or",
|
||||
" SQLite? Redis is already deployed for…",
|
||||
"",
|
||||
"[2] /code/c, waiting since <90000> (1 h 2 min);",
|
||||
"claude is open in loop-inbox",
|
||||
" Cut 0.4.0?",
|
||||
" Its changelog is ready.",
|
||||
"",
|
||||
"No loop runs.",
|
||||
], [
|
||||
"Type a number and Enter to answer that loop; q",
|
||||
"quits loop-inbox, and the loops keep waiting.",
|
||||
"> 1",
|
||||
]))
|
||||
|
||||
def test_the_running_loops_follow_the_waiting_ones_each_with_the_items_its_chunk_takes(self):
|
||||
log = asked("s1", "/code/log", "Which one?", at=0)
|
||||
running = (
|
||||
RunningLoop("s2", "/code/c", (Taken(12, "Accept undefined in MetadataValue and drop such keys on output."), Taken(14, ""))),
|
||||
RunningLoop("s1", "/code/log", (Taken(255, "Have loop-inbox list every running loop-claude on the machine."),)),
|
||||
RunningLoop("s3", "/code/web", ()),
|
||||
)
|
||||
lines, _ = inbox.listing_lines(Listing((log,), running=running), 120, lambda seconds: f"<{seconds}>", 50)
|
||||
self.assertEqual(lines, [
|
||||
"1 loop waits for you.",
|
||||
"",
|
||||
"[1] /code/log, waiting since <0> (2 min)",
|
||||
" Which one?",
|
||||
"",
|
||||
"Running: 3 loops",
|
||||
"- /code/c",
|
||||
" item 12: Accept undefined in MetadataValue…",
|
||||
" item 14",
|
||||
"- /code/log, waiting as [1]",
|
||||
" item 255: Have loop-inbox list every running…",
|
||||
"- /code/web",
|
||||
" no todo.md item yet",
|
||||
])
|
||||
|
||||
def test_the_running_section_counts_one_loop(self):
|
||||
lines, _ = inbox.listing_lines(Listing(running=(RunningLoop("s1", "/code/log", ()),)), 0, str, 79)
|
||||
self.assertEqual(lines, ["No loop waits for you.", "", "Running: 1 loop", "- /code/log", " no todo.md item yet"])
|
||||
|
||||
def test_an_empty_list_says_no_loop_waits_or_runs(self):
|
||||
self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 79), (["No loop waits for you.", "", "No loop runs."], ["Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "]))
|
||||
|
||||
def test_the_answer_screen_at_80_columns_shows_every_character_of_each_line_and_says_what_enter_alone_does(self):
|
||||
# The question's first line has 80 characters, one more than a line drawn at 80 columns holds.
|
||||
ask = asked("s1", "/code/log", "The changelog lists four fixes and three new tools, so the next release is 0.6.0\n\nCut it?", at=100)
|
||||
self.assertEqual(self.drawn(Answering(ask, "Yes"), Window(width=80)), [
|
||||
"/code/log, waiting since <100> (1 h 0 min):",
|
||||
"",
|
||||
"The changelog lists four fixes and three new tools, so the next release is",
|
||||
"0.6.0",
|
||||
"",
|
||||
"Cut it?",
|
||||
"",
|
||||
"Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps",
|
||||
"waiting): Yes",
|
||||
])
|
||||
|
||||
def test_an_answer_longer_than_its_line_goes_on_below_it_with_every_space_typed(self):
|
||||
typed = "Use B, as the cache then runs next to the sessions it serves and then cut 0.6.0."
|
||||
lines = self.drawn(Answering(asked("s1", "/code/log", "A or B?", at=100), typed), Window(width=80))
|
||||
self.assertEqual(lines[-2:], ["waiting): Use B, as the cache then runs next to the sessions it serves and then", " cut 0.6.0."])
|
||||
|
||||
def test_a_line_that_runs_into_the_screens_last_cell_leaves_the_screen_drawn(self):
|
||||
class Refusing(Window):
|
||||
"""Refuses the screen's last row, as curses refuses a line of wide characters, such as emoji, that runs into the last cell."""
|
||||
|
||||
def addnstr(self, row, column, text, count):
|
||||
super().addnstr(row, column, text, count)
|
||||
if row == self.height - 1:
|
||||
raise main.curses.error("addnwstr() returned ERR")
|
||||
self.assertEqual(self.drawn(Listing(), Refusing(height=3)), ["…", "q quits loop-inbox, and the loops keep waiting.", "> "])
|
||||
|
||||
def test_a_screen_too_short_keeps_the_foot_and_marks_the_cut(self):
|
||||
for lines, foot, height, shown in (
|
||||
(["a", "b", "c"], ["> "], 4, ["a", "b", "c", "> "]),
|
||||
(["a", "b", "c"], ["> "], 3, ["a", "…", "> "]),
|
||||
(["a", "b", "c"], ["n", "> "], 4, ["a", "…", "n", "> "]),
|
||||
(["a", "b", "c", "d"], ["n", "h", "> "], 2, ["h", "> "]),
|
||||
):
|
||||
with self.subTest(lines=lines, foot=foot, height=height):
|
||||
self.assertEqual(inbox.fitted(lines, foot, height), shown)
|
||||
|
||||
def test_a_wait_reads_in_minutes_under_an_hour_and_in_hours_under_a_day(self):
|
||||
for seconds, read in ((3599, "59 min"), (3600, "1 h 0 min"), (86399, "23 h 59 min"), (86400, "1 d 0 h")):
|
||||
with self.subTest(seconds=seconds):
|
||||
self.assertEqual(inbox.waited(seconds), read)
|
||||
|
||||
|
||||
class Terminal(io.StringIO):
|
||||
def isatty(self):
|
||||
return True
|
||||
|
||||
|
||||
class Starts(unittest.TestCase):
|
||||
def started(self, argv, stdin, stdout):
|
||||
"""What main returns for argv, run with stdin and stdout, and what it writes to stderr."""
|
||||
stderr = io.StringIO()
|
||||
with unittest.mock.patch.object(sys, "stdin", stdin), contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
||||
code = main.main(argv, pathlib.Path("/no home"))
|
||||
return code, stderr.getvalue()
|
||||
|
||||
def test_help_prints_the_docstring(self):
|
||||
for flag in ("-h", "--help"):
|
||||
with self.subTest(flag):
|
||||
stdout = io.StringIO()
|
||||
self.assertEqual(self.started([flag], io.StringIO(), stdout), (0, ""))
|
||||
self.assertEqual(stdout.getvalue(), f"{main.__doc__.strip()}\n")
|
||||
|
||||
def test_exits_2_on_an_unknown_argument_or_off_a_terminal(self):
|
||||
off_a_terminal = "loop-inbox: stdin or stdout is not a terminal; run it on one\n"
|
||||
for case, argv, stdin, stdout, said in (
|
||||
("an unknown argument", ["--x"], Terminal(), Terminal(), "loop-inbox: unknown argument --x; usage: loop-inbox\n"),
|
||||
("stdout off a terminal", [], Terminal(), io.StringIO(), off_a_terminal),
|
||||
("stdin off a terminal", [], io.StringIO(), Terminal(), off_a_terminal),
|
||||
):
|
||||
with self.subTest(case):
|
||||
self.assertEqual(self.started(argv, stdin, stdout), (2, said))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -49,11 +49,6 @@ class Rung:
|
||||
|
||||
# Least competent first.
|
||||
LADDER = (
|
||||
Rung("claude-haiku-5-5", "low"),
|
||||
Rung("claude-haiku-5-5", "medium"),
|
||||
Rung("claude-haiku-5-5", "high"),
|
||||
Rung("claude-haiku-5-5", "xhigh"),
|
||||
Rung("claude-haiku-5-5", "max"),
|
||||
Rung("claude-sonnet-5-5", "high"),
|
||||
Rung("claude-opus-5-5", "medium"),
|
||||
Rung("claude-opus-5-5", "high"),
|
||||
|
||||
@@ -14,10 +14,11 @@ OPUS = Rung("claude-opus-5-5", "medium")
|
||||
|
||||
|
||||
class Ladder(unittest.TestCase):
|
||||
def test_runs_from_haiku_at_low_effort_to_fable_at_max_with_opus_at_medium_between(self):
|
||||
self.assertEqual(LADDER[0], Rung("claude-haiku-5-5", "low"))
|
||||
def test_runs_from_sonnet_at_high_effort_to_fable_at_max_with_opus_at_medium_between(self):
|
||||
self.assertEqual(LADDER[0], Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER[1], OPUS)
|
||||
self.assertEqual(LADDER[-1], Rung("claude-fable-5-1", "max"))
|
||||
self.assertEqual(len(LADDER), 11)
|
||||
self.assertEqual(len(LADDER), 6)
|
||||
self.assertEqual(len(set(LADDER)), len(LADDER))
|
||||
|
||||
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
|
||||
@@ -53,7 +54,7 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(planning_rung(OPUS, 4), Rung("claude-opus-5-5", "high"))
|
||||
|
||||
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model haiku", "model sonnet", "model opus", "model fable"})
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model sonnet", "model opus", "model fable"})
|
||||
|
||||
def test_ranks_a_rung_off_the_ladder_below_every_rung_on_it(self):
|
||||
self.assertEqual(highest(OPUS, LADDER[-1], LADDER[0]), LADDER[-1])
|
||||
@@ -96,9 +97,9 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
|
||||
|
||||
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
|
||||
haiku, fable = LADDER[4], LADDER[-1]
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 4)["stability"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 5)["stability"], Rung("claude-opus-5-5", "high"))
|
||||
sonnet, fable = LADDER[0], LADDER[-1]
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 4)["stability"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 5)["stability"], Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rungs(OPUS, fable, 5)["stability"], fable)
|
||||
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["stability"], Rung("claude-opus-5-5", "max"))
|
||||
|
||||
@@ -106,14 +107,13 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
|
||||
|
||||
def test_runs_a_replayed_pass_on_its_replays_rung_below_the_workers_where_the_e_plus_i_steps_no_review_up_and_the_worker_runs_no_higher_than_the_project(self):
|
||||
sonnet, haiku, opus_high = Rung("claude-sonnet-5-5", "high"), LADDER[0], Rung("claude-opus-5-5", "high")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku, ("stability", "claude-sonnet-5-5"): haiku}):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[4], 4), {**dict.fromkeys(REVIEWERS, OPUS), "prose": haiku, "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, OPUS, 4)["prose"], haiku)
|
||||
sonnet, opus_high = Rung("claude-sonnet-5-5", "high"), Rung("claude-opus-5-5", "high")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): sonnet}):
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 4), {**dict.fromkeys(REVIEWERS, OPUS), "prose": sonnet, "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, OPUS, 4)["prose"], sonnet)
|
||||
self.assertEqual(review_rungs(OPUS, opus_high, 4)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 5)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 5)["prose"], LADDER[-1])
|
||||
self.assertEqual((review_rungs(sonnet, sonnet, 4)["prose"], review_rungs(sonnet, sonnet, 4)["stability"]), (sonnet, haiku))
|
||||
|
||||
def test_holds_each_replayed_rung_below_its_models_project_rung_on_the_ladder(self):
|
||||
for (kind, model), rung in ladder.REPLAYED.items():
|
||||
|
||||
@@ -7,15 +7,15 @@ from model_routing.ladder import Rung
|
||||
|
||||
class Environment(unittest.TestCase):
|
||||
PROJECT = Rung("claude-opus-5-5", "medium")
|
||||
WORKER = Rung("claude-haiku-5-5", "max")
|
||||
WORKER = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "0")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "6")
|
||||
|
||||
def test_a_project_off_the_ladder_is_handed_an_empty_rung_so_none_is_inherited(self):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
|
||||
def test_handed_reads_back_what_environment_named(self):
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, 5))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import collections
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from claude_code.entries import assistant_parts, parse_entry, tool_call, usage_count
|
||||
from git_command import commits
|
||||
@@ -32,7 +33,7 @@ def measure(threads: list[bytes], checkout: Checkout, home: str) -> Reading | No
|
||||
before = [[entry for entry in thread if entry.get("type") == "assistant" and str(entry.get("timestamp", "")) < commit] for thread in (worker, *subagents)]
|
||||
reads = [reads_of(part, str(entry.get("cwd") or "/"), home) for thread in before for entry in thread for part in assistant_parts(entry)]
|
||||
roots = [checkout.main_root, *(added for found in reads for added in found.added)]
|
||||
files = collections.Counter(file for found in reads for path in found.read if (file := relative(path, roots)) in checkout.tracked)
|
||||
files = collections.Counter(file for found in reads for path in found.read if (file := relative(in_main_checkout(path, checkout.main_root), roots)) in checkout.tracked)
|
||||
return Reading(sum(map(tokens_in, before)), files)
|
||||
|
||||
|
||||
@@ -68,6 +69,11 @@ def reads_of(part: object, cwd: str, home: str) -> Reads:
|
||||
return shell_reads(str(arguments.get("command", "")), cwd, home) if name == "Bash" else Reads([], [])
|
||||
|
||||
|
||||
# chunk-preflight adds each item's worktree beside the checkout as <checkout>-item-<ID>, which no transcript command names.
|
||||
def in_main_checkout(path: str, main_root: str) -> str:
|
||||
return re.sub("^" + re.escape(main_root.rstrip("/")) + r"-item-\d+(?=/)", main_root.rstrip("/"), path, count=1)
|
||||
|
||||
|
||||
# Relative to the deepest root holding it, so the checkout and each worktree name a file alike.
|
||||
def relative(path: str, roots: list[str]) -> str | None:
|
||||
holding = [root for root in roots if path.startswith(root.rstrip("/") + "/")]
|
||||
|
||||
@@ -64,6 +64,11 @@ class Measure(unittest.TestCase):
|
||||
checkout = Checkout("/c/w", "/c/p", frozenset({"README.md", "late.py", "src/a.py", "src/b.py", "x.py"}))
|
||||
self.assertEqual(measure.measure([jsonl(worker), jsonl(subagent)], checkout, "/h"), Reading(33, collections.Counter({"src/a.py": 2, "README.md": 1, "src/b.py": 1})))
|
||||
|
||||
def test_counts_a_file_read_in_the_worktree_chunk_preflight_made_as_the_checkout_s(self):
|
||||
worker = [said("1", "m1", tokens=10, name="Read", input={"file_path": "/c/p-item-7/README.md"}), said("2", "m2", command="git commit -m x")]
|
||||
checkout = Checkout("/c/p-item-7", "/c/p", frozenset({"README.md"}))
|
||||
self.assertEqual(measure.measure([jsonl(worker)], checkout, "/h").files, collections.Counter({"README.md": 1}))
|
||||
|
||||
def test_measures_nothing_for_a_worker_that_never_committed(self):
|
||||
self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="git log --grep commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
|
||||
self.assertIsNone(measure.measure([jsonl([said("1", "m1", command="echo git commit")])], Checkout("/c/p", "/c/p", frozenset()), "/h"))
|
||||
|
||||
@@ -23,7 +23,7 @@ def unsorted_imports(source: str) -> list[int]:
|
||||
|
||||
class ImportOrder(unittest.TestCase):
|
||||
def test_each_python_file_sorts_its_imports_by_their_first_binding(self):
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude", "bin/loop-inbox"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split()
|
||||
self.assertIn("bin/loop-claude", listed)
|
||||
for name in listed:
|
||||
with self.subTest(name):
|
||||
|
||||
@@ -215,16 +215,16 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung == MIDDLE else [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP])
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE])
|
||||
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
|
||||
# The default branch stands where it stood when the chunk began, so the prompt's diff against it shows the branch's change.
|
||||
self.assertEqual((reviewed, branch, base), ("1\n", "x\n", "0\n"))
|
||||
@@ -232,7 +232,7 @@ class Main(unittest.TestCase):
|
||||
self.assertFalse(pathlib.Path(cwd).exists())
|
||||
self.assertIn("The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.", out)
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟡 slow", out)
|
||||
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"))
|
||||
self.assertTrue(out.endswith("finds: none below the project's rung\n"), out)
|
||||
|
||||
def test_replays_the_prose_pass_with_the_prose_reviewer(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
@@ -243,8 +243,8 @@ class Main(unittest.TestCase):
|
||||
def test_tries_each_rung_down_to_the_ladders_lowest_below_the_lowest_a_worker_routes_to(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP, *(Rung("claude-haiku-5-5", effort) for effort in ("xhigh", "high", "medium", "low"))])
|
||||
self.assertTrue(out.endswith("finds: claude-haiku-5-5 at low effort\n"), out)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE])
|
||||
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"), out)
|
||||
|
||||
def review_folder_with_round_1(self):
|
||||
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15."""
|
||||
@@ -404,9 +404,9 @@ class Main(unittest.TestCase):
|
||||
for argv in ([], ["claude-opus-5-5"], ["full scan", "claude-opus-5-5"], ["stability", "off-ladder"], ["stability", "claude-opus-5-5", "x"]):
|
||||
with self.subTest(argv=argv):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["stability", "claude-haiku-5-5"], unused)
|
||||
code, _, err = self.run_main(["stability", "claude-sonnet-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived stability round of projects on claude-haiku-5-5", err)
|
||||
self.assertIn("no archived stability round of projects on claude-sonnet-5-5", err)
|
||||
|
||||
def test_prints_the_help(self):
|
||||
code, out, _ = self.run_main(["-h"], unused)
|
||||
|
||||
@@ -31,6 +31,11 @@ def round_counts(titles: list[str]) -> dict[str, int]:
|
||||
return {name: max(highest[name], commits[name]) for name in highest}
|
||||
|
||||
|
||||
def rounds_past_first(titles: list[str]) -> int:
|
||||
"""Each pass's rounds past its first among the commit titles, as round_counts counts them, summed."""
|
||||
return sum(max(0, count - 1) for count in round_counts(titles).values())
|
||||
|
||||
|
||||
def lacks_counts(title: str) -> bool:
|
||||
"""Whether title is a round title without all three counts after its colon, or with more misread findings than 🔴 and 🟡 findings."""
|
||||
return ROUND.match(title) is not None and ((counts := title_counts(title)) is None or counts.misread is None)
|
||||
|
||||
@@ -2,13 +2,18 @@
|
||||
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 git_repo import default_ref, Git
|
||||
from failure import Failure
|
||||
from claude_code.entries import parse_entry
|
||||
from file_writes import replace_file
|
||||
@@ -16,6 +21,8 @@ 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"
|
||||
@@ -72,35 +79,54 @@ def last_measured(root: pathlib.Path) -> int | Failure:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Measured:
|
||||
"""skipped names each chunk folder that could not be read whole, such as one another loop is writing."""
|
||||
"""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) -> Measured | Failure:
|
||||
def measure_archive(root: pathlib.Path, home: str, since: str, git: Git) -> Measured | 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 = sorted({root / key for key, _ in listed})
|
||||
projects = [measure_project(root, project, home, since, git) for project in sorted({root / key for key, _ in listed})]
|
||||
return Measured(
|
||||
[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:
|
||||
"""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,))
|
||||
chunks = [chunk for chunk in listed if chunk.finished > since]
|
||||
if not chunks:
|
||||
return Measured([], ())
|
||||
history = branch_history(checkout_of(key, pathlib.Path(home)), git)
|
||||
found = []
|
||||
skipped = []
|
||||
for project in projects:
|
||||
chunks = finished_chunks(project)
|
||||
if isinstance(chunks, Failure):
|
||||
skipped.append(str(project.relative_to(root)))
|
||||
for chunk in chunks:
|
||||
folder = project / chunk.folder
|
||||
try:
|
||||
kept = [path.read_text(encoding="utf-8") for path in chunk_outcomes(folder)]
|
||||
subagents = [subagent(path) for path in chunk.subagents]
|
||||
worker = entries(chunk.transcript)
|
||||
except (OSError, UnicodeDecodeError):
|
||||
skipped.append(str(folder.relative_to(root)))
|
||||
continue
|
||||
for chunk in (chunk for chunk in chunks if chunk.finished > since):
|
||||
folder = project / chunk.folder
|
||||
try:
|
||||
kept = [path.read_text(encoding="utf-8") for path in chunk_outcomes(folder)]
|
||||
subagents = [subagent(path) for path in chunk.subagents]
|
||||
worker = entries(chunk.transcript)
|
||||
except (OSError, UnicodeDecodeError):
|
||||
skipped.append(str(folder.relative_to(root)))
|
||||
continue
|
||||
found.append(measured(Chunk(str(project.relative_to(root)), kept, worker, subagents), home))
|
||||
return Measured(found, tuple(skipped))
|
||||
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 ())
|
||||
|
||||
|
||||
def branch_history(checkout: str, git: Git) -> list[BranchChunk] | Failure:
|
||||
"""The chunks on the checkout's default branch as last fetched, read guarded, since the checkout's config may name a program."""
|
||||
ref = default_ref(checkout, GIT_TIMEOUT, guarded=True, run=git)
|
||||
return ref if isinstance(ref, Failure) else branch_chunks(ref, functools.partial(git, cwd=checkout, timeout=GIT_TIMEOUT, guarded=True))
|
||||
|
||||
|
||||
def entries(path: pathlib.Path) -> list[dict]:
|
||||
|
||||
@@ -6,11 +6,12 @@ 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_from
|
||||
from model_routing.route import ESCALATION_MARKER, Route, route_from
|
||||
from routing_figures.prices import listed
|
||||
from model_routing.ladder import position, Rung
|
||||
from round_titles import round_counts
|
||||
from round_titles import rounds_past_first
|
||||
from shell_command import simple_commands
|
||||
from transcript_archive.outcomes import UNFINISHED_AT, workers
|
||||
|
||||
@@ -56,7 +57,7 @@ class Reports:
|
||||
|
||||
@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."""
|
||||
"""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
|
||||
@@ -66,11 +67,12 @@ class ChunkFigures:
|
||||
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."""
|
||||
"""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]]
|
||||
@@ -79,6 +81,8 @@ class Figures:
|
||||
skipped: tuple[str, ...] = ()
|
||||
unattributed: float = 0.0
|
||||
lacking: int = 0
|
||||
unmatched: int = 0
|
||||
unread: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -97,7 +101,8 @@ class Spent(typing.NamedTuple):
|
||||
message: Message
|
||||
|
||||
|
||||
def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
||||
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)
|
||||
@@ -116,16 +121,30 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
|
||||
return ChunkFigures(
|
||||
dollars=dollars,
|
||||
start=start.rung if start and start.item else None,
|
||||
rounds_past_first=rounds_past_first(chunk.worker, home),
|
||||
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=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)),
|
||||
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())
|
||||
@@ -207,15 +226,14 @@ def results(entries: list[dict]) -> dict[str, str]:
|
||||
return {result.tool_use_id: result.text for entry in entries for part in parts(entry) if (result := tool_result(part))}
|
||||
|
||||
|
||||
def rounds_past_first(worker: list[dict], home: str) -> int:
|
||||
# A commit retried after a failed hook repeats its title, so each title counts once.
|
||||
titles = dict.fromkeys(
|
||||
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
|
||||
)
|
||||
return sum(max(0, rounds - 1) for rounds in round_counts(list(titles)).values())
|
||||
))
|
||||
|
||||
|
||||
def due(cycle: int, last_measured: int) -> bool:
|
||||
@@ -223,7 +241,7 @@ def due(cycle: int, last_measured: int) -> bool:
|
||||
return cycle >= last_measured + CYCLES_PER_CHECK
|
||||
|
||||
|
||||
def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures:
|
||||
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:
|
||||
@@ -236,7 +254,18 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures
|
||||
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(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks))
|
||||
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]:
|
||||
@@ -266,6 +295,14 @@ def basis(figures: Figures) -> str:
|
||||
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 = [
|
||||
@@ -275,8 +312,9 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
|
||||
"".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",
|
||||
table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, 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}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated)))
|
||||
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",
|
||||
@@ -284,6 +322,7 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: str)
|
||||
"## 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"
|
||||
|
||||
@@ -292,6 +331,13 @@ def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], colle
|
||||
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())
|
||||
|
||||
@@ -3,17 +3,24 @@ import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from routing_figures import archive
|
||||
from branch_chunks.cut import BranchChunk
|
||||
from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals
|
||||
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 model_routing.route import Route
|
||||
@@ -48,6 +55,19 @@ def figures(start=LOW, rounds=0, unfinished=0, reports=None, escalated=None):
|
||||
return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}), 0.0)
|
||||
|
||||
|
||||
def shipping(*items, fixed_by=()):
|
||||
"""A chunk on a default branch that shipped the items with these IDs."""
|
||||
return BranchChunk("before", "tip", "abc1234", "merge", "2026-10-14T11:00:00Z", (), tuple(Item(id_, (0, 1, 0), "", f"**Item {id_}.**", {}, (), ()) for id_ in items), fixed_by)
|
||||
|
||||
|
||||
def no_checkout(*args, **options):
|
||||
return Failure("no checkout")
|
||||
|
||||
|
||||
# Three routed chunks whose later fixes are known: 0, 0 and 3, so their median and mean differ.
|
||||
MATCHED = [dataclasses.replace(figures(), fixed_later=fixed) for fixed in (0, 0, 3)]
|
||||
|
||||
|
||||
class Measured(unittest.TestCase):
|
||||
def test_prices_each_message_once_by_project_type_rung_and_the_tool_it_followed(self):
|
||||
worker = [
|
||||
@@ -91,6 +111,26 @@ class Measured(unittest.TestCase):
|
||||
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)
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
def test_counts_no_later_fix_where_no_later_chunk_fixed_the_chunk_that_shipped_the_item(self):
|
||||
self.assertEqual(self.fixed_later([shipping(7)]), 0)
|
||||
|
||||
def test_leaves_the_later_fixes_unknown_where_no_chunk_shipped_the_item(self):
|
||||
self.assertIsNone(self.fixed_later([shipping(8, fixed_by=("c",))]))
|
||||
self.assertIsNone(self.fixed_later([]))
|
||||
|
||||
def test_leaves_the_later_fixes_unknown_where_the_history_could_not_be_read(self):
|
||||
self.assertIsNone(self.fixed_later(None))
|
||||
|
||||
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"))
|
||||
@@ -220,17 +260,31 @@ class Calls(unittest.TestCase):
|
||||
self.assertNotIn("no transcript", text)
|
||||
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |", text)
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |", text)
|
||||
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | unknown | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("| Explore | 2 | 3 | 4 |", text)
|
||||
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | | trigger 2: 3, trigger 10: 1 |", escalated)
|
||||
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | unknown | | trigger 2: 3, trigger 10: 1 |", escalated)
|
||||
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\ntrigger 2: 3, trigger 3: 1, trigger 10: 1.\n", escalated)
|
||||
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\nNone.\n", text)
|
||||
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
|
||||
|
||||
def test_renders_the_mean_later_fixes_of_the_matched_chunks_and_how_many_they_are(self):
|
||||
text = render(totals([*MATCHED, figures()]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn(f"| {LOW} | 4 | 0.0 | 0.0 | 1.0 (3 known) | | |", text)
|
||||
self.assertIn("## Routed chunks by the rung they started on\n\nA routed chunk's later fixes are", text)
|
||||
self.assertNotIn("later fixes", text.split("## Calls for a routing change")[0])
|
||||
|
||||
def test_counts_the_routed_chunks_whose_later_fixes_are_unknown(self):
|
||||
self.assertIn("The later fixes of 2 of the routed chunks are unknown", render(totals([*MATCHED, figures(), figures(), figures(start=None)]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("are unknown", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
|
||||
def test_names_each_default_branch_unread(self):
|
||||
self.assertIn("## Default branches unread\n\n- log: no main branch\n", render(totals(MATCHED, unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("branches unread", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
|
||||
def test_measures_once_the_count_runs_20_past_the_last_measurement(self):
|
||||
self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True])
|
||||
self.assertTrue(due(20, 0))
|
||||
@@ -260,10 +314,74 @@ class Archive(unittest.TestCase):
|
||||
def test_measures_each_finished_chunk_keyed_by_its_project(self):
|
||||
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
found = archive.measure_archive(self.root, "/h", "")
|
||||
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"), archive.Measured([], ()))
|
||||
self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z", no_checkout), archive.Measured([], ()))
|
||||
|
||||
def test_counts_each_chunks_later_fixes_from_its_projects_checkout(self):
|
||||
home = self.root / "home"
|
||||
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)}
|
||||
self.ship_then_fix(home / "code" / "log", env)
|
||||
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
with unittest.mock.patch.dict(os.environ, env, clear=True):
|
||||
found = archive.measure_archive(self.root, str(home), "", git_repo.git)
|
||||
self.assertEqual([(chunk.dollars["project"].keys(), chunk.fixed_later) for chunk in found.chunks], [({"log": 0}.keys(), 1)])
|
||||
|
||||
def test_reads_each_projects_history_guarded_and_each_read_of_its_branch_time_limited(self):
|
||||
home = self.root / "home"
|
||||
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)}
|
||||
self.ship_then_fix(home / "code" / "log", env)
|
||||
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
made = []
|
||||
|
||||
def recording(*args, **options):
|
||||
made.append((args[0], options))
|
||||
return git_repo.git(*args, **options)
|
||||
with unittest.mock.patch.dict(os.environ, env, clear=True):
|
||||
archive.measure_archive(self.root, str(home), "", recording)
|
||||
self.assertTrue(all(options.get("guarded") is True for _, options in made))
|
||||
read = [options.get("timeout") for command, options in made if command in ("log", "ls-tree", "show", "diff", "blame")]
|
||||
self.assertEqual(set(read), {archive.GIT_TIMEOUT})
|
||||
self.assertIn("blame", [command for command, _ in made])
|
||||
|
||||
def test_names_a_project_whose_checkout_has_no_default_branch(self):
|
||||
home = self.root / "home"
|
||||
env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(home)}
|
||||
(home / "code" / "log").mkdir(parents=True)
|
||||
subprocess.run(["git", "init", "-q"], cwd=home / "code" / "log", check=True, env=env, capture_output=True)
|
||||
self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
with unittest.mock.patch.dict(os.environ, env, clear=True):
|
||||
found = archive.measure_archive(self.root, str(home), "", git_repo.git)
|
||||
self.assertEqual(found.unread, ("log: no origin remote, and no main or master branch to take as the default branch",))
|
||||
|
||||
def test_names_each_project_whose_history_it_cannot_read(self):
|
||||
self.chunk("gone", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
found = archive.measure_archive(self.root, "/h", "", no_checkout)
|
||||
self.assertEqual(([chunk.fixed_later for chunk in found.chunks], found.unread), ([None], ("gone: no checkout",)))
|
||||
|
||||
def ship_then_fix(self, checkout, env):
|
||||
"""Makes a checkout whose main branch merges the chunk that ships item 7 of LOW_ROUTE, then one that ships a defect item and rewrites a line item 7 shipped."""
|
||||
checkout.mkdir(parents=True)
|
||||
git = lambda *args: subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=checkout, check=True, env=env, capture_output=True)
|
||||
plan = lambda rows: "# todo\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n" + rows
|
||||
|
||||
def merge(branch, title, files):
|
||||
git("switch", "-q", "-c", branch)
|
||||
for name, text in files.items():
|
||||
(checkout / name).write_text(text)
|
||||
git("add", *files)
|
||||
git("commit", "-q", "-m", title)
|
||||
git("switch", "-q", "main")
|
||||
git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
|
||||
fix = "| 6 | 0.1.0 | | defect | **Fix six.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |\n"
|
||||
git("init", "-q", "-b", "main")
|
||||
(checkout / "todo.md").write_text(plan("| 7 | 0.1.0 | | | **Ship seven.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 3 | 1.0 |\n" + fix))
|
||||
(checkout / "a.py").write_text("1\n")
|
||||
git("add", "todo.md", "a.py")
|
||||
git("commit", "-q", "-m", "Start")
|
||||
merge("ship", "Ship seven", {"a.py": "1\nx\n", "todo.md": plan(fix)})
|
||||
merge("fix", "Fix six", {"a.py": "1\ny\n", "todo.md": plan("")})
|
||||
|
||||
def test_reads_each_cycles_route_from_its_own_outcomes_file(self):
|
||||
transcript = self.root / "t.jsonl"
|
||||
@@ -274,7 +392,7 @@ class Archive(unittest.TestCase):
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
|
||||
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "m", "j"), 4070908800))
|
||||
(found,) = archive.measure_archive(kept, "/h", "").chunks
|
||||
(found,) = archive.measure_archive(kept, "/h", "", no_checkout).chunks
|
||||
self.assertEqual((found.start, found.unfinished), (LOW, 1))
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0})
|
||||
|
||||
@@ -284,7 +402,7 @@ class Archive(unittest.TestCase):
|
||||
self.chunk("other", "c2", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
self.chunk("broken", "c3", "", [])
|
||||
(self.root / "broken" / "c3" / "copy.outcomes.md").write_bytes(b"\xff")
|
||||
found = archive.measure_archive(self.root, "/h", "")
|
||||
found = archive.measure_archive(self.root, "/h", "", no_checkout)
|
||||
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, ""))
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
"""Refuse an Agent call that launches a review below the rung it needs, worked out from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import Call, text
|
||||
from failure import Failure
|
||||
from rule_hook.git import git
|
||||
import git_repo
|
||||
from model_routing.worker_rungs import handed
|
||||
from model_routing.ladder import position, review_rungs, ReviewKind, Rung
|
||||
from review_passes import REVIEWERS
|
||||
@@ -14,6 +18,9 @@ SEAT = "You are one seat of a comprehension panel."
|
||||
# The opening of the security pass's prompt: skills/larv-review/SKILL.md → "Security".
|
||||
SECURITY_OPENER = "You are the security pass for this chunk."
|
||||
SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "the security pass's subagent"}
|
||||
# Markdown an agent follows, which counts as config: Claude Code's memory files, and the folders that hold Claude Code's skills, agents and rules and this repo's principles.
|
||||
INSTRUCTION_FILES = {"CLAUDE.md", "AGENTS.md"}
|
||||
INSTRUCTION_FOLDERS = {"agents", "principles", "rules", "skills"}
|
||||
|
||||
|
||||
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
|
||||
@@ -23,6 +30,9 @@ def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Bre
|
||||
if kind is None or project is None or worker is None:
|
||||
return []
|
||||
required = review_rungs(project, worker, escape_and_impact)[kind]
|
||||
# A branch that changes only Markdown no agent follows holds no code or config for a reviewer on a higher rung to catch a defect in: skills/larv-review/SKILL.md → "Markdown only".
|
||||
if kind in REVIEWERS and position(required) > position(project) and markdown_only(call.cwd):
|
||||
required = project
|
||||
named = named_rung(call.given, worker)
|
||||
if position(named) >= position(required):
|
||||
return []
|
||||
@@ -48,3 +58,21 @@ def named_rung(given: dict[str, typing.Any], worker: Rung) -> Rung:
|
||||
if not model:
|
||||
return Rung(worker.model, effort or worker.effort)
|
||||
return Rung.from_agent(model, effort)
|
||||
|
||||
|
||||
def markdown_only(directory: str) -> bool:
|
||||
"""Whether every file the branch in directory changes, against the default branch as last fetched, is Markdown that no agent follows, counting uncommitted and untracked files; False where it changes none or git cannot say."""
|
||||
default = git_repo.default_ref(directory, guarded=True)
|
||||
base = default if isinstance(default, Failure) else git(directory, "merge-base", default, "HEAD")
|
||||
changed = base if isinstance(base, Failure) else git(directory, "diff", "--name-only", base)
|
||||
untracked = git(directory, "ls-files", "--others", "--exclude-standard")
|
||||
if isinstance(changed, Failure) or isinstance(untracked, Failure):
|
||||
return False
|
||||
paths = [*changed.splitlines(), *untracked.splitlines()]
|
||||
return bool(paths) and all(prose(path) for path in paths)
|
||||
|
||||
|
||||
def prose(path: str) -> bool:
|
||||
"""Whether path names Markdown that no agent follows."""
|
||||
parts = pathlib.PurePosixPath(path).parts
|
||||
return path.endswith(".md") and parts[-1] not in INSTRUCTION_FILES and not INSTRUCTION_FOLDERS & set(parts[:-1])
|
||||
|
||||
@@ -219,11 +219,40 @@ class ReviewerRung(unittest.TestCase):
|
||||
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
|
||||
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
|
||||
|
||||
def test_a_branch_changing_only_markdown_reviews_on_the_projects_rung_whatever_the_e_plus_i(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", repo])
|
||||
git(repo, "init", "-q", "-b", "main")
|
||||
git(repo, "commit", "-q", "--allow-empty", "-m", "base")
|
||||
git(repo, "checkout", "-q", "-b", "chunk")
|
||||
pathlib.Path(repo, "docs").mkdir()
|
||||
pathlib.Path(repo, "README.md").write_text("Read me.\n")
|
||||
pathlib.Path(repo, "docs", "decisions.md").write_text("Decided.\n")
|
||||
git(repo, "add", ".")
|
||||
git(repo, "commit", "-q", "-m", "prose")
|
||||
high = self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "7"}
|
||||
on_project = {"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), [])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**on_project, "model": "sonnet", "effort": "high"}, repo), high)), ["reviewer-rung"])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), self.ABOVE)), [], "a worker that climbed doesn't lift a Markdown-only review either")
|
||||
for instructions in ("CLAUDE.md", "AGENTS.md", "skills/review/SKILL.md", "agents/reviewer.md", "rules/todo.md", "principles/tests.md"):
|
||||
with self.subTest(instructions=instructions):
|
||||
path = pathlib.Path(repo, instructions)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("Do this.\n")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"], "Markdown an agent follows is config")
|
||||
path.unlink()
|
||||
pathlib.Path(repo, "gate.yml").write_text("on: push\n")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"], "an uncommitted change to another file counts")
|
||||
git(repo, "add", ".")
|
||||
git(repo, "commit", "-q", "-m", "config")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"])
|
||||
|
||||
def test_a_reviewer_below_the_project_rung_is_refused_naming_the_arguments_to_pass(self):
|
||||
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "haiku", "effort": "max", "prompt": "Review."}, "/r"), self.ENVIRON)
|
||||
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review."}, "/r"), self.ENVIRON)
|
||||
self.assertEqual(rules(breaches), ["reviewer-rung"])
|
||||
self.assertIn("stability-reviewer", breaches[0].detail)
|
||||
self.assertIn("claude-haiku-5-5 at max effort", breaches[0].detail)
|
||||
self.assertIn("claude-sonnet-5-5 at high effort", breaches[0].detail)
|
||||
self.assertIn("model opus, effort medium", breaches[0].detail)
|
||||
|
||||
def test_a_reviewer_on_the_project_rung_or_a_rerun_above_it_passes(self):
|
||||
@@ -260,10 +289,10 @@ class ReviewerRung(unittest.TestCase):
|
||||
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "sonnet", "effort": "high"}, without), ["reviewer-rung"])
|
||||
|
||||
def test_a_replayed_passs_reviewer_is_held_to_its_replays_rung_below_the_workers_unless_the_e_plus_i_steps_reviews_up_or_the_worker_climbed(self):
|
||||
lowered = {"subagent_type": "prose-reviewer", "model": "haiku", "effort": "medium"}
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): Rung("claude-haiku-5-5", "medium")}):
|
||||
lowered = {"subagent_type": "prose-reviewer", "model": "sonnet", "effort": "high"}
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): Rung("claude-sonnet-5-5", "high")}):
|
||||
self.assertEqual(self.refused(lowered), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "haiku", "effort": "low"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "sonnet", "effort": "medium"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({**lowered, "subagent_type": "stability-reviewer"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused(lowered, self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused(lowered, self.ABOVE), ["reviewer-rung"])
|
||||
|
||||
@@ -64,7 +64,7 @@ class FirstReply(unittest.TestCase):
|
||||
|
||||
class DownFrom(unittest.TestCase):
|
||||
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
|
||||
self.assertEqual(down_from(REFERENCE, CHEAP), [REFERENCE, MIDDLE, CHEAP])
|
||||
self.assertEqual(down_from(Rung("claude-opus-5-5", "high"), MIDDLE), [Rung("claude-opus-5-5", "high"), REFERENCE, MIDDLE])
|
||||
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
||||
|
||||
|
||||
|
||||
+37
-64
@@ -23,14 +23,23 @@ holds R and S, and C too where its table also had A, G and Goals. The chunk meas
|
||||
round title lacks the counts, or the branch has no round;
|
||||
- misread findings: how many of those 🔴 and 🟡 findings a reviewer marked `[misread]`, the
|
||||
`(<j> misread)` after the 🟡 count, summed over the titles. Unknown where a round title lacks
|
||||
that count, as every title written before the count does, or the branch has no round.
|
||||
that count, as every title written before the count does, or the branch has no round;
|
||||
- later fixes: the later chunks that fixed code it shipped, each counted once. A later chunk fixed
|
||||
it where a change of the later chunk removes or rewrites lines, outside todo.md and the records,
|
||||
that `git blame` traces to a commit this chunk brought to the default branch. The change is the
|
||||
later chunk's whole change where it ships a todo.md item whose Exempt cell is `defect` or
|
||||
`security`, or one of its round commits that may answer a misread 🔴. A title counts misread 🔴
|
||||
and 🟡 findings together, so this takes each round commit whose title counts both a 🔴 and a
|
||||
misread finding. A fixing chunk that also ships other items counts all of its change, so the
|
||||
count can run high; a fix that ships no such item, and answers no such round, goes uncounted. A
|
||||
recent chunk has had less time to gather any.
|
||||
|
||||
A chunk is marked `by rebase` where a commit in it has a committer time apart from its author time,
|
||||
since a rebase replays a pull request's commits at once, and `never replayed` where none does, since
|
||||
a pushed or fast-forwarded commit may be part of a pull request. A merge's titles are its branch's
|
||||
commits'; any other chunk's are its own. Two pull requests merged in the same second read as one
|
||||
chunk. Rebase drops a round's commit that changed no file, so a rebase or push chunk gives its
|
||||
rounds and findings as lower bounds, `at least`, and the report ends saying all this.
|
||||
a pushed or fast-forwarded commit may be part of a pull request. A merge's titles are its own and
|
||||
its branch's commits'; any other chunk's are its own. Two pull requests merged in the same second
|
||||
read as one chunk. Rebase drops a round's commit that changed no file, so a rebase or push chunk
|
||||
gives its rounds and findings as lower bounds, `at least`, and the report ends saying all this.
|
||||
|
||||
Given L, E and I, on the levels ~/.claude/rules/todo-items.md defines, and S, it works out R from
|
||||
L, E and I, as rank_todo.py does, and lists the 5 finished items whose guesses sit closest, closest
|
||||
@@ -55,21 +64,26 @@ Then, newest first, each finished chunk's 🔴 and 🟡 findings with its misrea
|
||||
chunk whose round titles count them: code health's counter-signal in
|
||||
~/.claude/CLAUDE.md → "Shared goal".
|
||||
|
||||
Then, newest first, each finished chunk's later fixes, naming the fixing chunks, for every chunk
|
||||
that has any, then how many have none: the defects that reappear in what already shipped, the
|
||||
other half of that counter-signal.
|
||||
|
||||
Exit 1, saying why, on bad arguments, when git cannot start, finds no checkout or reads a shallow
|
||||
clone, or the default branch cannot be read; or, after the rest of the report, when the anchors are
|
||||
left out.
|
||||
"""
|
||||
import functools
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
from score_outcomes.anchors import anchor_lines, Anchors, ANCHORS_PATH, parse_anchors
|
||||
from score_outcomes.results import Chunk, Landing, misreads, nearest, render, report, Result, results_of, shipped
|
||||
from git_repo import default_branch, file_at, full_history, git, top
|
||||
from branch_chunks.read import branch_chunks
|
||||
from git_repo import default_branch, full_history, git, top
|
||||
from failure import Failure
|
||||
from score_outcomes.results import fixed_later, misreads, nearest, render, report, Result, results_of
|
||||
from todo_table import LEVELS, risk, TOP_SCORE
|
||||
from markdown_text import listed
|
||||
from utc_stamp import utc
|
||||
|
||||
# The scores score-outcomes takes, in order.
|
||||
GIVEN = ("L", "E", "I", "S")
|
||||
@@ -107,7 +121,7 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
|
||||
def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[str, int] | None) -> str:
|
||||
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings."""
|
||||
"""The report: the finished items nearest the given scores, where any are given, then the anchors, then the medians, then each chunk's misread findings, then its later fixes."""
|
||||
sections = []
|
||||
if given is not None:
|
||||
r = risk(given["L"], given["E"], given["I"])
|
||||
@@ -116,6 +130,7 @@ def report_text(results: list[Result], anchored: Anchors | Failure, given: dict[
|
||||
sections.append([f"Anchors in {ANCHORS_PATH}, each level's shipped items:", "", *anchor_lines(anchored, results)])
|
||||
sections.append(["Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:", "", *report(results)])
|
||||
sections.append(["🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:", "", *misreads(results)])
|
||||
sections.append(["Later fixes: the chunks that fixed code each finished chunk shipped, newest first:", "", *fixed_later(results)])
|
||||
if any(result.landed != "merge" for result in results):
|
||||
sections.append(UNMERGED)
|
||||
return "\n\n".join("\n".join(section) for section in sections)
|
||||
@@ -143,61 +158,19 @@ def read_results(default: str) -> list[Result] | Failure:
|
||||
"""What each chunk on the default branch's first-parent line measured."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
log = git("log", "--first-parent", "--format=%x1e%h %ct %at %p", "--name-only", default)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
# Each commit's part of the log is its line, then the files it changed against its first parent.
|
||||
commits = [part.splitlines() for part in log.split("\x1e")[1:]]
|
||||
headers = [commit[0] for commit in commits]
|
||||
hashes = [header.split()[0] for header in headers]
|
||||
plan = {short for short, commit in zip(hashes, commits) if "todo.md" in commit}
|
||||
root = top()
|
||||
if isinstance(root, Failure):
|
||||
return root
|
||||
run = functools.partial(git, cwd=root)
|
||||
chunks = branch_chunks(default, run)
|
||||
if isinstance(chunks, Failure):
|
||||
return chunks
|
||||
results: list[Result] = []
|
||||
for first, last, committed, landed in chunk_log(headers):
|
||||
# Only a chunk that changed todo.md can ship an item, so the others skip measure's git calls.
|
||||
if not any(short in plan for short in hashes[hashes.index(last):hashes.index(first) + 1]):
|
||||
for chunk in chunks:
|
||||
if chunk.before is None or not chunk.shipped:
|
||||
continue
|
||||
label = first if first == last else f"{first}^..{last}"
|
||||
titled = f"{first}^1..{first}^2" if landed == "merge" else f"{first}^1..{last}"
|
||||
measured = measure(f"{first}^1", last, label, utc(committed), titled, landed)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
results += measured
|
||||
numstat = run("diff", "--numstat", chunk.before, chunk.tip)
|
||||
if isinstance(numstat, Failure):
|
||||
return numstat
|
||||
results += results_of(chunk, numstat)
|
||||
return results
|
||||
|
||||
|
||||
def chunk_log(lines: list[str]) -> list[Chunk]:
|
||||
"""The chunks `git log --first-parent --format=%h %ct %at %p` lines cut, newest first: each chunk's first and last commit as short hashes, its commit time, and how it reached the branch. A merge commit is a chunk of its own; any other commit joins the run of the newer commit above it when both share a commit time."""
|
||||
chunks: list[Chunk] = []
|
||||
joinable = False
|
||||
for line in lines:
|
||||
short, committed, authored, *parents = line.split()
|
||||
if len(parents) > 1:
|
||||
chunks.append((short, short, int(committed), "merge"))
|
||||
joinable = False
|
||||
elif joinable and chunks[-1][2] == int(committed):
|
||||
_, newest, time, landed = chunks[-1]
|
||||
chunks[-1] = (short, newest, time, "rebase" if landed == "rebase" or committed != authored else "push")
|
||||
else:
|
||||
chunks.append((short, short, int(committed), "rebase" if committed != authored else "push"))
|
||||
joinable = True
|
||||
return chunks
|
||||
|
||||
|
||||
def measure(before: str, tip: str, label: str, merged: str, titled: str, landed: Landing) -> list[Result] | Failure:
|
||||
"""What one chunk measured for each item it shipped: its change from the commit before it to its tip, and the titles of the commits in the range titled."""
|
||||
planned = file_at(before, "todo.md")
|
||||
if isinstance(planned, Failure):
|
||||
return planned
|
||||
after = file_at(tip, "todo.md")
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
items = shipped(planned, after)
|
||||
if not items:
|
||||
return []
|
||||
numstat = git("diff", "--numstat", before, tip)
|
||||
if isinstance(numstat, Failure):
|
||||
return numstat
|
||||
titles = git("log", "--format=%s", titled)
|
||||
if isinstance(titles, Failure):
|
||||
return titles
|
||||
return results_of(items, label, merged, numstat, titles.splitlines(), landed)
|
||||
|
||||
@@ -2,27 +2,19 @@ import dataclasses
|
||||
import statistics
|
||||
import typing
|
||||
|
||||
from round_titles import Findings, round_counts, round_findings
|
||||
from comprehension_history import HISTORY
|
||||
from todo_table import Item, items
|
||||
from branch_chunks.cut import BranchChunk, Landing, NOT_WORK
|
||||
from round_titles import Findings, round_findings, rounds_past_first
|
||||
from todo_table import Item
|
||||
from markdown_text import listed
|
||||
from reading_cost.figures import RECORD
|
||||
|
||||
# Fewest single-item chunks a score needs before its medians print: the 10 figures the reading-cost trend waits for; no published standard sets either.
|
||||
ENOUGH = 10
|
||||
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
||||
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
||||
|
||||
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
|
||||
Landing = typing.Literal["merge", "rebase", "push"]
|
||||
# A chunk's first and last commit as short hashes, its commit time, and how it reached the default branch.
|
||||
Chunk = tuple[str, str, int, Landing]
|
||||
|
||||
|
||||
# The tool's name and report call a Result an outcome, a word the code keeps for an entry of a `.outcomes.md` file: docs/decisions.md → `bin/: an outcome is an entry`.
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Result:
|
||||
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed."""
|
||||
"""What the chunk that shipped an item measured. findings holds the 🔴 and 🟡 counts, and how many of them a reviewer marked `[misread]`, None where a round title lacks the 🔴 and 🟡 counts or the branch has no round; its misread is None where a round title lacks that count. landed says how the chunk reached the default branch: by a merge commit, by a rebase that replayed its commits, or by commits never replayed. fixed_by names the later chunks that fixed code it shipped, newest first, as branch_chunks counts them."""
|
||||
item: Item
|
||||
merge: str
|
||||
merged: str
|
||||
@@ -32,6 +24,7 @@ class Result:
|
||||
rounds_past_first: int
|
||||
findings: Findings | None
|
||||
landed: Landing
|
||||
fixed_by: tuple[str, ...]
|
||||
|
||||
|
||||
# A measure's name and how to read it from a Result, None where the chunk did not record it.
|
||||
@@ -44,26 +37,17 @@ ORDERED = ("L", "E", "I")
|
||||
SHOWN = ("L", "E", "I", "R", "S", "C")
|
||||
|
||||
|
||||
def shipped(before: str, after: str) -> list[Item]:
|
||||
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
||||
planned, left = items(before), items(after)
|
||||
if not isinstance(planned, list) or not isinstance(left, list):
|
||||
return []
|
||||
kept = {item.id for item in left}
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def results_of(shipped: list[Item], merge: str, merged: str, numstat: str, titles: list[str], landed: Landing) -> list[Result]:
|
||||
"""What one chunk measured for each item it shipped, from `git diff --numstat` against the commit before it and its commit titles; none where it changed nothing but the plan and the records."""
|
||||
def results_of(chunk: BranchChunk, numstat: str) -> list[Result]:
|
||||
"""What one chunk measured for each item it shipped, from `git diff --numstat` of its change; none where it changed nothing but the plan and the records."""
|
||||
changed = [row.split("\t", 2) for row in numstat.splitlines()]
|
||||
work = [row for row in changed if len(row) == 3 and row[2] not in NOT_WORK]
|
||||
if not work:
|
||||
return []
|
||||
# Git counts a binary file's lines as "-".
|
||||
lines = sum(int(count) for row in work for count in row[:2] if count.isdigit())
|
||||
past_first = sum(max(0, count - 1) for count in round_counts(titles).values())
|
||||
ids = [item.id for item in shipped]
|
||||
return [Result(item, merge, merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), past_first, round_findings(titles), landed) for item in shipped]
|
||||
titles = list(chunk.titles)
|
||||
ids = [item.id for item in chunk.shipped]
|
||||
return [Result(item, chunk.label, chunk.merged, tuple(id_ for id_ in ids if id_ != item.id), lines, len(work), rounds_past_first(titles), round_findings(titles), chunk.landed, chunk.fixed_by) for item in chunk.shipped]
|
||||
|
||||
|
||||
def nearest(results: list[Result], given: dict[str, int], count: int = 5) -> list[Result]:
|
||||
@@ -102,13 +86,26 @@ def report(results: list[Result]) -> list[str]:
|
||||
|
||||
def misreads(results: list[Result]) -> list[str]:
|
||||
"""Newest first, each chunk's 🔴 and 🟡 findings with how many of them a reviewer marked `[misread]`, for each chunk whose round titles count those."""
|
||||
# A chunk that shipped several items has a Result for each, so one line per chunk.
|
||||
chunks = {result.merge: result for result in results}
|
||||
newest_first = sorted(chunks.values(), key=lambda result: result.merged, reverse=True)
|
||||
lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in newest_first if result.findings is not None and result.findings.misread is not None]
|
||||
lines = [f"- {result.merged} in {result.merge}: {counted(result)}" for result in one_per_chunk(results) if result.findings is not None and result.findings.misread is not None]
|
||||
return lines or ["- None: no chunk's round titles count them."]
|
||||
|
||||
|
||||
def fixed_later(results: list[Result]) -> list[str]:
|
||||
"""Newest first, each finished chunk whose code later chunks fixed, naming them, then how many finished chunks none fixed."""
|
||||
chunks = one_per_chunk(results)
|
||||
lines = [f"- {result.merged} in {result.merge}: {later(result)}, by {listed(result.fixed_by, 'and')}" for result in chunks if result.fixed_by]
|
||||
if not lines:
|
||||
return ["- None: no later chunk fixed code a finished chunk shipped."]
|
||||
others = len(chunks) - len(lines)
|
||||
return lines + ([f"- The other {plural(others, 'finished chunk')}: none."] if others else [])
|
||||
|
||||
|
||||
def one_per_chunk(results: list[Result]) -> list[Result]:
|
||||
"""One result for each chunk, newest first: a chunk that shipped several items has a Result for each, and the report gives each chunk one line."""
|
||||
chunks = {result.merge: result for result in results}
|
||||
return sorted(chunks.values(), key=lambda result: result.merged, reverse=True)
|
||||
|
||||
|
||||
def too_few(held: int, name: str, what: str) -> str:
|
||||
chunks = "such chunk records" if held == 1 else "such chunks record"
|
||||
return f"{held} {chunks} {name} and {what}; the report needs {ENOUGH}."
|
||||
@@ -132,7 +129,7 @@ def render(result: Result) -> str:
|
||||
merged = {"merge": f"merged {result.merged} in {result.merge}", "rebase": f"merged {result.merged} by rebase in {result.merge}", "push": f"committed {result.merged} in {result.merge}, never replayed, so perhaps part of a pull request"}[result.landed]
|
||||
others = result.shipped_with
|
||||
together = f", with item{'s' if len(others) > 1 else ''} {', '.join(map(str, others))}" if others else ""
|
||||
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}; {merged}{together}. {result.item.tagline}"
|
||||
return f"- Item {result.item.id}, {scores}: {plural(result.lines, 'line')} in {plural(result.files, 'file')}, {at_least(result)}{plural(result.rounds_past_first, 'round')} past each pass's first, {counted(result)}, {later(result)}; {merged}{together}. {result.item.tagline}"
|
||||
|
||||
|
||||
def at_least(result: Result) -> str:
|
||||
@@ -148,5 +145,10 @@ def counted(result: Result) -> str:
|
||||
return f"{at_least(result)}{result.findings.red} 🔴, {result.findings.yellow} 🟡{misread}"
|
||||
|
||||
|
||||
def later(result: Result) -> str:
|
||||
count = len(result.fixed_by)
|
||||
return f"{count} later fix{'' if count == 1 else 'es'}"
|
||||
|
||||
|
||||
def plural(count: int, noun: str) -> str:
|
||||
return f"{count} {noun}{'' if count == 1 else 's'}"
|
||||
|
||||
@@ -8,81 +8,43 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from score_outcomes.anchors import anchor_lines, parse_anchors
|
||||
from score_outcomes.main import chunk_log, report_text
|
||||
from branch_chunks.cut import BranchChunk, Landing
|
||||
from failure import Failure
|
||||
from round_titles import Findings
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item
|
||||
from score_outcomes.results import Landing, nearest, rank_correlation, render, report, Result, results_of, shipped
|
||||
from score_outcomes.results import nearest, rank_correlation, render, report, Result, results_of
|
||||
from score_outcomes.main import report_text
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "score-outcomes"
|
||||
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
FIRST = "| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 10 | 6 | 7 | 1 | 9.0 |"
|
||||
SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |"
|
||||
FIX = "| 6 | 0.1.0 | defect | **Fix it.** | 1 | 1 | 1 | 6 | 7 | 1 | 9.0 |"
|
||||
|
||||
|
||||
def todo(*rows: str, header: str = HEADER) -> str:
|
||||
return "# todo\n\n## Items\n\n" + header + "".join(f"{row}\n" for row in rows)
|
||||
def todo(*rows: str) -> str:
|
||||
return "# todo\n\n## Items\n\n" + HEADER + "".join(f"{row}\n" for row in rows)
|
||||
|
||||
|
||||
def item(id_: int, scores: dict[str, int]) -> Item:
|
||||
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, (("1", None),), ())
|
||||
|
||||
|
||||
def result(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = (), levels: dict[str, int] | None = None, landed: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa") -> Result:
|
||||
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landed)
|
||||
|
||||
|
||||
class Shipped(unittest.TestCase):
|
||||
def test_ships_each_item_the_change_removed_with_the_scores_it_had_before(self):
|
||||
self.assertEqual([found.id for found in shipped(todo(FIRST, SECOND), todo(SECOND))], [4])
|
||||
self.assertEqual(shipped(todo(FIRST, SECOND), todo(SECOND))[0].scores, {"R": 2, "S": 3, "C": 10, "A": 6, "G": 7})
|
||||
|
||||
def test_lists_the_shipped_items_by_id(self):
|
||||
self.assertEqual([found.id for found in shipped(todo(SECOND, FIRST), todo())], [4, 5])
|
||||
|
||||
def test_reads_a_table_from_before_c_joined_it(self):
|
||||
older = "| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |"
|
||||
self.assertEqual(shipped(todo(older, header=WITHOUT_C), todo(header=WITHOUT_C))[0].scores, {"R": 2, "S": 3, "A": 6, "G": 7})
|
||||
|
||||
def test_ships_nothing_where_either_plan_has_no_table_it_can_read(self):
|
||||
self.assertEqual(shipped(todo(FIRST), "# todo\n\n- [ ] Do it.\n"), [])
|
||||
self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), [])
|
||||
|
||||
|
||||
class ChunkLog(unittest.TestCase):
|
||||
# Lines are `%h %ct %at %p`, newest first: short hash, commit time, author time, parents.
|
||||
|
||||
def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self):
|
||||
self.assertEqual(chunk_log(["m 100 100 a b", "c 100 100 a"]), [("m", "m", 100, "merge"), ("c", "c", 100, "push")])
|
||||
|
||||
def test_commits_sharing_a_commit_time_form_one_run_labelled_rebase_when_any_differs(self):
|
||||
self.assertEqual(chunk_log(["c2 200 150 c1", "c1 200 100 r"]), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_run_of_commits_that_all_kept_their_author_time_is_labelled_push(self):
|
||||
self.assertEqual(chunk_log(["c2 200 200 c1", "c1 200 200 r"]), [("c1", "c2", 200, "push")])
|
||||
|
||||
def test_a_run_is_rebase_when_only_its_older_commit_was_replayed(self):
|
||||
self.assertEqual(chunk_log(["c2 200 200 c1", "c1 200 100 r"]), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_run_is_rebase_when_only_its_newer_commit_was_replayed(self):
|
||||
self.assertEqual(chunk_log(["c2 200 100 c1", "c1 200 200 r"]), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_commit_at_another_time_starts_a_new_chunk(self):
|
||||
self.assertEqual(chunk_log(["c2 300 300 c1", "c1 200 200 r"]), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
|
||||
def result(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = (), levels: dict[str, int] | None = None, landed: Landing = "merge", misread: int | None = None, merge: str = "aaaaaaa", fixed_by: tuple[str, ...] = ()) -> Result:
|
||||
return Result(item(id_, {"R": r, "S": s} | ({"C": c} if c else {}) | (levels or {})), merge, merged, shipped_with, lines, 1, rounds, None if findings is None else Findings(*findings, misread), landed, fixed_by)
|
||||
|
||||
|
||||
class ResultsOf(unittest.TestCase):
|
||||
def test_measures_the_change_less_the_plan_and_the_tool_records_and_counts_binary_files(self):
|
||||
numstat = "3\t1\ta.py\n-\t-\tlogo.png\n0\t1\t2026\n5\t0\ttodo.md\n9\t0\tdocs/reading-cost.md\n4\t0\tdocs/comprehension-history.md\n"
|
||||
titles = ["Answer stability round 1: 1 🔴, 2 🟡; fix", "Answer stability round 2: 0 🔴, 1 🟡; fix", "Answer prose round 1: 0 🔴, 3 🟡", "Do it"]
|
||||
found = results_of([item(4, {"R": 2}), item(5, {"R": 3})], "abc1234", "2026-10-13T10:00:00Z", numstat, titles, "merge")
|
||||
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge"))
|
||||
found = results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", tuple(titles), (item(4, {"R": 2}), item(5, {"R": 3})), ("def5678",)), numstat)
|
||||
self.assertEqual(found[0], Result(item(4, {"R": 2}), "abc1234", "2026-10-13T10:00:00Z", (5,), 5, 3, 1, Findings(1, 6, None), "merge", ("def5678",)))
|
||||
self.assertEqual(found[1].shipped_with, (4,))
|
||||
|
||||
def test_measures_no_chunk_that_changed_only_the_plan(self):
|
||||
self.assertEqual(results_of([item(4, {"R": 2})], "abc1234", "2026-10-13T10:00:00Z", "0\t5\ttodo.md\n", [], "merge"), [])
|
||||
self.assertEqual(results_of(BranchChunk("before", "tip", "abc1234", "merge", "2026-10-13T10:00:00Z", (), (item(4, {"R": 2}),), ()), "0\t5\ttodo.md\n"), [])
|
||||
|
||||
|
||||
class Nearest(unittest.TestCase):
|
||||
@@ -140,20 +102,24 @@ class Render(unittest.TestCase):
|
||||
self.assertTrue(render(result(4, 3, 3, None, levels={"L": 2, "E": 2, "I": 1})).startswith("- Item 4, L 2, E 2, I 1, R 3, S 3:"))
|
||||
|
||||
def test_names_the_items_shipped_together_and_unknown_findings(self):
|
||||
self.assertEqual(render(result(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
|
||||
self.assertEqual(render(result(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(result(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
|
||||
self.assertEqual(render(result(4, 2, 3, None, lines=1, rounds=2, findings=None, shipped_with=(5, 6))), "- Item 4, R 2, S 3: 1 line in 1 file, 2 rounds past each pass's first, findings unknown, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa, with items 5, 6. **Item 4.**")
|
||||
self.assertEqual(render(result(4, 2, 3, 4, findings=(1, 2))), "- Item 4, R 2, S 3, C 4: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa, with item 5. ", render(result(4, 2, 3, 4, rounds=1, shipped_with=(5,))))
|
||||
|
||||
def test_counts_the_later_fixes_of_the_chunk_that_shipped_it(self):
|
||||
self.assertIn("0 🔴, 0 🟡, 1 later fix; merged", render(result(4, 2, 3, None, fixed_by=("bbbbbbb",))))
|
||||
self.assertIn("0 🔴, 0 🟡, 2 later fixes; merged", render(result(4, 2, 3, None, fixed_by=("bbbbbbb", "ccccccc"))))
|
||||
|
||||
def test_gives_the_misread_count_where_the_round_titles_do(self):
|
||||
self.assertIn("1 round past each pass's first, 1 🔴, 2 🟡 (1 misread); merged", render(result(4, 2, 3, None, findings=(1, 2), misread=1)))
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡 (0 misread); merged", render(result(4, 2, 3, None, misread=0)))
|
||||
self.assertIn("1 round past each pass's first, 1 🔴, 2 🟡 (1 misread), 0 later fixes; merged", render(result(4, 2, 3, None, findings=(1, 2), misread=1)))
|
||||
self.assertIn("1 round past each pass's first, 0 🔴, 0 🟡 (0 misread), 0 later fixes; merged", render(result(4, 2, 3, None, misread=0)))
|
||||
|
||||
def test_gives_a_rebase_merged_chunks_rounds_and_findings_as_lower_bounds(self):
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("at least 1 round past each pass's first, findings unknown; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(result(4, 2, 3, None, findings=None, landed="rebase")))
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="rebase")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa. **Item 4.**")
|
||||
self.assertIn("at least 1 round past each pass's first, findings unknown, 0 later fixes; merged 2026-10-13T10:00:00Z by rebase in aaaaaaa", render(result(4, 2, 3, None, findings=None, landed="rebase")))
|
||||
|
||||
def test_says_a_chunk_never_replayed_may_be_part_of_a_pull_request(self):
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
|
||||
self.assertEqual(render(result(4, 2, 3, None, findings=(1, 2), landed="push")), "- Item 4, R 2, S 3: 10 lines in 1 file, at least 1 round past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; committed 2026-10-13T10:00:00Z in aaaaaaa, never replayed, so perhaps part of a pull request. **Item 4.**")
|
||||
|
||||
|
||||
ANCHORS_TEXT = "# Score anchors\n\nWhy these.\n\n| Level | Items |\n|---|---|\n| L 1 | 4, 9 |\n| I 3 | 5 |\n"
|
||||
@@ -179,7 +145,7 @@ class Anchors(unittest.TestCase):
|
||||
|
||||
def test_lists_each_anchor_with_what_its_chunk_measured_and_says_which_it_cannot_find(self):
|
||||
lines = anchor_lines([("L 1", (4, 9))], [result(4, 2, 3, None, findings=(1, 2))])
|
||||
self.assertEqual(lines, ["L 1:", "- Item 4, R 2, S 3: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**", "- Item 9: no chunk shipped it."])
|
||||
self.assertEqual(lines, ["L 1:", "- Item 4, R 2, S 3: 10 lines in 1 file, 1 round past each pass's first, 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 4.**", "- Item 9: no chunk shipped it."])
|
||||
|
||||
def test_points_to_the_rules_where_the_project_names_no_anchors(self):
|
||||
self.assertIn("docs/score-anchors.md", anchor_lines([], [])[0])
|
||||
@@ -195,13 +161,13 @@ class ReportText(unittest.TestCase):
|
||||
too_few = "such chunks record"
|
||||
self.assertEqual(report_text(found, [("L 1", (2,))], {"L": 1, "E": 1, "I": 1, "S": 3}), f"""Finished items nearest L 1, E 1, I 1, so R 1, and S 3, closest first:
|
||||
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
- Item 1, R 5, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 1.**
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
- Item 1, R 5, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-13T10:00:00Z in aaaaaaa. **Item 1.**
|
||||
|
||||
Anchors in docs/score-anchors.md, each level's shipped items:
|
||||
|
||||
L 1:
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
- Item 2, R 1, S 3: 10 lines in 1 file, 1 round past each pass's first, 0 🔴, 0 🟡, 0 later fixes; merged 2026-10-12T10:00:00Z in aaaaaaa. **Item 2.**
|
||||
|
||||
Median outcome at each guessed score, among chunks that shipped one item, never-replayed ones left out:
|
||||
|
||||
@@ -213,7 +179,11 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
|
||||
|
||||
🔴 and 🟡 findings, with how many a reviewer marked `[misread]`, per finished chunk whose round titles count them, newest first:
|
||||
|
||||
- None: no chunk's round titles count them.""")
|
||||
- None: no chunk's round titles count them.
|
||||
|
||||
Later fixes: the chunks that fixed code each finished chunk shipped, newest first:
|
||||
|
||||
- None: no later chunk fixed code a finished chunk shipped.""")
|
||||
|
||||
def test_lists_each_chunks_findings_with_their_misread_count_newest_first_once_per_chunk(self):
|
||||
found = [result(1, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,)), result(2, 5, 3, None, findings=(1, 2), misread=1, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,)), result(3, 5, 3, None, findings=(0, 4), misread=0, merge="ccccccc", merged="2026-10-14T10:00:00Z", landed="rebase"), result(4, 5, 3, None)]
|
||||
@@ -222,6 +192,14 @@ Median outcome at each guessed score, among chunks that shipped one item, never-
|
||||
- 2026-10-14T10:00:00Z in ccccccc: at least 0 🔴, 4 🟡 (0 misread)
|
||||
- 2026-10-12T10:00:00Z in bbbbbbb: 1 🔴, 2 🟡 (1 misread)""", report_text(found, [], None))
|
||||
|
||||
def test_lists_each_chunks_later_fixes_newest_first_once_per_chunk_then_counts_the_others(self):
|
||||
found = [result(1, 5, 3, None, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(2,), fixed_by=("ddddddd",)), result(2, 5, 3, None, merge="bbbbbbb", merged="2026-10-12T10:00:00Z", shipped_with=(1,), fixed_by=("ddddddd",)), result(3, 5, 3, None, merge="ccccccc", merged="2026-10-14T10:00:00Z", fixed_by=("eeeeeee", "ddddddd")), result(4, 5, 3, None), result(5, 5, 3, None, merge="fffffff")]
|
||||
self.assertTrue(report_text(found, [], None).endswith("""Later fixes: the chunks that fixed code each finished chunk shipped, newest first:
|
||||
|
||||
- 2026-10-14T10:00:00Z in ccccccc: 2 later fixes, by eeeeeee and ddddddd
|
||||
- 2026-10-12T10:00:00Z in bbbbbbb: 1 later fix, by ddddddd
|
||||
- The other 2 finished chunks: none."""))
|
||||
|
||||
def test_ends_with_how_it_reads_chunks_merged_by_rebase_only_where_it_measured_one(self):
|
||||
text = report_text([result(1, 5, 3, None, landed="rebase")], [], None)
|
||||
self.assertIn("\n\nChunks that left no merge commit:\n\n- Each is the run of commits", text.split("Median outcome")[1])
|
||||
@@ -290,8 +268,8 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
self.env.pop(name, None)
|
||||
return self.git("rev-parse", "--short", "HEAD").strip()
|
||||
|
||||
def run_tool(self, *args):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
|
||||
def run_tool(self, *args, cwd=None):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True)
|
||||
|
||||
def test_measures_each_merged_chunk_that_removed_an_item(self):
|
||||
self.git("switch", "-q", "-c", "chunk")
|
||||
@@ -302,9 +280,24 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
ran = self.run_tool("1", "2", "1", "3")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("Finished items nearest L 1, E 2, I 1, so R 2, and S 3, closest first:", ran.stdout)
|
||||
self.assertIn("- Item 4, R 2, S 3, C 10: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡; merged ", ran.stdout)
|
||||
self.assertIn("- Item 4, R 2, S 3, C 10: 3 lines in 1 file, 0 rounds past each pass's first, 1 🔴, 2 🟡, 0 later fixes; merged ", ran.stdout)
|
||||
self.assertNotIn("Item 5", ran.stdout)
|
||||
|
||||
def test_counts_a_later_chunk_that_ships_a_defect_item_and_rewrites_a_line_a_chunk_shipped_run_from_a_folder_below_the_top(self):
|
||||
self.commit("File a fix", {"todo.md": todo(FIRST, SECOND, FIX)})
|
||||
self.git("switch", "-q", "-c", "chunk")
|
||||
self.commit("Do it", {"sub/a.py": "1\n2\n3\n", "todo.md": todo(SECOND, FIX)})
|
||||
self.git("switch", "-q", "main")
|
||||
shipped = self.merge_branch("chunk", "2026-10-13T10:00:00Z")
|
||||
self.git("switch", "-q", "-c", "fix")
|
||||
self.commit("Fix it", {"sub/a.py": "1\n2\n4\n", "todo.md": todo(SECOND)})
|
||||
self.git("switch", "-q", "main")
|
||||
fixed = self.merge_branch("fix", "2026-10-14T10:00:00Z")
|
||||
ran = self.run_tool("1", "2", "1", "3", cwd=self.checkout / "sub")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn(f"findings unknown, 1 later fix; merged 2026-10-13T10:00:00Z in {shipped}. **Do it.**", ran.stdout)
|
||||
self.assertIn(f"- 2026-10-13T10:00:00Z in {shipped}: 1 later fix, by {fixed}\n- The other 1 finished chunk: none.", ran.stdout)
|
||||
|
||||
def run_on_rebased_history(self):
|
||||
self.commit("Re-score item 4", {"todo.md": todo(FIRST.replace("| 2 | 3 |", "| 1 | 3 |"), SECOND)}, at="2026-10-13T08:00:00Z")
|
||||
first = self.commit("Score item 4 higher", {"todo.md": todo(FIRST, SECOND)}, at="2026-10-13T09:00:00Z")
|
||||
@@ -328,11 +321,11 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
|
||||
def test_labels_a_run_of_commits_that_kept_their_author_time_never_replayed(self):
|
||||
stdout, _, _, _, pushed = self.run_on_rebased_history()
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown; committed 2026-10-13T11:00:00Z in {pushed}, never replayed, so perhaps part of a pull request. **Then this.**", stdout)
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown, 0 later fixes; committed 2026-10-13T11:00:00Z in {pushed}, never replayed, so perhaps part of a pull request. **Then this.**", stdout)
|
||||
|
||||
def test_measures_a_rebase_run_at_one_commit_time_as_one_chunk_whose_rounds_read_at_least(self):
|
||||
_, item_4, first, last, _ = self.run_on_rebased_history()
|
||||
self.assertIn(f"at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", item_4)
|
||||
self.assertIn(f"at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", item_4)
|
||||
|
||||
def test_explains_the_chunks_that_left_no_merge_commit_after_a_rebase(self):
|
||||
stdout, _, _, _, _ = self.run_on_rebased_history()
|
||||
@@ -346,8 +339,8 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
self.git("merge", "-q", "--no-ff", "-m", "Merge chunk", "chunk")
|
||||
ran = self.run_tool("1", "2", "1", "3")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertRegex(ran.stdout, r"- Item 4, R 2, S 3, C 10: 1 line in 1 file, 0 rounds past each pass's first, findings unknown; merged \S+ in [0-9a-f]{7,}\. ")
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown; committed 2026-10-12T09:00:00Z in {drop}, never replayed, so perhaps part of a pull request. **Then this.**", ran.stdout)
|
||||
self.assertRegex(ran.stdout, r"- Item 4, R 2, S 3, C 10: 1 line in 1 file, 0 rounds past each pass's first, findings unknown, 0 later fixes; merged \S+ in [0-9a-f]{7,}\. ")
|
||||
self.assertIn(f"- Item 5, R 4, S 6, C 8: 1 line in 1 file, at least 0 rounds past each pass's first, findings unknown, 0 later fixes; committed 2026-10-12T09:00:00Z in {drop}, never replayed, so perhaps part of a pull request. **Then this.**", ran.stdout)
|
||||
self.assertNotIn("by rebase", ran.stdout)
|
||||
|
||||
def test_labels_a_merge_merge_even_when_its_author_and_commit_times_are_equal(self):
|
||||
@@ -384,7 +377,7 @@ class ScoreOutcomesTool(unittest.TestCase):
|
||||
self.merge_branch("other", "2026-10-13T10:00:00Z")
|
||||
ran = self.run_tool("1", "2", "1", "3")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn(f"- Item 4, R 2, S 3, C 10: 3 lines in 1 file, at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", ran.stdout)
|
||||
self.assertIn(f"- Item 4, R 2, S 3, C 10: 3 lines in 1 file, at least 0 rounds past each pass's first, at least 1 🔴, 2 🟡, 0 later fixes; merged 2026-10-13T09:00:00Z by rebase in {first}^..{last}. **Do it.**", ran.stdout)
|
||||
|
||||
def test_lists_the_projects_anchors_with_what_their_chunks_measured(self):
|
||||
self.git("switch", "-q", "-c", "chunk")
|
||||
|
||||
@@ -18,7 +18,8 @@ class SubagentRung(unittest.TestCase):
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 3), "model opus, effort medium")
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 2), "model sonnet, effort high")
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 4), "model opus, effort high")
|
||||
self.assertEqual(main.agent_args("claude-haiku-5-5", 1), "model haiku, effort low")
|
||||
self.assertEqual(main.agent_args("claude-sonnet-5-5", 1), "model sonnet, effort high")
|
||||
self.assertIsNone(main.agent_args("claude-haiku-5-5", 1))
|
||||
|
||||
def test_a_planning_task_never_runs_below_the_projects_rung(self):
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 1, planning=True), "model opus, effort medium")
|
||||
|
||||
@@ -26,6 +26,9 @@ class Git(unittest.TestCase):
|
||||
self.assertIn("latin", done.reason)
|
||||
self.assertIn("UTF-8", done.reason)
|
||||
|
||||
def test_reads_each_byte_that_is_not_utf_8_as_a_replacement_character_where_asked(self):
|
||||
self.assertEqual(git_repo.git("-c", "alias.latin=!printf 'caf\\351'", "latin", errors="replace"), "caf�")
|
||||
|
||||
def test_says_which_command_could_not_start_in_a_directory_that_is_gone(self):
|
||||
done = git_repo.git("log", cwd="/code/gone")
|
||||
self.assertIsInstance(done, Failure)
|
||||
@@ -99,5 +102,35 @@ class StalledOrigin(unittest.TestCase):
|
||||
self.assertIn("stopped after 0.5 s", found.reason)
|
||||
|
||||
|
||||
class TextAt(unittest.TestCase):
|
||||
def test_reads_the_file_the_revision_lists(self):
|
||||
answers = {"ls-tree": "todo.md\n", "show": "# todo\n"}
|
||||
self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: answers[args[0]]), "# todo\n")
|
||||
|
||||
def test_reads_empty_where_the_revision_lists_no_such_file(self):
|
||||
self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: "" if args[0] == "ls-tree" else Failure("no such file")), "")
|
||||
|
||||
def test_fails_where_git_cannot_list_the_revision(self):
|
||||
self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: Failure("bad revision")), Failure("bad revision"))
|
||||
|
||||
|
||||
class FileAt(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = temp.name
|
||||
self.run_git("init", "--quiet")
|
||||
pathlib.Path(self.root, "todo.md").write_text("# todo\n")
|
||||
self.run_git("add", "todo.md")
|
||||
self.run_git("-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgSign=false", "commit", "--quiet", "-m", "Start")
|
||||
|
||||
def run_git(self, *args):
|
||||
subprocess.run(["git", *args], capture_output=True, check=True, cwd=self.root)
|
||||
|
||||
def test_reads_the_file_in_the_checkout_cwd_names_while_running_in_another_directory(self):
|
||||
with tempfile.TemporaryDirectory() as elsewhere, contextlib.chdir(elsewhere):
|
||||
self.assertEqual(git_repo.file_at("HEAD", "todo.md", self.root), "# todo\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -4,7 +4,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from round_titles import Findings, lacks_counts, past_cap, round_counts, round_findings
|
||||
from round_titles import Findings, lacks_counts, past_cap, round_counts, round_findings, rounds_past_first
|
||||
|
||||
|
||||
class Rounds(unittest.TestCase):
|
||||
@@ -21,6 +21,10 @@ class Rounds(unittest.TestCase):
|
||||
def test_lists_the_principles_pass_before_its_first_round(self):
|
||||
self.assertIn("principles", round_counts([]))
|
||||
|
||||
def test_sums_each_passs_rounds_past_its_first(self):
|
||||
self.assertEqual(rounds_past_first(["Answer stability round 2: x", "Answer stability round 1: y", "Answer prose round 1: z", "Answer architecture round 3: w", "Do the work"]), 3)
|
||||
self.assertEqual(rounds_past_first([]), 0)
|
||||
|
||||
|
||||
class Cap(unittest.TestCase):
|
||||
def test_finds_a_round_title_past_round_2(self):
|
||||
|
||||
@@ -2898,3 +2898,434 @@ Inherited architect, decided by:
|
||||
- Locality: `bin/transcript_archive/write.py:14` `archive`: the same change, but its silent default `note` drops the `transcript: <path>` line for a new caller without a word
|
||||
- Shape: `bin/loop_claude/cycle/run.py:85` `archived_stop`: the same lambda is copied seven times across `run.py`, `loop/main.py` and `cycle/interrupt.py`, which roughly cancels the cleaner output path
|
||||
- Self-sufficiency: `bin/loop_claude/loop/main.py:289` `plan_item`: its comment sends the reader to the plan and reads oddly now that every message goes through `say`
|
||||
|
||||
## 2026-10-28T21:50:16Z, PR #392 at 6e12ee9, against 77bc635
|
||||
|
||||
Ruling: better
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | better | better | better | same | better |
|
||||
| Inherited architect | better | better | better | same | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Shape: `bin/branch_chunks/cut.py:59` `cut_branch`: the older `score_outcomes/main.py` cut the branch with index arithmetic over raw log lines, each chunk a `(short, short, int, Landing)` tuple read as `chunks[-1][2]`, with three helpers agreeing on hash slices; the newer typed `Commit`, `Span` and `Branch` dataclasses make one pure cut, the landing rule sits in its own `landing`, and both tools share it
|
||||
- Navigation: `README.md:128` the import-root paragraph: the older packed every package-to-package dependency into one long paragraph; the newer gives each package a bullet, sorted by name, so going from a package to what it serves and imports is one scan
|
||||
- Shape, Locality: `bin/branch_chunks/read.py:7` `branch_chunks`: every git call sits in this short shell while `cut.py` and `fixes.py` stay pure, and `fixes.py`'s docstring says what fixed later means before any code; the two tools only see `BranchChunk.fixed_by`
|
||||
- Shape: `bin/round_titles.py:34` `rounds_past_first`: the older computed rounds past the first in two places, one mixed into title extraction; the newer has one helper, and `measure.py:229` `commit_titles` does only what its name says
|
||||
- Locality, Shape: `bin/loop_claude/effects.py:31` `Effects.git`: uses `git_repo.Git` instead of a narrower local protocol, so one definition says what a git runner is; a small cost is that `git_repo.Git` and `git_repo.Run` are two neighbouring types for something that runs git
|
||||
- Self-sufficiency: `bin/routing_figures/measure.py:336` `fixes_per_chunk`: its comment says "A mean, where item 247 named the median", which only reads fully with `todo.md` open; the new docstrings in `fixes.py` and `score_outcomes/main.py:27` explain later fixes in place, and the two balance
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Shape, Locality: `bin/branch_chunks/cut.py:59` `cut_branch`: the older `chunk_log` returned a positional tuple read by index; the newer `Commit`, `Span` and `Branch` are frozen dataclasses with named fields, and `landing` and `label` are small functions each readable and changeable alone
|
||||
- Shape: `bin/score_outcomes/results.py:40` `results_of`: the older took six positional arguments its caller built from rev-range strings such as `f"{first}^1..{first}^2"`; the newer takes one `BranchChunk` and the numstat, and `read_results` is a short loop without rev-range arithmetic
|
||||
- Navigation, Locality: `bin/routing_figures/measure.py:229` `commit_titles`: the older wrote the rounds-past-first sum twice, once mixed with reading the transcript; the newer has one definition in `round_titles` used by both tools, and reading titles is its own unit
|
||||
- Navigation: `README.md:128` the module list: the older described the module dependencies in one run-on paragraph; the newer gives one bullet per module, including `branch_chunks/` naming who uses it
|
||||
- Shape: `bin/routing_figures/measure.py:257` `totals`: the older built `Figures` from eight positional arguments; the newer passes them by keyword, which matters now that it gained `unmatched` and `unread`
|
||||
- Locality: `bin/git_repo.py:48` `Git`: the protocol moved out of `loop_claude/effects.py` into `git_repo`, and `default_ref` and `branch_chunks` take the runner as an injected `run`, so the guarded and timed path reads at the call site
|
||||
- Locality: `bin/branch_chunks/fixes.py:50` `with_fixes`: `branch.owner[commit] > change.chunk` means a later chunk fixed an earlier one only because chunks are ordered newest first, which only `Branch`'s and `chunk_log`'s docstrings state; not enough to move the ruling
|
||||
- Self-sufficiency: `bin/routing_figures/measure.py:336` `fixes_per_chunk`: explains its choice by pointing to "item 247" in the plan, while `later_fixes_of` and `fixes.py`'s docstring state their rules in full, so it is mixed
|
||||
|
||||
## 2026-10-29T00:40:36Z, PR #394 at bbb33f5, against b743228
|
||||
|
||||
Ruling: worse
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | worse | same | worse |
|
||||
| Inherited architect | same | worse | worse | same | worse |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Overall: `bin/loop_claude/cycle/interrupt.py:36` `put_question`, with `bin/loop_claude/cycle/interrupt.py:90` `talk`: the ask is published in `put_question`, whose `finally` leaves it listed on a `Talk`, and `talk`'s own `finally` removes it one state later; changing either means following the ask's lifecycle across both and the `Talking` state, where at the base each did one local thing
|
||||
- Locality, Shape: `bin/loop_claude/cycle/interrupt.py:98` `opened`: its call to `shown` is also the go-ahead `claim_talk` (`bin/loop_claude/waiting.py:192`) polls for, so a function named for showing a question is one step of a handshake between two processes; only the comment above it and `waiting.py`'s docstring warn
|
||||
- Shape: `bin/loop_claude/loop/routing_check.py:7` `raise_calls`: the imports now reach into `cycle.interrupt` for `claude_args`, `shown` and `withdrawn` plus the `waiting` types, and it builds an `Ask` whose session is its own id
|
||||
- Shape: `bin/loop_claude/effects.py:12` the import of `Answer`: the low-level effects module, and `states.py`, now depend on the domain module `waiting.py` for their types
|
||||
- Shape, Self-sufficiency: `bin/loop_claude/cycle/states.py:12` `TypedAnswer`: its docstring still says typed at loop-claude's terminal, though an answer from loop-inbox becomes one too, and `Talking` lost its docstring; minor, outweighed by `waiting.py`'s docstring
|
||||
- Shape: `bin/loop_claude/cycle/interrupt.py:22` `WorkerSession`: bundles the base's seven loose `talk` arguments and six `hand_over` arguments, which reads better and keeps Shape only mildly worse
|
||||
- Navigation: `README.md:102` the loop-inbox entry: the new tool is signposted from the README, `loop-claude --help` and `loop-inbox --help`, so a symptom crosses more files but each is named where you would look
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:36` `put_question`, with `bin/loop_claude/cycle/interrupt.py:90` `talk`: on a `Talk` the ask's file stays up while the answer passes through `run.ask`, `TalkChosen`, `transition` and `Talking`, and `talk`'s `finally` takes it down; to be sure it is always removed, a reader holds the state machine across three files
|
||||
- Locality: `bin/loop_claude/waiting.py:192` `claim_talk`: loop-inbox waits 5 s for `OpenInInbox`, which the loop shows only after five units in three other files, so step 2 of the protocol is spread out and the timeout rests on that path staying quick
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:78` `shown`: confirming its docstring's failure path, loop-inbox gives up and the loop stops, takes four steps across two processes and two files
|
||||
- Shape: `bin/loop_inbox/main.py:39` the import of `hand_over`: `interrupt.py` under `cycle/` now also holds `hand_over`, `claude_args`, `shown` and `withdrawn`, which `routing_check` and loop-inbox import, so its name and folder no longer say who depends on it, while `waiting.py` holds only the raw `publish` and `withdraw`
|
||||
- Shape: `bin/loop_claude/cycle/states.py:12` `TypedAnswer`: its docstring still says typed at loop-claude's terminal; `Talking` lost its docstring, and `states.py` and `effects.py:12` now import from the inbox's file format
|
||||
- Locality: `bin/loop_claude/cycle/run.py:102` `step`, the `Talking` branch: `WorkerSession` gathers the base's seven loose arguments and `claude_command` builds the resume command in one place, a smaller gain outweighed by the above
|
||||
- Self-sufficiency: `bin/loop_claude/waiting.py:1` the module docstring: documents the file protocol in three numbered steps, so nothing new needs a document beside it; the cost is how far apart the pieces are
|
||||
|
||||
## 2026-10-29T00:46:50Z, PR #394 at bbb33f5
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Mid A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Maintainability senior | 6 | 5 | 6 | 5.5 | 5.5 |
|
||||
| Inherited architect | 7 | 6 | 5.5 | 7.5 | 6.5 |
|
||||
| Mean | 6.75 | 5.50 | 6.13 | 6.25 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: four interacting rules, with helpers in ladder.py, route.py and escalation_mark.py, so predicting one rung means holding the rung, the unfinished count, the mark, the cap and taking_in at once
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: English instructions assembled from routing state and review_choice.chosen, whose order matters and whose result only the docstring examples show
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder with REJECTED and RETIRED sentinels and an unstated `fits` convention, where a small mistake breaks the reload's hand-over of state
|
||||
- `bin/loop_claude/cycle/judge.py:150` `run_judge`: a misquote ends three different ways, with a verdict precedence only the comments in `Grounds` resolve
|
||||
- `bin/rank_todo.py:410` `blockers_first`: recursive blocker placement with loop detection, and every scoring function branches on the old and new table shapes
|
||||
- `bin/chunk_pick.py:11` `LastCut`: fields typed with `Failure` put errors inside the data, and the renamed-release rule lives only in named_releases
|
||||
- `skills/larv-review/SKILL.md:72` "Round cap": dense rules held together by cross-references, so one question took four files
|
||||
- `bin/rule_hook/rules.py:160` `unlimited_container`: a PATH heuristic about run-heavy decides whether a container is capped
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: one rule raises, steps once, caps, moves the escalation mark and takes in E + I, readable only with routing.py, escalation_mark.py, route.py and ladder.py open together
|
||||
- `bin/loop_claude/cycle/run.py:167` `ask`: which rung a step-up is charged to travels as a StepUp inside the states, action at a distance the comments at 145 and 170 resolve twice
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a recursive reflective decoder with sentinels and a duck-typed `fits`, whose consequence is spelled out only on LoopRun
|
||||
- `bin/rank_todo.py:428` `place`: recursive blocker placement, with the old and new table shapes running through read_scoring, weigh, score and cited_goals_failure
|
||||
- `bin/comprehension_history.py:207` `labelled_bullets`: a stateful line parser whose branches serve formats from before PR #232 and #255
|
||||
- `bin/loop_claude/cycle/judge.py:164` `quotes_checked`: a misquoted reply ends three ways, plus grounded's ellipsis matching, found only by tracing each caller
|
||||
- `bin/model_routing/route.py:84` `route_from`: reads three spellings of one value, and nothing says when the legacy form can go
|
||||
- `bin/review_replay/main.py:234` `redirected`: rewrites archived prompt paths where order matters, and guesses a round's commit from author times
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: five rung concepts, each defined elsewhere, plus the unfinished counter, a mark counted in transcript entries and taking_in, replayed by hand on examples
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: generic reflection machinery inside a domain package; nothing says when a field becomes RETIRED instead of REJECTED
|
||||
- `bin/rank_todo.py:410` `blockers_first`: two table shapes side by side, recursive placement, and weight rules stated together only in the module docstring
|
||||
- `bin/chunk_pick.py:166` `named_releases`: the next release derived from every todo.md since the tag minus renames, clearer in chunk-preflight's help than at its home
|
||||
- `bin/comprehension_history.py:130` `newest_scored`: prefix-matched commits, regex headings whose differences matter, and legacy carve-outs citing PR numbers instead of the old shapes
|
||||
- `bin/loop_claude/cycle/run.py:190` `archive_stepped`: the route update runs in a channel beside the states, so what changes the route has two answers, here and in loop/main.py's after_verdict
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: which sentences reach a worker's prompt depends on a dozen small functions, and no whole prompt is visible
|
||||
- `bin/rule_hook/rules.py:312` `unlimited_container`: slice arithmetic on words, and resets_path counts -i and -u whatever launcher they follow
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/round_titles.py:8` `CAP`: the round cap lives in a module named for commit titles, and nothing says a third reviewer launch is left unguarded on purpose
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the step-up policy is split from model_routing/ and spread over about six files, so why a worker is on rung X takes two packages
|
||||
- `bin/loop_claude/loop/main.py:169` `run_loop`: about twelve steps per cycle and an import fan-in of about 20 modules from 8 packages
|
||||
- `bin/loop_claude/waiting.py:76` `Typed`: one name over three concepts, with transcript.py's Typed and states.py's TypedAnswer
|
||||
- `bin/rung_replay/search.py:1` the imports: replay tools reach into loop_claude.cycle.retry and loop_claude.effects, so loop_claude is also the shared headless-claude library
|
||||
- `bin/loop_claude/cycle/judge.py:64` `Reply`: a new verdict field touches Reply, verdicts.py, states.py, routing.py, Route and the outcomes archive
|
||||
- `README.md:129` the module map: lists only cross-package imports, leaving the 18 root modules of bin/ without an index
|
||||
|
||||
## 2026-10-29T00:51:59Z, PR #394 rerun at bbb33f5
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Mid A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Maintainability senior | 6.5 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 7.5 | 6.5 |
|
||||
| Mean | 6.88 | 5.88 | 6.25 | 6.38 | 6.25 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: four rules meet in one expression, so one call means holding item_rung, ESCALATION_CAP, UNFINISHED_PER_STEP and the mark's entries_read while jumping to ladder.py and escalation_mark.py
|
||||
- `bin/comprehension_history.py:97` `entries`: the module parses its own markdown output, old formats are keyed only to PR numbers, and scored against scoring_runs differ in a way the code doesn't name
|
||||
- `bin/loop_claude/cycle/run.py:167` `ask`: which route each archived line names before and after a step-up, with the cycle replaced inside run_cycle; the comments at 61, 145 and 170 resolve it
|
||||
- `skills/larv-review/SKILL.md:31` "Passes": dense rules pointing out to CLAUDE.md, rules/, the standards and --help, with the re-entry table and the round cap held together
|
||||
- `bin/rule_hook/round_cap.py:24` `earlier_titles`: returns an empty list when git fails, so a git failure turns the round cap off without saying so
|
||||
- `bin/rank_todo.py:568` `score`: both table shapes run through the whole 659-line file, and only rules/todo-items.md says what C, A and G mean
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: recursive type decoding with sentinels and a duck-typed fits hook, so a hot reload depends on dataclasses in other files
|
||||
- `bin/routing_figures/measure.py:174` `costed`: recorded costs scaled across list prices and messages matched to a rung by timestamp, resolved by long docstrings
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:263` `after_unfinished`: one condition needs rung, item rung, kept rung, L taken in, the escalation mark and the cap held at once, with rules/todo-items.md and the ladder open
|
||||
- `bin/rank_todo.py:332` `weigh`: a 658-line file carries a legacy scoring model through almost every function, so each one asks which shape it is in
|
||||
- `bin/loop_claude/escalation_mark.py:183` `checked`: part of the contract is a sentence spliced into the judge's schema text, so changing English changes behaviour
|
||||
- `bin/loop_claude/cycle/judge.py:316` `verdict_from`: the verdict precedence is encoded twice, as the order of the ifs and in the QUOTE_RULES prose
|
||||
- `bin/loop_claude/loop/main.py:169` `run_loop`: builds Cycle in one line of about 330 characters under 25 unordered imports, and plan_item defers to a todo.md item number
|
||||
- `bin/routing_figures/measure.py:59` `ChunkFigures`: fields documented in one dense paragraph instead of beside each field, and render builds tables inline in one huge literal
|
||||
- `skills/larv-review/SKILL.md:72` "Round cap": what counts as a round, the auto-reviewer exception and relaunches staying in their round took rereads beside round_titles.py and round_cap.py
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: one verdict raises the rung, moves the mark, resets or bumps the count and takes in E + I, with invariants in route.py, ladder.py and escalation_mark.py held open at once
|
||||
- `bin/loop_claude/cycle/run.py:167` `ask`: the StepUp travels through the Working and Interrupting states while run_cycle swaps Cycle.route out of sight of these handlers
|
||||
- `bin/rank_todo.py:568` `score`: the old table shape forks about eight functions, and the module docstring describes only the new shape
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: the worker's prompt is built from conditional fragments, so the text the worker reads appears only in docstring examples
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder with first-fit union matching, sentinels and a duck-typed fits, which every LoopRun field quietly depends on
|
||||
- `bin/shell_command.py:44` `segments`: a hand-made state machine over shlex tokens tracks redirect targets, and a change's safety is unclear without the tests
|
||||
- `bin/chunk_pick.py:109` `next_release`: LastCut fields typed str, None or Failure, and recovering renamed releases from todo.md's history is explained only in passing
|
||||
- `bin/loop_claude/waiting.py:192` `claim_talk`: a handshake between processes with a timeout and a take-back, resolved by the module's three-step docstring
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `README.md:129` the module map: five domain modules sit at bin/'s root because two tools share them, so larv-review's rules spread over larv_review/, round_titles.py, review_passes.py, review_folder.py and comprehension_history.py
|
||||
- `bin/git_command.py:17` `commits`: parses git commit out of shell words and doesn't run git, beside git_repo.py's git and rule_hook/git.py's guarded git
|
||||
- `bin/rung_replay/search.py:1` the imports: replay tools reach into loop_claude.cycle.retry and loop_claude.effects, so loop_claude is also a shared library
|
||||
- `bin/rule_hook/main.py:79` `breaches_of`: rules.py is both the RULES registry and the checker of about half the rules, while the other half have their own modules
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the step-up policy is spread over about six files across loop_claude and model_routing, where the next routing rule lands
|
||||
- `bin/round_titles.py:8` `CAP`: enforced only on round commit titles, so a third reviewer launch is guarded by SKILL.md prose alone
|
||||
- `bin/loop_claude/project/records.py:1` `RECORD_FILES`: "records" means the judge's records here and a tool-kept document in AGENTS.md
|
||||
- `bin/loop_claude/loop/main.py:1` the module docstring: a 122-line contract restating README and SKILL.md, where drift will come from
|
||||
|
||||
## 2026-10-29T12:15:18Z, PR #394 at 9ebd06e, against b743228
|
||||
|
||||
Ruling: worse
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | better | same | worse |
|
||||
| Inherited architect | same | worse | same | same | worse |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:39` `interrupt`: where the base's `put_question` read one terminal line, it waits on the terminal and on an answer file another process writes, and hands a lambda wrapping `claude_open` to `human_typed`, so a change means holding the two-process protocol; its docstring is one long sentence over every branch
|
||||
- Locality, Shape: `bin/loop_claude/waiting.py:202` `claim_talk`, with `bin/loop_claude/waiting.py:221` `make_way`: /talk from loop-inbox is a three-step handshake across two processes, with a take-back on timeout; order dependence with no counterpart at the base, though the module docstring explains it
|
||||
- Shape: `bin/loop_claude/cycle/interrupt.py:74` `first_answer`: `OpenOnTerminal`, an ask's state in loop-inbox's file, doubles as the return value for /talk and, at line 48, for a release ready to cut, so the name tells the truth about the file but not the control flow
|
||||
- Shape: `bin/loop_claude/cycle/states.py:34` `Interrupting`: the state machine loses `Talking` and `TalkChosen`, so `transition` has one state and one event fewer
|
||||
- Shape: `bin/loop_claude/hand_over.py:24` `hand_over`: opening claude on a terminal leaves `cycle/interrupt.py` for its own module, ending routing_check's sideways reach into the cycle, and `ClaudeCommand` replaces six loose arguments
|
||||
- Shape: `bin/loop_inbox/inbox.py:59` `pressed`: the new tool splits into a pure core of screens and keys behind a curses shell, with names that say what they are
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality, Overall: `bin/loop_claude/waiting.py:202` `claim_talk`, with `bin/loop_claude/waiting.py:221` `make_way`, `bin/loop_claude/cycle/interrupt.py:77` `claude_open` and `bin/loop_inbox/main.py:146` `opened`: /talk, one call in one process at the base, is a three-step handshake between two processes through a JSON file, over three files in two packages, resting on `MAKE_WAY_SECONDS`, a take-back after a timeout and pid liveness; the module docstring lays the steps out well
|
||||
- Locality: `bin/loop_claude/effects.py:105` `alive`: whether an ask still counts, and whether the loop still waits on loop-inbox's claude, rests on a pid being alive, and nothing addresses pid reuse, a risk neither caller shows
|
||||
- Locality: `bin/loop_claude/cycle/interrupt.py:39` `interrupt`, with `bin/loop_claude/cycle/interrupt.py:94` `human_typed`: the base read straight down, `put_question` returning and the state machine stepping to `Talking`; now the wait sits inside `listed`, `first_answer` polls two sources, and the claude wait passes as a lambda; fewer states and `hand_over`'s move out of `cycle/` are real gains that don't offset it
|
||||
|
||||
## 2026-10-29T13:05:34Z, PR #394 at 9ebd06e
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 5.5 | 6.5 | 5.5 | 6 |
|
||||
| Maintainability senior | 7.5 | 6 | 6.5 | 7 | 6.5 |
|
||||
| Inherited architect | 7 | 6 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.13 | 5.75 | 6.25 | 6.38 | 6.25 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: five interacting rules in one function, each resting on terms defined in ladder.py, route.py, escalation_mark.py and the charter; the module docstring's outline says which branch, not why the order
|
||||
- `bin/loop_claude/cycle/run.py:165` `ask`: the route before and after a step-up travel together, and seeing which one each archive line names meant tracing step_up through states.py; the comments at 61, 143 and 168 resolve it
|
||||
- `bin/loop_claude/waiting.py:202` `claim_talk`, with `bin/loop_claude/waiting.py:221` `make_way` and `bin/loop_claude/cycle/interrupt.py:77` `claude_open`: a three-step handshake between two processes through files, polled against a deadline with liveness checks; the module docstring gives the order, but who writes which file needs both sides
|
||||
- `bin/loop_claude/cycle/interrupt.py:39` `interrupt`: a one-sentence docstring over about six outcomes, with the body spread over first_answer, claude_open and human_typed; accurate but too dense for one read
|
||||
- `bin/rank_todo.py:218` `rank`: about eight failure checks in sequence, and several functions branch on SHAPE versus OLD_SHAPE, a dual path explained only in todo_table.py
|
||||
- `bin/loop_claude/cycle/judge.py:164` `quotes_checked`: quietly turns a misquoted answer into an Interrupt, and verdict_from's branch order decides the meaning
|
||||
- `skills/larv-review/SKILL.md:72` "Round cap": a dense rulebook of passes, caps, re-entry and severities, part implemented in bin/larv_review and part followed by the agent; stayed too much to hold at once
|
||||
- `bin/model_routing/route.py:84` `route_from`: an archived line is JSON or an older regex format, and renaming a field breaks archived lines, guarded only by a comment
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: kept_rung, item_rung, raised, a one-rung step and a cap check held at once, plus two step triggers and a moving escalation mark; the docstring's index and escalation_mark.py's four steps resolve it partly, after three rereads
|
||||
- `bin/loop_claude/cycle/run.py:54` `run_cycle`: a step-up rides on state fields while run_cycle swaps Cycle.route on Ruled, HumanTalked drops it, and ran_on and archive_stepped decide which route a line names; the comments at 61, 143 and 168 explain it, read beside states.py
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder with REJECTED and RETIRED sentinels, duck-typed to Route through `fits`, which nothing at Route mentions
|
||||
- `bin/rank_todo.py:332` `weigh`: OLD_SHAPE/SHAPE branches spread over weigh, score, cited_goals_failure and goal_weights instead of converted once at read time; why both exist is in todo_table.py
|
||||
- `bin/loop_claude/cycle/interrupt.py:39` `interrupt`: a docstring of one sentence chain with four where/else turns, then a split across first_answer, claude_open, human_typed and the /talk handshake; waiting.py's module docstring resolves it
|
||||
- `bin/loop_claude/cycle/judge.py:106` `verdict_from`: an implicit priority order and silent coercions, a misquote becoming an Interrupt and an off-scale L becoming 0
|
||||
- `bin/rank_todo.py:428` `place`: recursive blocker placement with loop detection, fiddly by nature
|
||||
- `skills/larv-review/SKILL.md:31` "3. Passes": dense rules pointing to CLAUDE.md, review-findings.md, standards/ and larv-review --help, not fully followed
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: one unit raises the rung to an item's L, steps on every second unfinished verdict or on an escalation below the cap, moves the mark and records E + I, with rules from ladder.py, route.py and escalation_mark.py; the docstring states the rule but each branch needed tracing by hand
|
||||
- `bin/loop_claude/cycle/judge.py:96` `Grounds`: quotes from three sources, each misquote punished differently (Rejected, escalation dropped, answer turned to Interrupt), with the escalation half in escalation_mark.checked; each case commented, but the asymmetry is easy to break
|
||||
- `bin/chunk_pick.py:109` `next_release`: the outcomes come from combining is_earliest with landed, and LastCut's X | Failure fields push failure handling into the data; subtle by nature, clear on a second read
|
||||
- `bin/loop_claude/cycle/run.py:54` `run_cycle`: the route changes on Cycle at a Ruled step-up while step_up travels through the states, and ran_on versus cycle.route decides which rung each archive call charges; the comments at 61, 143 and 168 explain it, but the invariant spans two modules
|
||||
- `bin/rank_todo.py:428` `place`: recursive placement with loop detection, with OLD_SHAPE threading through older_columns, parse_weights, goal_term and cited_goals_failure; whether the old shape is still live stayed unclear
|
||||
- `bin/model_routing/route.py:84` `route_from`: layered backward compatibility (a JSON or legacy Worker line, reload's REJECTED and RETIRED sentinels and a `fits` found by name), so a change to Route's fields hits three decoders
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: timestamps compared as text, tool calls paired with results by id and truncation markers handled, closely tied to the transcript format; the comments resolve it
|
||||
- `skills/larv-review/SKILL.md:31` "3. Passes": dense cross-referenced rules, waves, reruns and the re-entry table not holdable in one read
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/rule_hook/round_cap.py:8` `round_cap_breaches`: the round cap is split over round_titles.py, rule_hook/round_cap.py, larv_review/main.py and SKILL.md, and guards only `Answer <pass> round` commit titles, so a third reviewer run slips through on a launch without a round commit, a misspelled pass name or a slow git; nothing in the code says the cap is advisory at launch time
|
||||
- `bin/loop_claude/cycle/judge.py:186` `grounded`: fuzzy quote matching against a transcript rendered in escalation_mark.py and normalised in claude_code/transcript.py, three modules that must stay in step; where it rots first
|
||||
- `bin/round_titles.py:8` `CAP`: the `bin/` root holds about 55 peers, with review mechanics, shell parsing, plan reading and plumbing side by side, the README grouping only part; the worst level
|
||||
- `bin/git_command.py:17` `commits`: the name says it runs git, but it pulls commit messages from parsed shell words, beside git_repo.py, which runs git, and rule_hook/git.py, a third wrapper; three opens to sort out
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: routing reaches over routing.py, model_routing, cycle/prompts.py and, through environment variables, rule_hook/reviewer_rung.py; hard because the policy is, and documented
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: 120 lines of contract that restate CLAUDE.md's Vocabulary, AGENTS titles and the README's Tools, so a vocabulary change must land in four places
|
||||
- `skills/larv-review/SKILL.md:31` "3. Passes": about twelve interacting concepts under one heading, the prose twin of the bin/ root
|
||||
- `bin/loop_claude/cycle/states.py:88` `transition`: "ruling" names both the judge's ruling and the comprehension paired ruling, "project" a rung, a package and project_key, "chunk" three tools
|
||||
|
||||
## 2026-10-29T13:05:37Z, PR #394 rerun at 9ebd06e
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 6 | 6 | 5.5 | 6 |
|
||||
| Maintainability senior | 7 | 6 | 7 | 6 | 6.5 |
|
||||
| Inherited architect | 7 | 6.5 | 5.5 | 6.5 | 6 |
|
||||
| Mean | 7.00 | 6.00 | 6.13 | 6.00 | 6.13 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the unfinished count, a step every two verdicts, a two-rung cap, the escalation mark and the item's rung interact, unpredictable on one read; the docstring and rules/todo-items.md gave the words, the arithmetic only made sense after tracing loop/main.py
|
||||
- `bin/loop_claude/escalation_mark.py:53` `checked`: the mark is an entry count that becomes a `[step]` line in the judge's prompt, which the grounding check in judge.py then relies on; one concept over three files, neither naming the other
|
||||
- `bin/rank_todo.py:428` `place`: recursive placement with loop detection, and the OLD_SHAPE/SHAPE branches through weigh, goal_term, score, parse_weights and cited_goals_failure; the spec docstring explains why, the recursion stayed hard
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a recursive type-directed decoder with REJECTED and RETIRED sentinels and a duck-typed `fits`, generic machinery whose reason lives at exec_if_edited
|
||||
- `bin/comprehension_history.py:150` `scoring_runs`: a near-twin of `scored` at 159 that a reader would mix up, with branches for formats from before PR #232 and #255 that need history the reader doesn't have
|
||||
- `bin/model_routing/review_choice.py:21` `chosen`: many near-synonym ladder helpers and an opaque "higher" loop; the docstrings explain edge cases, not the shape
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: timestamps compared as strings and truncation heuristics, correct only under assumptions not stated there
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: about 120 lines of contract before any code, accurate but costly, citing a plan item the reader may not open
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: the kept rung, the item's rung, the cap, the mark's step and whether E + I was taken in, held at once, with meanings spread over routing.py, ladder.py, route.py and escalation_mark.py; no single place states the rule as a whole
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: a generic recursive decoder signalling through REJECTED and RETIRED and duck-typing `fits`; why it exists is stated, which types reach `fits` took a grep
|
||||
- `bin/rank_todo.py:332` `weigh`: both table shapes branch inside weigh, score and cited_goals_failure, so a scoring change must be made right in several places; nothing collects the shape logic
|
||||
- `bin/routing_figures/measure.py:104` `measured`: many collaborators and a proportional cost scaling, a ChunkFigures docstring defining every field in one paragraph, and rung_at comparing timestamps as strings without saying why that holds
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: sentences that branch on route, project rung and taken-in state, a second copy of routing.py's rung rules in English; the worked examples help
|
||||
- `bin/model_routing/route.py:84` `route_from`: JSON and legacy regex lines both parse, RETIRED covers removed rungs, and nothing says when a form may be dropped
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: 120 lines of contract before the first import, which routed and closed_cycle only make sense against
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: rebuilds which lines a Read showed from transcript results with truncation heuristics and string-compared timestamps; the module docstring mostly resolves it
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/rank_todo.py:218` `rank`: the largest module, with every scoring step branching on OLD_SHAPE versus SHAPE and checks reaching into README.md and docs/decisions.md; the format docstring doesn't say why two shapes coexist
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: three rules in one function, followed only with route.py, escalation_mark.py, verdicts.py and ladder.py open; the docstrings and escalation_mark's overview resolve it eventually
|
||||
- `bin/loop_claude/loop/reload.py:45` `decoded_as`: calls `kind.fits` by naming convention, so Route.fits is action at a distance and a rename breaks the reload silently; the LoopRun comment warns about fields, not this hook
|
||||
- `bin/chunk_pick.py:109` `next_release`: the earliest release after the tag depends on renames across historical todo.md texts; chunk_preflight restates the rule, the rename tracking stays subtle
|
||||
- `bin/loop_claude/cycle/judge.py:150` `run_judge`: three kinds of ungrounded evidence end three ways, Rejected and retried, an Interrupt, or a silently dropped escalation; the Grounds comments resolve it
|
||||
- `bin/model_routing/review_choice.py:21` `chosen`: the `higher` loop records the lowest E + I per rung, and its `or` clause needs replay_applies and reviewers_rung from ladder.py; one terse comment
|
||||
- `bin/loop_claude/cycle/prompts.py:104` `escalation`: sentences assembled from ReviewChoice over three cases, the output described only by docstring examples
|
||||
- `bin/rank_todo.py:428` `place`: recursive topological placement with path-based loop detection, traced by hand
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/rule_hook/round_cap.py:24` `earlier_titles`: the round cap holds only at commit time, nothing refuses a third launch, and when git fails or no default branch is recorded it fails open; three files to establish that
|
||||
- `bin/round_titles.py:8` `CAP`: the `bin/` root holds about 60 entries, launchers, tool packages, shared modules and single-file tools at one level, told apart only by naming; the worst level
|
||||
- `bin/loop_claude/effects.py:36` `Effects`: 18 callables in loop-claude's home, yet imported by review_replay, loop_inbox and routing_check, so the README's claim that shared code lives at the bin/ root doesn't hold, and every feature adds a field every sharer pays for
|
||||
- `bin/git_command.py:17` `commits`: reads as "run a git command" but parses `git commit` out of shell words, one of three git modules
|
||||
- `bin/rule_hook/rules.py:139` `command_breaches`: some checks sit here, others in their own modules joined by main.py's bash_breaches, so adding a rule needs a choice the code doesn't explain
|
||||
- `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: a second source of truth for who is a reviewer, beside review_passes.py's table of the same name
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: "routing" spans loop_claude/routing.py, model_routing, routing_check, routing_figures and rung_replay
|
||||
- `bin/loop_claude/loop/main.py:169` `run_loop`: a fan-in of about 25 modules
|
||||
|
||||
## 2026-10-29T19:59:03Z, PR #397 at 1723469, against 77ab11e
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | better | same | same |
|
||||
| Inherited architect | same | worse | better | same | same |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/loop/main.py:182` `run_loop`: the line after `shown_running` rebinds `paths.waiting` to `listed.folder`, a private unlisted folder when the lock can't be taken; `interrupt` and `routing_check` read `paths.waiting` with no way to see the swap
|
||||
- Locality: `bin/loop_claude/waiting.py:123` `listed`: works only when the caller passes the folder `running_loops.shown_running` yields; in the base the ask carried its own liveness check
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:72` `review_launches`: types out the "Markdown no agent follows" list by hand instead of deriving it from `INSTRUCTION_FILES` and `INSTRUCTION_FOLDERS` in `bin/rule_hook/reviewer_rung.py:22`
|
||||
- Shape: `bin/loop_claude/verdicts.py:6` `TakenIn`: three loose fields on each verdict become one named value, and `taken_in_from` in `bin/loop_claude/cycle/judge.py:139` takes the clamping out of `verdict_from`
|
||||
- Navigation, Self-sufficiency: `bin/loop_claude/running_loops.py:1` module docstring: leads from "loop-inbox doesn't show my loop" to the mechanism as directly as the base's pointer to `waiting.py`; `session_lock.py` still sends the reader to `docs/decisions.md` for why lock files stay
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/loop/main.py:182` `run_loop`: rebinds `paths.waiting` to `listed.folder`, a throwaway `unlisted/<id>` folder where another loop holds the lock; `cycle/interrupt.py` and `loop/routing_check.py` write questions to a folder they can't see was swapped, explained only at `Listed.folder`
|
||||
- Locality: `bin/loop_claude/running_loops.py:3` module docstring: liveness moved from one `Ask.pid` field to a flock shared by `session_lock.py`, `running_loops.py` and `waiting.py`, and `listed` has a precondition stated only in its docstring
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:72` `review_launches`: its "Markdown only" list repeats `INSTRUCTION_FILES` and `INSTRUCTION_FOLDERS` in `bin/rule_hook/reviewer_rung.py:22` and the skill's "Markdown only" section, with nothing tying them together
|
||||
- Locality: `bin/loop_claude/running_loops.py:83` `locked_soon`: the flock lapses for a moment when the reload execs into the edited script inside the `with` at `bin/loop_claude/loop/main.py:185`, and no comment says so; the nested `ExitStack` takes more than one read
|
||||
- Shape: `bin/loop_claude/verdicts.py:6` `TakenIn`: one value replaces the `highest_*_taken_in` pair repeated across three verdicts, and `taken_in_from` checks the ranges in one place
|
||||
- Shape: `bin/rule_hook/reviewer_rung.py:22` `prose`: the name hides "Markdown no agent follows", and `markdown_only` runs git inside a hook module that was pure
|
||||
- Navigation: `bin/loop_claude/session_lock.py:1` module docstring: small, well-named modules lead to the protocol quickly, against liveness now spread over three files
|
||||
- Self-sufficiency: `bin/loop_claude/session_lock.py:1` module docstring: a new pointer to `docs/decisions.md`, offset by the in-place explanations at `Listed.folder` and `fetched_todo`
|
||||
|
||||
## 2026-10-29T20:01:40Z, PR #397 at 1723469
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 6 | 6 | 6 | 6 |
|
||||
| Maintainability senior | 7 | 6 | 6 | 6 | 6 |
|
||||
| Inherited architect | 6.5 | 6 | 5.5 | 7 | 6 |
|
||||
| Mean | 6.88 | 5.88 | 5.88 | 6.25 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: eight names held at once to follow one call; the docstring resolves it only after `escalation_mark.py` and `rules/todo-items.md`
|
||||
- `bin/rank_todo.py:568` `score`: every scoring step branches on SHAPE against OLD_SHAPE, so each function reads twice; nothing says when OLD_SHAPE can go
|
||||
- `bin/loop_claude/cycle/run.py:56` `run_cycle`: the route swaps on a step-up outside `transition`, and `archive_stepped` and `ask` touch it too, so where the rung changes has three answers
|
||||
- `bin/loop_claude/loop/reload.py:47` `decoded_as`: a recursive reflection-based decoder with two sentinels and a duck-typed `fits`; the comments give the reason
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: six conditional sentences; checking one branch needs `ladder.py`'s `review_rungs` and `replay_applies`
|
||||
- `bin/loop_claude/cycle/judge.py:185` `quotes_checked`: the misquote rule splits across `judge.py` and `escalation_mark.py`, and `grounded`'s fragment matching is subtle
|
||||
- `bin/comprehension_history.py:164` `worse_places`: one nested comprehension to unroll by hand
|
||||
- `skills/larv-review/SKILL.md:84` "Re-entry": a table plus exceptions across 🔴, 🟡, the cap and round 2
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: five near-synonymous rung helpers held at once, and one docstring sentence packs five rules; resolved only across `escalation_mark.py`, `ladder.py` and `route.py`
|
||||
- `bin/loop_claude/cycle/run.py:169` `ask`: `step_up` threads through three states, and which route each archived line names matters only for `routing_figures/measure.py`'s `rung_at`
|
||||
- `bin/loop_claude/loop/reload.py:47` `decoded_as`: a recursive decoder with two sentinels and duck-typed hooks that `Route` defines far away
|
||||
- `bin/rank_todo.py:428` `place`: recursive with loop detection, in the largest module, which keeps two table shapes side by side
|
||||
- `bin/chunk_pick.py:109` `next_release`: `Upcoming.landed` is `bool | Failure`, and "landed" has four meanings across modules
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: six conditional sentence kinds coupled to the routing rules
|
||||
- `bin/comprehension_history.py:159` `scored`: two look-alike predicates that differ on history formats named only by PR numbers
|
||||
- `bin/loop_claude/loop/main.py:1` module docstring: about 120 lines, every sentence a rule, restated again by the units
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: four rules in one pass over four near-synonym callees; the docstring lists them, but they still had to be simulated by hand
|
||||
- `bin/loop_claude/cycle/run.py:56` `run_cycle`: `cycle.route` is replaced inside the loop on a step-up, and a StepUp pair rides through the states so each archive line names the right rung
|
||||
- `bin/loop_claude/loop/reload.py:47` `decoded_as`: a recursive decoder with sentinels and a duck-typed `fits`; nothing at the call site says which LoopRun fields survive a reload
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: sentences branch on ladder positions, so checking one means computing rungs by hand
|
||||
- `bin/routing_figures/measure.py:104` `measured`: nine locals, timestamps matched as strings cut to the second, and price rescaling on one screen
|
||||
- `bin/rank_todo.py:332` `weigh`: the OLD_SHAPE compatibility is spread across many functions rather than cut at the boundary
|
||||
- `bin/comprehension_history.py:159` `scored`: differs from `newest_scored` only by a carve-out dated by a PR number
|
||||
- `bin/loop_claude/cycle/judge.py:185` `quotes_checked`: three quotes checked against three texts, each misquote with its own outcome; the exit-1 path takes four files
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `README.md:129` module map: names bin/'s 18 root modules only as a group, at a level of about 50 entries
|
||||
- `bin/round_titles.py:8` `CAP`: the round cap lives here and in `bin/rule_hook/round_cap.py:8`, not in larv_review/, and nothing says it counts commit titles rather than launches
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: step-up and escalation logic spans about eight files, from `cycle/run.py` to `loop/main.py`'s `stepped_route`
|
||||
- `bin/loop_claude/running_loops.py:1` module docstring: the inbox file protocol sits inside loop_claude though loop-inbox imports it
|
||||
- `bin/rule_hook/git.py:7` `git`: shadows `bin/git_repo.py:26` `git`, and `reviewer_rung.py` imports and calls both
|
||||
- `bin/rung_replay/search.py:17` `Item`: TypeVars named `Item` and `Reply` collide with `todo_table.Item` and judge.py's `Reply`
|
||||
- `bin/branch_chunks/cut.py:22` `Commit`: a second `Commit` dataclass with other fields than `bin/git_command.py:10`'s
|
||||
|
||||
## 2026-10-29T20:02:43Z, PR #397 rerun at 1723469
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 5.5 | 6 |
|
||||
| Mid A | 7 | 6 | 6.5 | 6.5 | 6.5 |
|
||||
| Maintainability senior | 6.5 | 5 | 6 | 5 | 5.5 |
|
||||
| Inherited architect | 6.5 | 6 | 5.5 | 7 | 6 |
|
||||
| Mean | 6.75 | 5.63 | 6.00 | 6.00 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: several conditions combine and hand off to six near-synonym rung helpers; the why sits behind `docs/decisions.md`
|
||||
- `bin/loop_claude/loop/reload.py:47` `decoded_as`: a recursive decoder with sentinels and an unwritten `fits` convention, followed only by tracing one call by hand
|
||||
- `bin/routing_figures/measure.py:104` `measured`: many jobs in one function, coupled to `costed` and a long comprehension in `render`
|
||||
- `bin/comprehension_history.py:130` `newest_scored`: a Markdown file parsed as a database, with back-compat notes dated by PR numbers
|
||||
- `bin/chunk_pick.py:166` `named_releases`: "release" is split across `chunk_pick`, `todo_table` and `larv_review/plan.py`
|
||||
- `bin/rank_todo.py:428` `place`: recursive, with OLD_SHAPE threaded through a 658-line file whose help text is the format spec
|
||||
- `bin/loop_claude/cycle/judge.py:185` `quotes_checked`: quote checks layered across three functions and `escalation_mark.py`
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: timestamps compared as text, and Read and Bash reads treated differently
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: folds five rules into one function, and the cap it enforces is spread across five files
|
||||
- `bin/loop_claude/loop/reload.py:47` `decoded_as`: a hand-written decoder with two sentinels, a union rule for RETIRED and a `fits` hook found by `getattr`; three passes to follow
|
||||
- `bin/rank_todo.py:568` `score`: two table shapes run through scoring, weighing and validation, and nothing says which is leaving
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: six sentence groups from one `ReviewChoice`, with a replay branch that `ladder.py`'s empty `REPLAYED` leaves without data
|
||||
- `bin/loop_claude/waiting.py:212` `claim_talk`: the `/talk` handshake runs between two programs through files and a flock, with deadlines and a compensating `ClaudeEnded`
|
||||
- `bin/rule_hook/repeat_read.py:72` `shown_lines`: pairs transcript tool calls with results by id and handles truncation markers of a transcript format written down nowhere
|
||||
- `bin/chunk_pick.py:109` `next_release`: renamed releases, the history since the last tag and landed work; the rename handling stayed unresolved
|
||||
- `bin/shell_command.py:44` `segments`: a heuristic token loop with a redirect-target flag; its docstring lists what it doesn't parse
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: combines the unfinished count, the escalation cap and whether a step already happened, with inputs built in `cycle/run.py`; three files open at once
|
||||
- `bin/loop_claude/cycle/prompts.py:55` `review_launches`: about six conditional sentence kinds, with no example output beside the function
|
||||
- `bin/loop_claude/loop/main.py:173` `run_loop`: the line rebinding `paths.waiting` to `listed.folder` quietly points every later question at another folder, explained only at `Listed.folder`
|
||||
- `bin/model_routing/ladder.py:97` `review_rungs`: the Markdown-only exception that lowers a reviewer lives only in `bin/rule_hook/reviewer_rung.py:34`, and `REPLAYED` is empty
|
||||
- `bin/loop_claude/loop/reload.py:47` `decoded_as`: sentinels, a duck-typed `fits` and recursion over type hints; which archived shapes decode needs `route.py` too
|
||||
- `bin/rank_todo.py:558` `goal_term`: OLD_SHAPE and SHAPE run through nearly every function, selected by the string "W" or "V"
|
||||
- `bin/loop_claude/waiting.py:212` `claim_talk`: a three-step handshake over three files, resolved only by holding the whole protocol
|
||||
- `bin/loop_claude/cycle/judge.py:207` `grounded`: a misquote is handled three ways by what was quoted, with no single table of the outcomes
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `README.md:129` module map: bin/'s root holds about 64 ungrouped entries, mixing review, plan and infrastructure modules
|
||||
- `bin/rule_hook/round_cap.py:8` `round_cap_breaches`: the cap counts round commit titles, while a third reviewer launch is governed only by `skills/larv-review/SKILL.md:76` "Round cap"
|
||||
- `bin/round_titles.py:22` `round_counts`: any unknown pass name gets its own counter, so a misspelled pass never reaches the cap
|
||||
- `bin/loop_claude/routing.py:76` `after_unfinished`: routing has four homes, from `model_routing/` to `loop/routing_check.py`
|
||||
- `bin/loop_claude/loop/main.py:256` `after_verdict`: the hub of about 25 imports that every routing or judge feature edits, with `stepped_route` on the same path
|
||||
- `bin/loop_claude/stop.py:1` `Stop`: documented as loop-claude's exit, but rung_replay exits through it and imports `cycle.retry` too
|
||||
- `bin/rank_todo.py:71` `GOAL_STEP`: a separable formula evaluator inside a 658-line, 39-function module
|
||||
- `bin/chunk_pick.py:1` module docstring: beside `bin/chunk_preflight/`, the names don't say which does what
|
||||
|
||||
+33
-6
@@ -50,12 +50,14 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the
|
||||
|
||||
2026-10-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
|
||||
|
||||
## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
## loop-claude: before it or loop-inbox opens claude on a terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
|
||||
2026-09-21, lilleman. Serves goal 1. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog. Trusting every worktree `git worktree list` names spares reading which one from the transcript. Since the human answers an interrupt on loop-claude's own terminal (todo item 168), claude opens there only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then. Valid while resume re-enters a recorded worktree and trust is kept per path.
|
||||
|
||||
2026-09-30, lilleman. A write by another claude inside `trust`'s read-modify-write window is lost, a risk larv-review accepted on 2026-09-24. Claude Code owns and writes `~/.claude.json`, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it.
|
||||
|
||||
2026-10-28, lilleman, todo item 243. `/talk` from loop-inbox opens claude in loop-inbox's terminal, through loop-claude's `hand_over`, which marks the trust just before. It adds a second writer to `~/.claude.json`, under the same risk, until item 6 ends it.
|
||||
|
||||
## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
|
||||
2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session.
|
||||
@@ -99,6 +101,21 @@ Hours. A chunk ran a median 0.7 hours from its first message to its last, one in
|
||||
|
||||
Valid while cache reads cost a twentieth of input and Claude Code's compaction keeps the worker's task.
|
||||
|
||||
## loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
|
||||
|
||||
2026-10-28, lilleman, todo item 243. Serves goal 1. With several loops running, each asked on its own terminal, and the human searched the terminals for the ones that waited. loop-inbox lists every loop's interrupts, the routing calls included, oldest first, and the human answers each one there. A loop asking for its project's model, as on a project's first run, asks on its terminal only: the human has just started it there, and no worker session exists yet. `bin/loop_claude/waiting.py` holds the protocol:
|
||||
- An answer reaching the wrong loop is the worst failure. Each answer names the question it answers by a fresh id, so an answer meant for an earlier question, or sent as the terminal answered, never answers a later one.
|
||||
- `/talk` from loop-inbox waits for the loop to stop reading its terminal before claude opens, so only one claude holds the worker's session.
|
||||
- While claude is open for a question, as for a release ready to cut, the routing calls or a `/talk`, loop-inbox lists the loop and where claude is open, but takes no answer for it.
|
||||
- loop-inbox runs the claude command the loop wrote, `bypassPermissions` included, so that claude runs in the same sandbox as the loop. Since loop-inbox runs a command read from a file, the folder is private to the user.
|
||||
- Files, read by polling, need no daemon and only the standard library, and a loop with no loop-inbox running is answered on its terminal as before.
|
||||
- loop-inbox lists a question only while its loop holds the session's lock file with flock, and removes a question whose lock is free. The loop holds the lock for its whole run. The kernel frees the lock however the loop ends, killed included. A process id could not tell a running loop from a killed one: on 2026-10-29 this machine's kernel handed out its 32,768 ids again every 30 to 75 minutes, so a killed loop's question came back whenever another process got its id. The lock file stays once the loop ends, one per project: removing it while another process has it open could let loop-inbox lock a file no loop holds. PR #396.
|
||||
- A loop also lists itself as running, with the items its chunk takes, in `<session>.running`, under the same lock: one lock tells loop-inbox both that the loop runs and that its question stands. The judge names the items the worker took in, as an array of IDs in its reply's `items_taken_in`. PR #397.
|
||||
|
||||
A bench of three readers seated as the README's audience picked the name `loop-inbox`, 3–0.
|
||||
|
||||
Valid while every loop and loop-inbox run on one machine under one user's home.
|
||||
|
||||
## machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
|
||||
2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, whether direct or inside a container. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once.
|
||||
@@ -145,19 +162,25 @@ Valid while no published standard sets either number, the reading-cost window st
|
||||
|
||||
2026-10-08, lilleman. Serves goal 1.4: run beside the full scan, `/security-review` started seconds apart from it each round and returned a near-identical report. Valid while the full scan covers what `/security-review` reports.
|
||||
|
||||
## review: a fix for a 🔴 or 🟡 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
## review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none
|
||||
|
||||
2026-10-08, lilleman. Serves goal 1.4. An audit of the four costliest archived chunks found nearly every finding that mattered in a pass's first round; when every fix, a nit's included, re-entered review, later rounds mostly re-checked the last fix, reworded what an earlier round wrote, or contradicted another round on the same line. A round 2 caught real bugs only where a fix changed behaviour, so stability still reruns on every fix that does, and security on every fix that opens an untrusted-input boundary or touches authn/authz, secrets or crypto. Valid while round-2 reviews of nit and prose fixes keep changing nothing a user would notice.
|
||||
|
||||
2026-10-13, lilleman through todo item 97. Serves goals 1.4 and 1.5. From round 2 a pass reviews only how the chunk answered its previous round, each fix and each dismissal with its reason, and reports only one that is plainly wrong or worse than the change it answered. A fix from another pass that re-enters it is still reviewed as a first round would review it, limited to its lines. Reviewing all that changed had a reviewer find new gaps in each round's fixes, so a pass ran to its cap. Valid while round-2 findings outside a round's answers keep changing nothing a user would notice.
|
||||
|
||||
2026-10-29, lilleman. Serves goals 1.4 and 1.5. A 🟡 fix no longer reruns its pass. One project's chunk on 2026-10-29, a README paragraph and plan rows, took 10 review rounds in 45 minutes, and three of its four second rounds answered only 🟡 findings, such as the wording of a question's options. Round 2 found 12 🔴 in about 200 runs since 2026-10-21, mostly in round 1's fixes of 🔴 findings, so a 🔴 fix still reruns its pass. A 🟡 fix that breaks something merges unreviewed by its pass; another pass whose row it meets for a 🔴 fix in the same round still reviews it. Valid while 🔴 findings in later chunks, fixing code a 🟡 fix wrote, stay rare.
|
||||
|
||||
## review: a comment is prose in any file; a branch changing only Markdown no agent follows runs only the prose pass and, for README or docs an outside reader lands on, the product-owner pass; plan rows a chunk files from a finding, re-scores or moves get no review
|
||||
|
||||
2026-10-29, lilleman. Serves goals 1.4 and 1.5. One project's chunk on 2026-10-29 changed a README paragraph, `todo.md` and three lines of `gate.yml`, and the principles, security and stability passes all ran on it, each twice: 6 of the chunk's 10 rounds. A change to config is one that changes what runs, so a comment in it fires only the prose pass, as a comment in code already did. A branch that changes only Markdown no agent follows changes no code, config or tests, so no pass that reads those runs on it. A plan row a chunk files from a finding, re-scores or moves is read by the chunk that ships it, so reviewing it at filing reviewed it twice: that chunk spent a prose round of 4 minutes on its plan change. Markdown an agent follows, such as a skill, is config, since a change there changes what agents do. Valid while defects in prose-only chunks stay rare in later chunks' fixes.
|
||||
|
||||
## review: a pass gets at most two rounds per chunk, with no third and no ask for one; the fixes answering round 2 merge once the gate passes
|
||||
|
||||
2026-10-28, lilleman through todo item 246. Serves goals 1 and 1.4. One counter per pass per chunk, so no fix bounces between two passes without end. lilleman measured every repo's round titles since 2026-10-21. Round 1 ran 357 times and found 59 🔴. Round 2 ran about 200 times and found 12 🔴, mostly in round 1's fixes. Rounds 3 and later ran about 110 times and found no 🔴, at about $125 of review at list prices, and asks for a fourth or fifth round were 24 of the 59 interrupts. The cap had stood at three because a lower cap would ask the human more often; once nothing asks, that reason is gone. A rerun one rung up belongs to the round it reruns, so it doesn't count toward the cap: `review: a reviewer or comprehension seat that rules the work below standard`.
|
||||
|
||||
rule-hook's `round-cap` refuses a round commit that would take its pass past round 2, and no override waives it. It counts the pass's round commits on the branch as `larv-review round-count` does, so a third commit titled round 2 is refused too. The hook must not fetch, so it lists the branch's commits since the default branch as last fetched. It follows first parents, so the round commits that a merge of a newer default branch brought in don't count as this chunk's. It leaves out the commit an `--amend` replaces. Where git cannot list the branch's commits, within 5 seconds or because origin records no default branch, it counts the title's own number alone, so a slow or unset lookup doesn't block the commit.
|
||||
|
||||
Valid while the defects that later commits fix in a finished chunk's code, which `todo.md` item 247 counts, don't rise per chunk.
|
||||
Valid while the later fixes per finished chunk, which `score-outcomes` and the routing figures count, don't rise.
|
||||
|
||||
## review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
|
||||
|
||||
@@ -183,7 +206,7 @@ Valid while the ladder orders its rungs by competence.
|
||||
|
||||
## review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
|
||||
|
||||
2026-10-23, claude. Serves code health (`CLAUDE.md` → "Shared goal"): its counter-signal, reviewers raising blockers because the implementer misunderstood the current system, had no count, since no tool recorded why a finding arose. The reviewer is the one that knows, so it marks the finding (`skills/larv-review/review-findings.md` → "Misread"). The worker counts the marked 🔴 and 🟡 findings in the round's commit title, `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, which `score-outcomes` already reads for the 🔴 and 🟡 counts, so the count needs no record of its own. rule-hook's `round-title-counts` refuses a round title without the count, or with more misread findings than findings, so a title that leaves the count out never reads as zero; titles from before the count read as unknown. Only the reviewers under `agents/` mark findings. `/security-review` marks none, so its round titles count 0 misread, and the count is a floor. A bench of three readers seated as the audience chose `[misread]` right after the severity mark, which stays at a fixed place on a skimmed line, and the parenthesis `(1 misread)`, which reads as a share of the 🔴 and 🟡 counts rather than a third kind of finding, each two to one. The other half of the counter-signal, defects that keep reappearing, waits for the later fixes that `todo.md` item 110 counts. Valid while round titles are where `score-outcomes` reads a chunk's findings.
|
||||
2026-10-23, claude. Serves code health (`CLAUDE.md` → "Shared goal"): its counter-signal, reviewers raising blockers because the implementer misunderstood the current system, had no count, since no tool recorded why a finding arose. The reviewer is the one that knows, so it marks the finding (`skills/larv-review/review-findings.md` → "Misread"). The worker counts the marked 🔴 and 🟡 findings in the round's commit title, `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, which `score-outcomes` already reads for the 🔴 and 🟡 counts, so the count needs no record of its own. rule-hook's `round-title-counts` refuses a round title without the count, or with more misread findings than findings, so a title that leaves the count out never reads as zero; titles from before the count read as unknown. Only the reviewers under `agents/` mark findings. `/security-review` marks none, so its round titles count 0 misread, and the count is a floor. A bench of three readers seated as the audience chose `[misread]` right after the severity mark, which stays at a fixed place on a skimmed line, and the parenthesis `(1 misread)`, which reads as a share of the 🔴 and 🟡 counts rather than a third kind of finding, each two to one. The other half of the counter-signal, defects that keep reappearing, is each chunk's later fixes, which `score-outcomes` lists after the misread findings. Valid while round titles are where `score-outcomes` reads a chunk's findings.
|
||||
|
||||
## review: an ask no user answers leaves the PR unmerged
|
||||
|
||||
@@ -245,7 +268,7 @@ The run has no time cap. Limiting it to the changed lines already bounds it by t
|
||||
|
||||
Valid while a mutation run on a chunk's changed lines stays cheap beside the review itself.
|
||||
|
||||
## routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
|
||||
## routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass or the branch changes only Markdown no agent follows, which reviews on the project's rung; the seats and the security pass always on the project's
|
||||
|
||||
2026-10-14, lilleman. Serves goals 1.1 and 1.4.
|
||||
|
||||
@@ -257,6 +280,8 @@ On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on ei
|
||||
|
||||
Valid until the trial on real chunks shows whether a worker below the project's rung holds quality.
|
||||
|
||||
2026-10-29, lilleman. Serves goals 1.4 and 1.5. A branch that changes only Markdown no agent follows reviews on the project's rung, whatever its items' E + I. E + I scores an item before its chunk starts, by the change the item asks for, so one project's item, filed to build a control on a CI runner, kept its E + I of 7 when the chunk found no control the repo could build and shipped a README paragraph: five reviewers read prose on Opus 5.5 at xhigh. rule-hook's `reviewer-rung` reads the branch's files, committed or not, against the default branch as last fetched. Markdown an agent follows, `CLAUDE.md`, `AGENTS.md` and files under `agents/`, `principles/`, `rules/` or `skills/`, counts as config. Valid while a README or docs defect costs a reader no more than review on the project's rung lets through.
|
||||
|
||||
## 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, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
|
||||
|
||||
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung, and the agent proposed the replay that gates it. On 2026-10-16 lilleman asked for the prose pass to run on the worker's rung or lower, and, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. Serves goal 1.4 without giving up goal 1.1: a cheaper reviewer saves money only where it misses nothing.
|
||||
@@ -333,7 +358,7 @@ Valid while the archived verdicts show what a judge should return, and until a n
|
||||
|
||||
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one ladder, the same in every project, read by loop-claude and by the worker through `bin/subagent-rung`. The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/ladder.py` holds the rungs and the steps.
|
||||
|
||||
The rungs, least competent first: 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.
|
||||
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.
|
||||
|
||||
@@ -341,6 +366,8 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
|
||||
|
||||
2026-10-23, lilleman: 15 chunks had shipped under today's steps. Over them, L's rank correlation with review rounds was +0.53. They held only 3 🔴 findings, too few to test E and I. 50 chunks hold about 10 at that rate, and a re-tune on fewer chunks would fit noise.
|
||||
|
||||
2026-10-29, lilleman: Haiku 5.5 is off the ladder, so no worker, subagent or review runs on it, and a Sonnet 5.5 project's L 1 and L 2 workers stay on Sonnet 5.5 at high. One project's chunk on 2026-10-29, a README paragraph and plan rows, ran on Haiku 5.5 at max for 2 h 17 min and wrote 3.1 million output tokens; the chunk before it, item 7, a merge gate with tests, took 29 minutes and 111k tokens on Sonnet 5.5 at high. The routing figures had shown the same before: chunks started on Haiku 5.5 at max took 7.8 review rounds past each pass's first against 2.8 on Sonnet 5.5 at high (goals 1.4 and 1.5). A review replay can now lower a pass only to Sonnet 5.5 at high, and on a Sonnet 5.5 project to no rung.
|
||||
|
||||
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
|
||||
|
||||
@@ -907,3 +907,19 @@ Read most (opens and searches):
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/todo-items.md` 4
|
||||
|
||||
## Reading cost, chunk da9c1fcad7c3, finished 2026-10-28T17:55:08Z
|
||||
|
||||
139037 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk 07c647e1636e, finished 2026-10-28T21:51:38Z
|
||||
|
||||
105188 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/todo-items.md` 1
|
||||
|
||||
## Reading cost, chunk cfd9ab4f5b1b, finished 2026-10-28T22:00:08Z
|
||||
|
||||
64114 new input tokens before the first commit.
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ paths:
|
||||
- **Name in Moves each achieve goal in `README.md` → `## Goals` the item moves, and how far,** from 1 to 10, judged by its value to the audience in `## Audience`: `1.1 by 8, 1.2 by 5`. Where the item moves code health, the goal in `CLAUDE.md` → "Shared goal", name it as in `code health by 6`, unless the README voids it. Name the most specific goal it moves, and a parent goal only for a move none of its sub-goals covers, never beside its own sub-goal. Leave out every maintain goal, which vetoes, except on an item marked `defect` that restores it: name that goal, and how much of it is broken. `rank_todo.py --help` says how it weighs each goal.
|
||||
- **A table with C, A, G and Goals in place of L, E, I and Moves is in the old shape.** Reshaping it is the project's only work until done, as `CLAUDE.md` → "Working loop" says, and `rank_todo.py` says how. Until then, A is the item's value to the audience and G its value to the goals it cites.
|
||||
- **Score L, E and I against the project's anchors, and check every score against finished chunks.** Guess the scores, then run `~/.claude/bin/score-outcomes <L> <E> <I> <S>` in the project. It lists the finished items guessed nearest and the project's anchors, the shipped items its `docs/score-anchors.md` names for each level, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings. Compare the item with each anchor in turn: is it more or less likely to hold a defect, to let one escape, or to do damage? Give it the level whose anchors it matches; where a level has no anchor, judge by the level's words in the table above. Set S to the value guessed for the finished items whose outcome matches what you expect of this one. Keep your guess when no listed item resembles the one you are scoring.
|
||||
- **Anchor each level of L, E and I with two or three items the project shipped,** in `docs/score-anchors.md`: a table whose Level column names a level, such as `L 1`, and whose Items column lists the anchors' IDs, such as `12, 14`. Choose an L anchor whose chunk, as `score-outcomes` measured it, fits the level's words: its lines changed and the components it touched. Choose an E or I anchor by the level's words and what followed its release, since no tool measures either yet. Leave out a level no shipped item shows. Replace a level's anchors when the items scored at it turn out about ten times more likely, or ten times less likely, than its words say: to hold a defect, to let one escape, or to do damage.
|
||||
- **Anchor each level of L, E and I with two or three items the project shipped,** in `docs/score-anchors.md`: a table whose Level column names a level, such as `L 1`, and whose Items column lists the anchors' IDs, such as `12, 14`. Choose an L anchor whose chunk, as `score-outcomes` measured it, fits the level's words: its lines changed and the components it touched. Choose an E anchor by the level's words and the later fixes `score-outcomes` counts for its chunk, the defects that escaped it. Choose an I anchor by the level's words and what followed its release, since no tool measures I yet. Leave out a level no shipped item shows. Replace a level's anchors when the items scored at it turn out about ten times more likely, or ten times less likely, than its words say: to hold a defect, to let one escape, or to do damage.
|
||||
- **Read the places the comprehension seats found hard before filing an item.** `~/.claude/bin/larv-review places`, run in the project, prints them. Where the item's change touches one, its detail says to make that place easier to read.
|
||||
- **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score.
|
||||
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding or an item that restores a maintain goal the project breaks today, `question` for a question only the human can answer, which ranks first in its release, `decision` for an item `docs/decisions.md` cites, `owner` for an item the human told you to keep, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
|
||||
|
||||
@@ -41,9 +41,13 @@ A pass is one kind of review, a row of the table, named by its first column. Its
|
||||
| Overrides | override-reviewer | `~/.claude/bin/rule-hook overrides`, run in the chunk's worktree, prints a line no round of this pass has ruled on |
|
||||
| Stability | stability-reviewer | changes code, config or tests |
|
||||
| Product-owner | product-owner-reviewer | changes an external surface: API, CLI, UI, error or deprecation text a consumer reads, README and docs an outside reader lands on |
|
||||
| Prose | prose-reviewer | changes prose a reader reads, such as docs, comments, help or error text, or the plan; one round |
|
||||
| Prose | prose-reviewer | changes prose a reader reads, such as docs, comments, help or error text, or the plan's text for an item the chunk ships, splits or answers; one round |
|
||||
|
||||
A comment is prose, not code.
|
||||
A comment is prose, not code, in any file. A change to config is one that changes what runs, so a comment in a workflow or compose file fires only the prose pass. Markdown an agent follows is config: `CLAUDE.md`, `AGENTS.md`, and files under `agents/`, `principles/`, `rules/` or `skills/`.
|
||||
|
||||
**Plan rows.** A `todo.md` row or detail that the chunk files from a finding, re-scores or moves between releases gets no review: the chunk that ships the item reads it.
|
||||
|
||||
**Markdown only.** A branch that changes only Markdown no agent follows, such as `README.md`, `docs/` and `todo.md`, changes no code, config or tests. It runs the prose pass, and the product-owner pass where it changes README or docs an outside reader lands on; no other pass. Its reviewers run on the project's rung, whatever its items' E + I; rule-hook's `reviewer-rung` allows that.
|
||||
|
||||
**Waves.** Launch a round's passes in up to three waves. Launch each wave's reviewers in one message: Agent calls in one message run together, so a wave lasts as long as its slowest reviewer. Start a wave only once every pass of the waves before it is done ("Round cap" → "Done"): line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. Skip a wave none of whose passes runs.
|
||||
|
||||
@@ -77,18 +81,18 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
|
||||
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass and a pass at its cap, fixed. Resolve that round's 🟢s and ❓s per "Findings" too.
|
||||
- **Cap.** A pass takes at most two rounds per chunk; don't ask the user for a third. Answer its second round's findings per "Findings": those fixes merge once the gate passes, unreviewed by that pass. rule-hook's `round-cap` refuses a round commit that would take a pass past two, and no override waives it. A review the auto-reviewer posts after its second isn't a round: fix none of it and rerun no pass for it, but file a security finding it raises per `~/.claude/CLAUDE.md` → "Working loop", and any other 🔴 in `todo.md`.
|
||||
|
||||
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟢, a ❓ or a prose finding reruns no pass, whatever it changes. A round's fixes for 🔴 and 🟡 findings re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4. A pass at its cap doesn't run again ("Round cap" → "Cap").
|
||||
**Re-entry.** A fix is a change no pass has seen. A fix for a 🟡, a 🟢, a ❓ or a prose finding reruns no pass, whatever it changes. A round's fixes for 🔴 findings re-enter together: run every pass that a row below names for any of them, a done pass included, in the waves of "Waves", then §4. A pass at its cap doesn't run again ("Round cap" → "Cap").
|
||||
|
||||
| The fix | Reruns |
|
||||
|---------|--------|
|
||||
| answers a 🔴 or 🟡 of a pass other than prose | that pass |
|
||||
| answers a 🔴 of a pass other than prose | that pass |
|
||||
| carries an architectural decision | Architecture |
|
||||
| changes code, config or tests | Principles |
|
||||
| opens an untrusted-input boundary or touches authn/authz, secrets or crypto | Security, unless the full scan reruns on it |
|
||||
| made rule-hook log an override | Overrides |
|
||||
| changes behaviour: what the code or its tests do | Stability |
|
||||
|
||||
A fix meets every row it fits. Prose has no row, so a comment or doc edit inside a fix reruns nothing. Example: a fix for a stability 🟡 that changes code and a comment reruns Principles and Stability.
|
||||
A fix meets every row it fits. Prose has no row, so a comment or doc edit inside a fix reruns nothing. Example: a fix for a stability 🔴 that changes code and a comment reruns Principles and Stability.
|
||||
|
||||
**What a round reviews.** An agent under `~/.claude/agents/` reviews the branch in round 1. From round 2 it reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with the path of its last round's report and each finding's answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
|
||||
|
||||
|
||||
@@ -6,18 +6,18 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 251`
|
||||
`Next ID = 256`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 247 | 0.4.0 | | owner | **Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4 | 1.7 |
|
||||
| 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 |
|
||||
| 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 |
|
||||
| 248 | 0.5.0 | | question | **Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 2 | 3.3 |
|
||||
| 250 | 0.5.0 | | | **Move the repeat-read rule's transcript, mtime and file reads from `bin/rule_hook/main.py` into `bin/rule_hook/repeat_read.py`, behind one `*_breaches` entry point like the other rules, and name the tuple `results_on` returns.** | 2 | 1 | 3 | 4 | 3 | code health by 3 | 13.5 |
|
||||
| 253 | 0.5.0 | | principle | **Group `bin/loop_claude/waiting.py`'s 29 top-level names, such as the ask's states, the answers and the /talk handshake, so each level holds about seven.** | 2 | 1 | 3 | 4 | 3 | code health by 3 | 13.5 |
|
||||
| 235 | 0.5.0 | | decision | **Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2, 1.4 by 3 | 6.8 |
|
||||
| 254 | 0.5.0 | | principle | **Store when a loop asked as an ISO UTC datetime in loop-inbox's ask files.** | 1 | 1 | 2 | 2 | 2 | code health by 1 | 6.0 |
|
||||
| 167 | 0.5.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 |
|
||||
| 6 | 0.5.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 240 | 0.5.0 | | decision | **Give loop-claude's worker prompt the reading rule "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", and keep it only where the 20 chunks after it hold the 20 before's review rounds, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk.** | 1 | 2 | 3 | 4 | 2 | 1.4 by 3 | 4.0 |
|
||||
@@ -47,7 +47,6 @@
|
||||
| 81 | 0.6.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.6.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.6.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 |
|
||||
| 110 | 0.6.0 | | decision | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 6, 1.4 by 6 | 4.9 |
|
||||
| 12 | 0.6.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.6.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.6.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 |
|
||||
@@ -79,23 +78,6 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 247. Count each finished chunk's escaped defects, the later commits that fix code it shipped, in `score-outcomes` and the routing figures.
|
||||
|
||||
lilleman's call, 2026-10-28. Escaped defects are the counter-signal of goals 1 and 1.1, and nothing counts them, so nobody can tell whether review spending prevents defects or only polishes. A review costs about 56% of a chunk's dollars. Count, for each finished chunk, the later commits on the default branch that fix lines it added: a fix item's chunk, a `defect` item, or a 🔴 marked `[misread]` whose lines `git blame` traces to the earlier chunk. Show the count per chunk and its median per rung in `score-outcomes` and `routing-figures.md`, so a cheaper review pipeline can be judged against it. Measure on every project in loop-claude's archive.
|
||||
|
||||
### 243. Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.
|
||||
|
||||
lilleman's call, 2026-10-28: with several loops running, each asks on its own terminal, so the human jumps between terminals to find which wait. On 2026-10-28 three of five loops waited on round-cap questions at once. Today `put_question` in `bin/loop_claude/cycle/interrupt.py` reads the answer with `input()`, and nothing outside that terminal sees a question.
|
||||
|
||||
- Each loop, as it asks, writes one file per session under `~/.local/state/loop-claude/`, holding the project, the question, when it was asked, its pid and whether `/talk` is offered, and removes it once answered or stopped.
|
||||
- While it waits, the loop takes the first answer from either its terminal or the app, so a loop keeps working with no app running.
|
||||
- The app lists the waiting loops oldest first and sends a typed one-line answer to the loop it is meant for. A loop whose pid is gone drops off the list.
|
||||
- `/talk` from the app runs `claude --resume` for that session in the app's terminal; the loop then waits, as `talk` does today, until a human turn appears in the transcript.
|
||||
- A release ready to cut, which today opens the session at once, shows in the app too.
|
||||
- It runs on the host's Python with the standard library, such as `curses`, as `docs/decisions.md` → `bin/: the tools and their tests run on the host's Python` has it.
|
||||
|
||||
Bench the app's command name and how it shows a question with readers seated as the README's audience before it ships. An answer reaching the wrong loop is the worst failure: a test sends answers to two waiting loops and checks each gets its own. The change touches `loop-claude --help` in `bin/loop_claude/loop/main.py`, which the comprehension seats found hard: make it easier to read where it describes the interrupt.
|
||||
|
||||
### 226. Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.
|
||||
|
||||
Found by review of PR #370. Today `uv run mutmut run`, `poetry run mutmut run`, `python3 -m mutmut run`, `sudo docker build .`, `docker image build .` and `docker compose up --build` pass the rule, which `docs/decisions.md` → `machine load: …` and `RULES["run-heavy"]` describe as blocking docker builds and mutation runs. The rule's own text says a gate script isn't checked since no program can tell it from a light one, so the human decides where the line sits. Say what the rule's "checked" text promises either way. Where the answer widens the rule, the change touches `heavy` in `bin/rule_hook/heavy_command.py`, which the comprehension seats found hard: make it easier to read.
|
||||
@@ -108,10 +90,18 @@ Filed from PR #387's architecture round 1. The decision's 2026-10-16 addendum sa
|
||||
|
||||
Found by the paired ruling of PR #387: all four seats ruled Locality worse at `read_breaches`, `modified` and `first_lines` in `main.py`. The rule's reads sit there while its logic sits in `repeat_read.py`, and two contracts cross the seam: `modified` must stamp the mtime as the transcript stamps entries, since `shown_lines` compares the two as text, and `first_lines` must read one line past the last shown one, which `repeat_breaches` needs. Make these places easier to read: keep both contracts inside `repeat_read.py`, the way `todo_check.py` and `reviewer_report.py` do their own reads. Replace `results_on`'s positional four-part tuple with a named type, and rename `repeat_read.written`, which names a path while `written` in `main.py` names the text that may carry an override marker.
|
||||
|
||||
### 253. Group `bin/loop_claude/waiting.py`'s 29 top-level names, such as the ask's states, the answers and the /talk handshake, so each level holds about seven.
|
||||
|
||||
Found by the principles review of item 252, against the technical principles' "about seven things per level". A split by role is one way: the ask's file and states, the answers loop-inbox sends, and the /talk handshake, `claim_talk` and `make_way`.
|
||||
|
||||
### 235. Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.
|
||||
|
||||
`docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: 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 at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; the routing figures now put such dollars in. A chunk ran under the window when its first worker started after that decision merged.
|
||||
|
||||
### 254. Store when a loop asked as an ISO UTC datetime in loop-inbox's ask files.
|
||||
|
||||
Found by the principles review of item 252, against the technical principles' rule that timestamps are ISO UTC. `Ask.asked` in `bin/loop_claude/waiting.py` is a float of seconds since the epoch, which `publish` writes to `<session>.json` and `read_ask` reads back. loop-inbox shows it as a local time and a wait, so change the code that shows it too.
|
||||
|
||||
### 167. Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.
|
||||
|
||||
rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invokes `/security-review` in its own context, instead of in a subagent, runs the pass on its own rung, and nothing blocks it. Check Skill calls too: `breaches_of` in bin/rule_hook/main.py takes a Skill call whose skill is `security-review` or `claude-security` as a review launch, and settings.json's PreToolUse matcher gains Skill. Found by the systems-architect's review of PR #295.
|
||||
@@ -162,7 +152,7 @@ F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk cos
|
||||
|
||||
### 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. Make `decoded_as` easier to read.
|
||||
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.
|
||||
|
||||
@@ -244,10 +234,6 @@ Raised by the overrides pass of PR #296. The hook imports the main checkout's `r
|
||||
|
||||
Found by the principles audit of PR #242, against "Functional core, imperative shell" (`principles/technical-principles.md`). `bin/larv_review/history_commands.py:87` reads `time.time()`, then checks git (`:90`, `commit_exists`) and the history file (`:92`) inside the function that parses the seats file and decides. A test cannot fix the heading's time, and every test of `read_seats` touches the real checkout.
|
||||
|
||||
### 110. Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.
|
||||
|
||||
`score-outcomes` measures risk only by the 🔴 findings review caught. A serious bug review missed shows later, as a change that fixes code the chunk wrote: the defect that escaped, which E guesses.
|
||||
|
||||
### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.
|
||||
|
||||
The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word.
|
||||
@@ -374,7 +360,7 @@ The key names the project's session, archive folder and models entry. `project_k
|
||||
|
||||
### 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, `put_question`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
"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.
|
||||
|
||||
### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.
|
||||
|
||||
@@ -390,7 +376,7 @@ The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/c
|
||||
|
||||
### 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. `effects.input` reads the answer to both of loop-claude's questions: the interrupt, in `cycle/interrupt.py`'s `put_question`, and the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. Importing `readline` in `effects.py` gives both line editing, at two costs. 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."
|
||||
`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."
|
||||
|
||||
### 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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user