Compare commits
48 Commits
item-281
...
item-trigger
| Author | SHA1 | Date | |
|---|---|---|---|
| 1fa03973a3 | |||
| 329f0fd3a0 | |||
| 52da15ea2b | |||
| 09caf3576f | |||
| 7fb019914e | |||
| 5c08bc34d6 | |||
| 0fdaf926c5 | |||
| 87273e94a4 | |||
| 13d1550299 | |||
| 58402083cb | |||
| 567ff471ec | |||
| 538fbc52b9 | |||
| ac98e0e4a7 | |||
| e69eb982bc | |||
| 1c6e04c8b8 | |||
| 92867f64cd | |||
| 0301ca01c4 | |||
| 3ee136ae44 | |||
| 5b230fd013 | |||
| d2ad46c9cb | |||
| 03ee7a4a75 | |||
| 79d764e682 | |||
| 6440824f27 | |||
| e10e301582 | |||
| 1bb740a47f | |||
| 05539e2e0d | |||
| 998e295ef9 | |||
| f2fef1d32d | |||
| 7d187d22f3 | |||
| 493a652499 | |||
| 12d70586ed | |||
| ce941388a2 | |||
| b6038c4e41 | |||
| a875e11e00 | |||
| 70a1b95086 | |||
| b3d4b8fe27 | |||
| 8a80d452f2 | |||
| ce126aa1aa | |||
| 055ee752ba | |||
| 5f47b4e1d5 | |||
| ed0fea8eef | |||
| b195ba8bf1 | |||
| 7143c9daad | |||
| cfd3008615 | |||
| 41b91e2265 | |||
| 968f22b5ae | |||
| 23381b08eb | |||
| 509804da0d |
@@ -53,9 +53,14 @@
|
||||
!bin/loop_claude/
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!bin/loop_effects/
|
||||
!bin/loop_effects/*.py
|
||||
!bin/loop-inbox
|
||||
!bin/loop_inbox/
|
||||
!bin/loop_inbox/*.py
|
||||
!bin/loop_state/
|
||||
!bin/loop_state/**/
|
||||
!bin/loop_state/**/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/metric-bench
|
||||
|
||||
@@ -6,7 +6,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and no score blocks a merge or release
|
||||
- deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
|
||||
- deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's
|
||||
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
|
||||
@@ -40,7 +40,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
|
||||
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
|
||||
- review: the architecture and principles passes run only in the release review, a release's last chunk, which must land before the release is ready to cut; between releases the product-owner pass reviews changes to what consumers rely on
|
||||
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
- review: the comprehension check records how hard a project is to read, and no score blocks a merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
- review: the premises chunk's whole review is the human's approval
|
||||
- review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies
|
||||
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `chunk-pr merge` now refuses while a scoring run the plan calls is unrecorded on the branch, and `larv-review needs-scoring-run` calls one after a release is cut with none.
|
||||
|
||||
## 0.7.0
|
||||
|
||||
- README's test, CI and mutation-test commands now have their own section, README → Test.
|
||||
- `rule-hook overrides` now lists the chunk's overrides when a file or folder shares the branch's name. It used to exit saying it could not read the reflog.
|
||||
- `chunk-pr clean` removes a merged chunk's worktree and local branch and fast-forwards the main checkout. It leaves a main checkout with uncommitted files, another branch or commits of its own as it was, and says why.
|
||||
- `review-replay` now replays each round at the commit with the newest author time at or before the round's time, and takes the clone's base the same way by the time the chunk began. It took the first such commit in log order, so a commit authored early but merged late, such as a dependency bump, could win over the commits the round reviewed.
|
||||
- The shared goal every project pursues, code health, now asks that code stay easy to read, change safely and debug, tomorrow and after seven years of development.
|
||||
|
||||
@@ -113,6 +113,31 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
|
||||
- `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.
|
||||
- `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file, and `todo-item --help` states the flags.
|
||||
|
||||
`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. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py` and `failure.py`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` 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.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
|
||||
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
|
||||
- `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, loop-inbox, both replay tools and `reviewer-merge-trials`' driver use it.
|
||||
- `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools.
|
||||
- `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.
|
||||
- `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new.
|
||||
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `plan_file.py` reads, ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item`.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `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, and finds that file through `loop_state`'s paths.
|
||||
- `test_env.py` serves the tests.
|
||||
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
|
||||
|
||||
## Test
|
||||
|
||||
Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in four workers, one heavy slot's CPUs (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's scripts with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
|
||||
CI runs `ci.sh` on every pull request, and `main` merges nothing until it passes. The script runs the same tests on the committed HEAD in a pinned Python container; run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH`.
|
||||
@@ -130,28 +155,6 @@ 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. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py` and `failure.py`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` 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.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
|
||||
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
|
||||
- `judge_replay` imports `loop_claude`'s judge.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
- `loop_inbox` imports `loop_claude`'s question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), its effects and paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes loop-inbox too.
|
||||
- `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.
|
||||
- `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new.
|
||||
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, which `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item` import).
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `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.
|
||||
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
`.gitignore` is an allowlist. Track a file by negating it and its parent directories, then confirm with `git check-ignore -v <path>`:
|
||||
|
||||
@@ -5,11 +5,11 @@ import re
|
||||
import typing
|
||||
|
||||
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.todo_table import Exempt, Item
|
||||
from review_rules.round_titles import title_counts
|
||||
|
||||
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
|
||||
FIXES = ("defect", "security")
|
||||
FIXES: tuple[Exempt, ...] = ("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]+")
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
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_cli.git_repo import Run, text_at
|
||||
from git_cli.git_repo import Git, text_at
|
||||
|
||||
|
||||
def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure:
|
||||
def branch_chunks(default: str, run: Git) -> 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."""
|
||||
@@ -23,7 +23,7 @@ def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure:
|
||||
return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced)
|
||||
|
||||
|
||||
def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure:
|
||||
def plans_at(revisions: list[str], run: Git) -> dict[str, str] | Failure:
|
||||
"""todo.md's text at each revision, empty where the revision holds none."""
|
||||
plans = {}
|
||||
for revision in revisions:
|
||||
@@ -34,7 +34,7 @@ def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure:
|
||||
return plans
|
||||
|
||||
|
||||
def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure:
|
||||
def traces(changes: list[FixingChange], run: Git) -> list[Traced] | Failure:
|
||||
"""The commits traced_to traces for each change."""
|
||||
found = []
|
||||
for change in changes:
|
||||
@@ -45,7 +45,7 @@ def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure:
|
||||
return found
|
||||
|
||||
|
||||
def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure:
|
||||
def traced_to(before: str, tip: str, run: Git) -> 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")
|
||||
|
||||
@@ -18,7 +18,9 @@ merge merges the pull request, and only while its head is still the commit ch
|
||||
push after the gate is never merged. It takes the first method the repository allows of:
|
||||
a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash.
|
||||
GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the
|
||||
merge gate passed on that commit; without it, chunk-pr refuses.
|
||||
merge gate passed on that commit; without it, chunk-pr refuses. It also refuses where
|
||||
`larv-review scoring-run-owed` exits 1, because the chunk owes a scoring run it has not
|
||||
recorded; no flag waives that.
|
||||
clean acts once the forge reports the branch's pull request merged at the commit checked out,
|
||||
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
|
||||
default branch, removes the chunk's worktree, then deletes the local branch; origin's
|
||||
@@ -32,6 +34,7 @@ It prints what it did, exit 0, or why it failed, exit 1.
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
@@ -40,6 +43,7 @@ from chunk_preflight.gathered import Forge
|
||||
from chunk_preflight.choices import forge_of
|
||||
from deploy_release.forge import gitea, merged_pull, open_pull, Run, runner
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean"
|
||||
|
||||
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
|
||||
@@ -157,6 +161,9 @@ def merged(run: Run) -> str | Failure:
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, number, head = found
|
||||
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
|
||||
if isinstance(owed, Failure):
|
||||
return owed
|
||||
method = merge_method(forge, run)
|
||||
if isinstance(method, Failure):
|
||||
return method
|
||||
|
||||
@@ -21,6 +21,7 @@ GH_LIST = ["gh", "pr", "list", "--head", "item-7", "--json", "number,headRefOid,
|
||||
TEA_LIST = ["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]
|
||||
GH_SETTINGS = ["gh", "repo", "view", "--json", "mergeCommitAllowed,rebaseMergeAllowed,squashMergeAllowed"]
|
||||
TEA_SETTINGS = ["tea", "api", "repos/{owner}/{repo}"]
|
||||
OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scoring-run-owed"]
|
||||
|
||||
|
||||
class Checkout:
|
||||
@@ -58,7 +59,7 @@ class Checkout:
|
||||
|
||||
def acted(self) -> list[list[str]]:
|
||||
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
|
||||
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS]
|
||||
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED]
|
||||
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
|
||||
|
||||
|
||||
@@ -137,6 +138,14 @@ class Merge(unittest.TestCase):
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
|
||||
for origin in (GITHUB, GITEA):
|
||||
with self.subTest(origin=origin):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (merge).")
|
||||
|
||||
+9
-12
@@ -46,14 +46,11 @@ def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarde
|
||||
|
||||
|
||||
class Git(typing.Protocol):
|
||||
"""Runs git as `git` does."""
|
||||
"""Runs git as `git` does: git itself, Effects.git, or a functools.partial of either that binds the checkout."""
|
||||
|
||||
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")
|
||||
@@ -109,24 +106,24 @@ def origin_head(cwd: str | None, timeout: float | None, run: Git) -> str | Failu
|
||||
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
|
||||
|
||||
|
||||
def commits_since(tag: str | None, branch: str, cwd: str | None = None) -> int | Failure:
|
||||
def commits_since(tag: str | None, branch: str, cwd: str | None = None, run: Git = git) -> int | Failure:
|
||||
"""How many commits branch holds after tag, or holds in all where tag is None; read in cwd, else in the current directory."""
|
||||
count = git("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd)
|
||||
count = run("rev-list", "--count", f"{tag}..{branch}" if tag else branch, cwd=cwd)
|
||||
return count if isinstance(count, Failure) else int(count)
|
||||
|
||||
|
||||
def commit_exists(commit: str, cwd: str | None = None) -> bool:
|
||||
return not isinstance(git("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
|
||||
def commit_exists(commit: str, cwd: str | None = None, run: Git = git) -> bool:
|
||||
return not isinstance(run("rev-parse", "--quiet", "--verify", f"{commit}^{{commit}}", cwd=cwd), Failure)
|
||||
|
||||
|
||||
def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure:
|
||||
def file_at(revision: str, path: str, cwd: str | None = None, run: Git = git) -> 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):
|
||||
if not commit_exists(revision, cwd, run):
|
||||
return ""
|
||||
return text_at(revision, path, functools.partial(git, cwd=cwd))
|
||||
return text_at(revision, path, functools.partial(run, cwd=cwd))
|
||||
|
||||
|
||||
def text_at(revision: str, path: str, run: Run) -> str | Failure:
|
||||
def text_at(revision: str, path: str, run: Git) -> 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):
|
||||
|
||||
+1
-1
@@ -6,6 +6,6 @@ import sys
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from judge_replay import main
|
||||
from loop_claude.effects import system_effects
|
||||
from loop_effects.effects import system_effects
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
|
||||
|
||||
@@ -32,7 +32,7 @@ from rung_replay.command import arguments_or_exit, down_from, failed, limited_ex
|
||||
from loop_claude.cycle.judge import Brief, judge_once
|
||||
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
|
||||
from transcript_archive.project_key import checkout_of
|
||||
from loop_claude.effects import Effects
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.reply import Limited
|
||||
|
||||
@@ -11,7 +11,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
|
||||
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
|
||||
from loop_claude.effects import Effects
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from judge_replay import main
|
||||
|
||||
@@ -10,7 +10,7 @@ from larv_review.ruling import counted, overall, ruling, split, surplus, votes
|
||||
from failure import Failure
|
||||
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
|
||||
from larv_review.scoring import floor_step, means, under_floor
|
||||
from release_plan import ranking
|
||||
from release_plan import plan_file
|
||||
from records.file_writes import replace_file
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ def rerank() -> Failure | None:
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
todo = pathlib.Path(checkout, "todo.md")
|
||||
ranked = ranking.rank_file(todo)
|
||||
ranked = plan_file.rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
if ranked.under_bar:
|
||||
|
||||
+27
-5
@@ -1,8 +1,8 @@
|
||||
"""Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt.
|
||||
|
||||
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]
|
||||
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]
|
||||
|
||||
The comprehension check records how hard a project is to read, two ways, and blocks no merge. In a
|
||||
The comprehension check records how hard a project is to read, two ways, and no score blocks a merge. In a
|
||||
paired ruling, simulated readers, the seats, read the branch's head beside a base and vote better,
|
||||
same or worse, overall and on each dimension. In a scoring run, four seats score the project from 1
|
||||
to 10. Each seat names the places it found hard.
|
||||
@@ -11,7 +11,7 @@ Run it inside a project checkout or one of its worktrees. Each command but revie
|
||||
record-ruling, places and agreement first fetches origin, when the checkout has that remote, and
|
||||
takes origin's default branch, or else the local main or master, as the default branch. When the
|
||||
fetch fails, round-count and reviewer-header read origin as last fetched and say so on stderr; the
|
||||
other three exit 1.
|
||||
other four exit 1.
|
||||
The history is docs/comprehension-history.md in the checkout.
|
||||
|
||||
review-folder makes the chunk's review folder, where each reviewer writes its report, and prints its
|
||||
@@ -36,6 +36,18 @@ an item whose tagline names the comprehension floor. It is also due when the chu
|
||||
with no item in the checkout's todo.md, once the shipped items are set aside, and work has landed
|
||||
towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's
|
||||
todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none.
|
||||
A chunk is also due one while no scoring run in the default branch's history is newer than the
|
||||
commit of its second-newest v* tag, so a release cut unmeasured is caught up by the next chunk. A project whose
|
||||
docs/decisions.md opts out of the comprehension check is never due one.
|
||||
|
||||
scoring-run-owed prints `No scoring run owed.` or exits 1 naming the runs the chunk owes and has
|
||||
not recorded. chunk-pr merge runs it and refuses to merge on exit 1, so a due line read earlier in
|
||||
the chunk can't stand in for it. It applies needs-scoring-run's rule to the checkout's todo.md and the committed history, against the
|
||||
merge base with the default branch, so a default branch that has moved on adds nothing: the items
|
||||
the merge base's todo.md holds and the checkout's does not count as shipped. A chunk that empties a
|
||||
release owes two runs, any other due chunk one. The chunk has recorded the scoring runs that its
|
||||
committed docs/comprehension-history.md holds beyond the merge base's. A project that opts out or
|
||||
has no todo.md items table owes none.
|
||||
|
||||
A second scoring run of one head names itself `<PR or branch> rerun at <commit>`, so record-scoring
|
||||
does not refuse it as a repeat of the first.
|
||||
@@ -110,7 +122,7 @@ missing.
|
||||
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
|
||||
breaks the shape above, a todo.md that fails rank_todo.py after record-scoring records a run, or
|
||||
when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base,
|
||||
needs-scoring-run or record-scoring, or cannot read or write the history, todo.md or the review
|
||||
needs-scoring-run, scoring-run-owed or record-scoring, or cannot read or write the history, todo.md or the review
|
||||
folder.
|
||||
"""
|
||||
import pathlib
|
||||
@@ -126,12 +138,13 @@ from larv_review.history_changes import history_changes
|
||||
from review_rules.review_folder import made_review_folder
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.agreement import MIN_PAIRS
|
||||
from larv_review.owed import owed_scoring_run
|
||||
from review_rules.review_passes import PASSES, REVIEWERS
|
||||
from larv_review.plan import plan_reasons
|
||||
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
|
||||
from larv_review.reviewer_header import reviewer_header
|
||||
|
||||
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]"
|
||||
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -147,6 +160,8 @@ def main(argv: list[str]) -> int:
|
||||
done = with_default_branch(round_count, stale_ok=True)
|
||||
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
|
||||
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
|
||||
elif command == "scoring-run-owed" and not given:
|
||||
done = with_default_branch(owed, stale_ok=False)
|
||||
elif command == "record-ruling" and len(given) == 1:
|
||||
done = record_ruling(pathlib.Path(given[0]))
|
||||
elif command == "record-scoring" and given and all(re.fullmatch(r"[0-9]+", id_) for id_ in given[1:]):
|
||||
@@ -223,6 +238,13 @@ def cap_note(count: int, most: int) -> str:
|
||||
return f", {'at' if count == most else 'past'} the cap: no more rounds"
|
||||
|
||||
|
||||
def owed(default: str) -> Failure | None:
|
||||
unrecorded = owed_scoring_run(default)
|
||||
if unrecorded is None:
|
||||
print("No scoring run owed.")
|
||||
return unrecorded
|
||||
|
||||
|
||||
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
|
||||
reasons = plan_reasons(default, ids)
|
||||
if isinstance(reasons, Failure):
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import pathlib
|
||||
|
||||
from larv_review.plan import EMPTIED_WORDS, plan_reasons
|
||||
from review_rules.comprehension_history import entries, HISTORY
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git, top
|
||||
from release_plan.todo_table import items, NoItemsTable
|
||||
|
||||
|
||||
def owed_scoring_run(default: str) -> Failure | None:
|
||||
"""A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none.
|
||||
|
||||
The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began counts for nothing. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking.
|
||||
"""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
if not has_plan(checkout):
|
||||
return None
|
||||
base = git("merge-base", default, "HEAD", cwd=checkout)
|
||||
if isinstance(base, Failure):
|
||||
return base
|
||||
reasons = plan_reasons(base.strip(), None)
|
||||
if isinstance(reasons, Failure):
|
||||
return reasons
|
||||
if not reasons:
|
||||
return None
|
||||
before = file_at(base.strip(), HISTORY, checkout)
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
after = file_at("HEAD", HISTORY, checkout)
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
return shortfall(reasons, len(scoring_runs(after)) - len(scoring_runs(before)))
|
||||
|
||||
|
||||
def shortfall(reasons: list[str], recorded: int) -> Failure | None:
|
||||
"""Which scoring runs the plan's reasons call that recorded, the count the branch added to the history, leaves unrecorded; None where it holds them all."""
|
||||
needed = 2 if any(reason.endswith(EMPTIED_WORDS) for reason in reasons) else 1
|
||||
if recorded >= needed:
|
||||
return None
|
||||
return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}")
|
||||
|
||||
|
||||
def has_plan(checkout: str) -> bool:
|
||||
"""Whether the checkout has a todo.md holding an items table. A file that can't be read counts, so `plan_reasons` reports it."""
|
||||
try:
|
||||
return not isinstance(items(pathlib.Path(checkout, "todo.md").read_text(encoding="utf-8")), NoItemsTable)
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return True
|
||||
|
||||
|
||||
def scoring_runs(history: str) -> list[str]:
|
||||
return [entry.heading for entry in entries(history) if not entry.paired]
|
||||
+28
-10
@@ -2,28 +2,36 @@ import pathlib
|
||||
|
||||
from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, top
|
||||
from larv_review.scoring import FLOOR_ITEM
|
||||
from release_plan.todo_table import Item, items, NoItemsTable, renames
|
||||
from release_plan.ranking import OPTED_OUT
|
||||
from release_plan.release import Release, version
|
||||
from git_cli.git_repo import top
|
||||
from larv_review.unmeasured import unmeasured_cut
|
||||
|
||||
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release]) -> list[str] | Failure:
|
||||
# The words that end the reason a chunk empties a release. Such a chunk is due two scoring runs; a chunk with any other reason, one.
|
||||
EMPTIED_WORDS = "with no plan item"
|
||||
|
||||
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release], unmeasured: str | None = None) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not.
|
||||
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none.
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none. A chunk after a release `unmeasured_cut` names is due one too, so a release cut with no scoring run is caught up.
|
||||
|
||||
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed_release is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed.
|
||||
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed_release is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed. unmeasured is `unmeasured_cut`'s answer.
|
||||
"""
|
||||
plan = {item.id: item for item in before + after}
|
||||
if unknown := sorted(set(ships) - set(plan)):
|
||||
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
|
||||
shipped = [plan[id_] for id_ in ships]
|
||||
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if FLOOR_ITEM in item.tagline.lower()]
|
||||
if unmeasured:
|
||||
reasons.append(f"follows {unmeasured}")
|
||||
for release in emptied(before, after, shipped, renamed):
|
||||
if work_landed(release, shipped, landed_release):
|
||||
# SKILL.md → "Second run" keys on this wording.
|
||||
reasons.append(f"leaves release {version(release)} with no plan item")
|
||||
reasons.append(f"leaves release {version(release)} {EMPTIED_WORDS}")
|
||||
return reasons
|
||||
|
||||
|
||||
@@ -55,12 +63,17 @@ def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed:
|
||||
return sorted(named - {item.release for item in kept} - renamed)
|
||||
|
||||
|
||||
def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, from the default branch's todo.md and the checkout's."""
|
||||
def plan_reasons(ref: str, ids: list[int] | None) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, from todo.md at ref and the checkout's; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not."""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
held = default_plan(checkout, default)
|
||||
decisions = file_at(ref, "docs/decisions.md", checkout)
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
if OPTED_OUT.search(decisions):
|
||||
return []
|
||||
held = default_plan(checkout, ref)
|
||||
before = held.todo
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
@@ -73,14 +86,19 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
if isinstance(planned, NoItemsTable):
|
||||
planned = []
|
||||
if isinstance(planned, Failure):
|
||||
return Failure(f"{default}'s todo.md: {planned.reason}")
|
||||
return Failure(f"{ref}'s todo.md: {planned.reason}")
|
||||
renamed = renames(after)
|
||||
if isinstance(renamed, Failure):
|
||||
return Failure(f"the checkout's todo.md: {renamed.reason}")
|
||||
landed_release = landed_towards(planned, held.cut)
|
||||
if isinstance(landed_release, Failure):
|
||||
return landed_release
|
||||
return scoring_run_due(planned, chunk, ids, landed_release, renamed)
|
||||
unmeasured = unmeasured_cut(ref, checkout)
|
||||
if isinstance(unmeasured, Failure):
|
||||
return unmeasured
|
||||
if ids is None:
|
||||
ids = sorted({item.id for item in planned} - {item.id for item in chunk})
|
||||
return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
|
||||
|
||||
|
||||
def checkout_plan(checkout: str) -> tuple[str, list[Item]] | Failure:
|
||||
|
||||
@@ -12,7 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
|
||||
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
|
||||
from larv_review.plan import checkout_plan, landed_towards, plan_reasons, scoring_run_due
|
||||
from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
|
||||
from review_rules import comprehension_history
|
||||
from larv_review.ruling import counted, ruling, split, surplus, votes
|
||||
from larv_review.history_commands import decided
|
||||
@@ -23,6 +23,7 @@ from release_plan.todo_table import Item, items, NoItemsTable
|
||||
from release_plan.release_standing import LastCut
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.seats import score_line, scores, seats_file, SeatsFile
|
||||
from larv_review.owed import shortfall
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review"
|
||||
SCORING = "## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mean | 7.00 |\n"
|
||||
@@ -425,6 +426,20 @@ class LandedTowards(unittest.TestCase):
|
||||
self.assertEqual(landed_towards(plan, LastCut(Failure("fatal: bad object"), "", 3, [])), Failure("could not tell the next release: the default branch's tags cannot be read: fatal: bad object"))
|
||||
|
||||
|
||||
class Shortfall(unittest.TestCase):
|
||||
def test_skill_md_names_the_words_that_end_the_reason_a_release_empties(self):
|
||||
self.assertIn(EMPTIED_WORDS, (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8"))
|
||||
|
||||
def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self):
|
||||
emptied = ["leaves release 0.1.0 with no plan item"]
|
||||
floor = ["ships item 2, which names the comprehension floor"]
|
||||
self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason)
|
||||
self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason)
|
||||
self.assertIn("records 0:", shortfall(floor, -1).reason)
|
||||
self.assertIsNone(shortfall(emptied, 2))
|
||||
self.assertIsNone(shortfall(floor, 1))
|
||||
|
||||
|
||||
class LarvReviewTool(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
@@ -502,6 +517,128 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
self.assertIn("todo.md's ID column", self.run_tool("needs-scoring-run", "item-85").stderr)
|
||||
|
||||
def test_a_scoring_run_that_a_release_ending_chunk_owes_is_refused_until_the_branch_records_two(self):
|
||||
rest = ("| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
|
||||
self.commit("Ship item 1", {"todo.md": todo(*rest)})
|
||||
owed = self.run_tool("scoring-run-owed")
|
||||
self.assertEqual(owed.returncode, 1)
|
||||
self.assertIn("leaves release 0.1.0 with no plan item", owed.stderr)
|
||||
self.assertIn("records 0:", owed.stderr)
|
||||
history = "# Comprehension history\n\n" + SCORING
|
||||
self.commit("Record a run", {"docs/comprehension-history.md": history})
|
||||
self.assertIn("records 1:", self.run_tool("scoring-run-owed").stderr)
|
||||
self.commit("Record a rerun", {"docs/comprehension-history.md": history + "\n" + SCORING.replace("PR #1 at", "PR #1 rerun at")})
|
||||
done = self.run_tool("scoring-run-owed")
|
||||
self.assertEqual((done.returncode, done.stdout), (0, "No scoring run owed.\n"), done.stderr)
|
||||
|
||||
def test_a_scoring_run_the_floor_calls_is_owed_once(self):
|
||||
row = "| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
|
||||
other = "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
|
||||
self.commit("Plan the floor item", {"todo.md": todo(row, "| 2 | 0.2.0 | | **Reach the comprehension floor.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", other)})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.commit("Ship it", {"todo.md": todo(row, other)})
|
||||
self.assertIn("names the comprehension floor", self.run_tool("scoring-run-owed").stderr)
|
||||
self.commit("Record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 0)
|
||||
|
||||
ROW = "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
|
||||
|
||||
def ship_item_1(self):
|
||||
self.commit("Ship item 1", {"todo.md": todo(self.ROW)})
|
||||
|
||||
def test_no_scoring_run_is_owed_where_none_is_due(self):
|
||||
self.commit("Ship item 2", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", self.ROW)})
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
|
||||
self.ship_item_1()
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
|
||||
|
||||
def test_a_run_counts_only_as_committed_and_a_ruling_is_no_run(self):
|
||||
self.ship_item_1()
|
||||
(self.checkout / "docs").mkdir()
|
||||
(self.checkout / "docs" / "comprehension-history.md").write_text("# Comprehension history\n\n" + SCORING)
|
||||
self.assertIn("records 0", self.run_tool("scoring-run-owed").stderr)
|
||||
self.commit("Record a ruling", {"docs/comprehension-history.md": "# Comprehension history\n\n" + paired("2026-10-08T12:00:00Z", "better")})
|
||||
self.assertIn("records 0", self.run_tool("scoring-run-owed").stderr)
|
||||
|
||||
def test_a_project_that_opts_out_owes_none_and_is_never_due_one_but_a_branch_cannot_opt_itself_out(self):
|
||||
self.ship_item_1()
|
||||
self.commit("Opt out on the branch", {"docs/decisions.md": "## review opt-out: the comprehension check\n\n2026-11-10, lilleman.\n"})
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
|
||||
self.git("switch", "-q", "main")
|
||||
self.commit("Opt out", {"docs/decisions.md": "## review opt-out: the comprehension check\n\n2026-11-10, lilleman.\n"})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.git("switch", "-q", "chunk")
|
||||
self.git("merge", "-q", "main")
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_a_project_with_no_plan_or_no_items_table_owes_none(self):
|
||||
self.ship_item_1()
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
|
||||
self.commit("Reshape the plan", {"todo.md": "# Plan\n"})
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
|
||||
self.git("rm", "-q", "todo.md")
|
||||
self.commit("Drop the plan")
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
|
||||
(self.checkout / "todo.md").write_bytes(b"\xff\xfe")
|
||||
self.git("add", "todo.md")
|
||||
self.commit("Break the plan")
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1, "a plan that can't be read is no plan the gate may skip")
|
||||
|
||||
def test_a_default_branch_that_moved_on_since_the_branch_began_adds_no_owed_run(self):
|
||||
self.git("switch", "-q", "main")
|
||||
self.commit("Plan release 0.3.0", {"todo.md": todo("| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", self.ROW, "| 4 | 0.3.0 | | **Later.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"), "docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.git("switch", "-q", "chunk")
|
||||
self.commit("Do some work")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").stdout, "No scoring run owed.\n")
|
||||
self.ship_item_1()
|
||||
self.commit("Ship item 1 and record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING.replace("PR #1", "PR #7")})
|
||||
self.assertIn("owes 2 scoring runs and the branch's committed history records 1:", self.run_tool("scoring-run-owed").stderr, "main's own run is no credit to the branch")
|
||||
|
||||
def release(self, tag, date, files=None):
|
||||
"""Cut tag on the default branch at a commit dated date."""
|
||||
self.env["GIT_COMMITTER_DATE"] = date
|
||||
self.addCleanup(self.env.pop, "GIT_COMMITTER_DATE", None)
|
||||
self.commit(f"Release {tag}", files)
|
||||
self.git("tag", tag)
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
|
||||
def test_a_release_cut_with_no_scoring_run_since_the_one_before_it_calls_one_and_a_later_run_ends_that(self):
|
||||
self.release("v0.0.1", "2026-10-09T12:00:00Z")
|
||||
self.release("v0.0.2", "2026-10-20T12:00:00Z", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.1.\n")
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 1)
|
||||
self.commit("Record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING + "\n" + SCORING.replace("PR #1 at", "PR #2 at")})
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 0)
|
||||
self.release("v0.0.3", "2026-10-21T12:00:00Z", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING.replace("2026-10-08T12", "2026-10-20T18")})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_a_run_ends_an_unmeasured_release_only_when_it_is_a_scoring_run_newer_than_the_tag_with_a_time_that_reads(self):
|
||||
self.release("v0.0.1", "2026-10-09T12:00:00Z")
|
||||
history = "# Comprehension history\n\n"
|
||||
due = "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.1.\n"
|
||||
self.release("v0.0.2", "2026-10-20T12:00:00Z", {"docs/comprehension-history.md": history + paired("2026-10-21T12:00:00Z", "better") + "\n" + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-09T12:00:00Z")})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due, "a ruling, and a run at the earlier tag's own second, end nothing")
|
||||
self.release("v0.0.3", "2026-10-21T12:00:00Z", {"docs/comprehension-history.md": history + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-30")})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due.replace("v0.0.2", "v0.0.3").replace("v0.0.1", "v0.0.2"), "a run whose time doesn't parse ends nothing")
|
||||
|
||||
def test_an_unmeasured_release_is_judged_by_the_default_branch_alone_and_names_a_release_over_its_candidate(self):
|
||||
self.release("v0.0.1", "2026-10-09T12:00:00Z")
|
||||
self.release("v0.0.2-rc.1", "2026-10-10T12:00:00Z")
|
||||
self.release("v0.0.2", "2026-10-20T12:00:00Z")
|
||||
self.git("switch", "-q", "-c", "side")
|
||||
self.commit("Tag a side branch")
|
||||
self.git("tag", "v0.9.0")
|
||||
self.git("switch", "-q", "chunk")
|
||||
self.commit("Record a run on the branch", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING.replace("2026-10-08T12", "2026-10-25T12")})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.2-rc.1.\n")
|
||||
|
||||
def test_one_release_alone_calls_no_scoring_run_for_lacking_one(self):
|
||||
self.release("v0.0.1", "2026-10-09T12:00:00Z")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_calls_a_scoring_run_for_a_deferred_release_and_none_for_one_the_checkouts_plan_marks_renamed(self):
|
||||
rows = ("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
|
||||
self.commit("Move 0.1.0's item to 0.2.0", {"todo.md": todo(*rows)})
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import datetime
|
||||
|
||||
from review_rules.comprehension_history import entries, HISTORY
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git
|
||||
|
||||
|
||||
def unmeasured_cut(default: str, checkout: str) -> str | None | Failure:
|
||||
"""Whether the default branch's newest release was cut unmeasured, as `v0.7.0, cut with no scoring run since v0.6.0`. It was where no scoring run in the default branch's history is newer than the second-newest v* tag. None where the branch holds fewer than two such tags, or a run since the earlier one.
|
||||
|
||||
The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run.
|
||||
|
||||
A scoring run counts by the time its history heading records, against the tag's commit time; a heading whose time doesn't parse counts for nothing, so the run is asked for again.
|
||||
"""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0, as release.newest_tag does.
|
||||
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname", cwd=checkout)
|
||||
if isinstance(tags, Failure):
|
||||
return tags
|
||||
newest, earlier, *_ = [*tags.split(), None, None]
|
||||
if earlier is None:
|
||||
return None
|
||||
since = git("log", "-1", "--format=%ct", earlier, cwd=checkout)
|
||||
history = file_at(default, HISTORY, checkout)
|
||||
if isinstance(since, Failure) or isinstance(history, Failure):
|
||||
return since if isinstance(since, Failure) else history
|
||||
if any(at > int(since) for at in (seconds(entry.time) for entry in entries(history) if not entry.paired)):
|
||||
return None
|
||||
return f"{newest}, cut with no scoring run since {earlier}"
|
||||
|
||||
|
||||
def seconds(heading_time: str) -> float:
|
||||
"""A history heading's UTC time as seconds since the epoch; 0 where it doesn't parse."""
|
||||
try:
|
||||
return datetime.datetime.strptime(heading_time, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=datetime.timezone.utc).timestamp()
|
||||
except ValueError:
|
||||
return 0
|
||||
+2
-1
@@ -6,7 +6,8 @@ import sys
|
||||
LAUNCHER = pathlib.Path(__file__).resolve()
|
||||
sys.path.insert(0, str(LAUNCHER.parent))
|
||||
|
||||
from loop_claude import effects, paths
|
||||
from loop_effects import effects
|
||||
from loop_claude.loop import main
|
||||
from loop_state import paths
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home()), LAUNCHER, pathlib.Path.cwd(), effects.system_effects()))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""loop-claude: headless claude cycles, judged, that interrupt the human only for a decision that is theirs (loop/usage.py's help).
|
||||
|
||||
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, project/ reads a checkout's files, and waiting/ shows a question to loop-inbox. Each module at this level is imported by more than one package, and loop-inbox imports several. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
|
||||
Its packages hold one concern each: cycle/ runs a cycle, loop/ runs the cycles, and project/ reads a checkout's files. The files it shares with loop-inbox live in bin/loop_state/, and its effects in bin/loop_effects/. Each module at this level is imported by more than one package, or by a module at this level that is. A reader finds a module by its name, so the modules stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows that.
|
||||
"""
|
||||
|
||||
@@ -4,14 +4,14 @@ import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from loop_state.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed
|
||||
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_effects.effects import Effects, POLL_SECONDS, say
|
||||
from failure import Failure
|
||||
from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.waiting.listing import listed, shown
|
||||
from loop_claude.waiting.talk import make_way, TALK
|
||||
from loop_state.waiting.listing import listed, shown
|
||||
from loop_state.waiting.talk import make_way, TALK
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import typing
|
||||
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from loop_effects.effects import Effects
|
||||
from claude_code.entries import Entry, structured_output
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
|
||||
@@ -61,7 +61,7 @@ def review_launches(route: Route, project: Rung | None) -> list[str]:
|
||||
if project is None:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice, project)]
|
||||
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice)]
|
||||
|
||||
|
||||
def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
|
||||
@@ -74,13 +74,13 @@ def planning_launch(route: Route, project: Rung) -> list[str]:
|
||||
return [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 []
|
||||
|
||||
|
||||
def markdown_launch(choice: ReviewChoice, project: Rung) -> list[str]:
|
||||
"""Where the reviewers run above the project's rung, the sentence that a branch changing only Markdown no agent follows reviews on the project's rung, as rule-hook's reviewer-rung allows. On an Opus 5.5 project it ends: `launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium.`"""
|
||||
if position(choice.reviewers) <= position(project):
|
||||
def markdown_launch(choice: ReviewChoice) -> list[str]:
|
||||
"""The sentence that names choice.markdown_only, the rung a reviewer runs on where the branch changes only Markdown no agent follows. It is empty where that rung is the reviewers'. rule-hook's reviewer-rung holds a launch to the same rung. On an Opus 5.5 project it ends: `launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium.`"""
|
||||
if choice.markdown_only == choice.reviewers:
|
||||
return []
|
||||
files = ", ".join(f"`{name}`" for name in INSTRUCTION_FILES)
|
||||
folders = listed([f"`{folder}/`" for folder in INSTRUCTION_FOLDERS], "or")
|
||||
return [f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {project.agent_args()}."]
|
||||
return [f"Where your branch changes only Markdown, none of it {files} or under {folders}, launch {EACH_REVIEWER} on the project's rung instead, with the Agent tool set to {choice.markdown_only.agent_args()}."]
|
||||
|
||||
|
||||
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
@@ -7,7 +7,7 @@ from transcript_archive.write import archive
|
||||
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
from loop_claude.cycle.judge import Brief, judge, Rejected
|
||||
from claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_effects.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
|
||||
@@ -86,10 +86,15 @@ def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
|
||||
def archived_stop(project_archive: pathlib.Path, session: Session, task: str, route: Route, stop: Stop, why: str, effects: Effects) -> Stop:
|
||||
"""stop, once archived with the route the worker holds. A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once."""
|
||||
path = transcript_file(session)
|
||||
failure = archive(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects.now(), lambda text: say(text, effects)) if path else None
|
||||
failure = archived(project_archive, path, task, outcomes.stopped(route.worker_line(), why), effects) if path else None
|
||||
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
|
||||
|
||||
|
||||
def archived(project_archive: pathlib.Path, transcript_path: str, task: str, outcome: str, effects: Effects) -> Failure | None:
|
||||
"""transcript_archive.write.archive, stamped now and saying its notes through effects. A cycle and close.py, which has no Cycle, both archive through it."""
|
||||
return archive(project_archive, transcript_path, task, outcome, effects.now(), lambda text: say(text, effects))
|
||||
|
||||
|
||||
def judge_of(cycle: Cycle) -> Rung:
|
||||
"""The judge's rung, which the archive names beside each verdict."""
|
||||
return judge_rung(cycle.judge_model, cycle.route)
|
||||
@@ -157,13 +162,13 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
|
||||
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> str:
|
||||
"""The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from README.md or the records."""
|
||||
if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers):
|
||||
return outcomes.answered(ruling.question, prompts.QUOTE_SOURCES, ruling.answer, ruling.evidence, ruling.escalation, str(judge_of(cycle)), cycle.route.worker_line(), ruling.judge_cost)
|
||||
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judge_cost)
|
||||
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judge_cost)
|
||||
|
||||
|
||||
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
|
||||
"""Archives a judge reply loop-claude rejected, so the archive shows what the judge returned before a retry or an exit 1."""
|
||||
if unkept := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost), cycle.effects.now(), lambda text: say(text, cycle.effects)):
|
||||
if unkept := archived(cycle.project_archive, transcript_path, cycle.task, outcomes.rejected(rejected.reason, rejected.reply, str(judge_of(cycle)), rejected.cost), cycle.effects):
|
||||
return Stop(1, unkept.reason)
|
||||
return None
|
||||
|
||||
@@ -183,7 +188,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
|
||||
|
||||
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str, step_up: StepUp | None) -> Failure | None:
|
||||
"""Archives the outcome of a ruling, then the step-up it made, if it made one. The first failure is returned."""
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)):
|
||||
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
|
||||
return failure
|
||||
return archived_step(cycle.project_archive, transcript_path, cycle.task, step_up, cycle.effects)
|
||||
|
||||
@@ -192,7 +197,7 @@ def archived_step(project_archive: pathlib.Path, transcript_path: str, task: str
|
||||
"""Archives a step-up, if there is one, as the worker line it steps to. The outcome archived before it names the route the worker ran on until then, so the figures charge each stretch of work to its own rung. Both a ruling within a cycle and an unfinished verdict between cycles archive their step-up here."""
|
||||
if step_up is None:
|
||||
return None
|
||||
return archive(project_archive, transcript_path, task, outcomes.stepped_up(step_up.after.worker_line()), effects.now(), lambda text: say(text, effects))
|
||||
return archived(project_archive, transcript_path, task, outcomes.stepped_up(step_up.after.worker_line()), effects)
|
||||
|
||||
|
||||
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
@@ -203,7 +208,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
|
||||
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judge_cost) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judge_cost)
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)):
|
||||
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
|
||||
return Stop(1, failure.reason)
|
||||
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
|
||||
return Stop(1, failure.reason)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from claude_code.entries import AssistantTurn, ends_stream, entry_from, hit_limit, json_object, limit_said, rejected_until
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from claude_code.transcript import part_line
|
||||
|
||||
@@ -4,31 +4,32 @@ import typing
|
||||
|
||||
from release_plan.release_standing import default_plan, DefaultPlan
|
||||
from git_cli.git_repo import default_ref, file_at
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.routing import first_route, kept, routed_item
|
||||
from release_plan.todo_table import Item
|
||||
from transcript_archive.read import latest_worker
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_claude.cycle import prompts
|
||||
from model_routing.route import Route, route_from
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import Session, session_open, transcript_file
|
||||
from loop_claude.running_loops import Show, taken_items
|
||||
from claude_code.session import session_open, transcript_file
|
||||
from loop_state.running_loops import 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
|
||||
|
||||
|
||||
def shown_items(show: Show, root: str, routed: int) -> typing.Callable[[tuple[int, ...]], None]:
|
||||
def shown_items(loop: Loop, 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))
|
||||
todo = fetched_todo(loop)
|
||||
return lambda taken_in: loop.listed.show(taken_items(todo, routed, taken_in))
|
||||
|
||||
|
||||
def fetched_todo(root: str) -> str | Failure:
|
||||
def fetched_todo(loop: Loop) -> 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)
|
||||
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
|
||||
return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", loop.root, loop.effects.git)
|
||||
|
||||
|
||||
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
@@ -42,37 +43,37 @@ def routed(route: Route | None, project: Rung | None, model: str, archived: typi
|
||||
return route if route and kept(route, project) else first_route(project, item())
|
||||
|
||||
|
||||
def archived_route(archive_folder: pathlib.Path, session: Session, effects: Effects) -> Route | None:
|
||||
"""The route the latest verdict archived for the session's open chunk names; None for a chunk not yet judged."""
|
||||
transcript = transcript_file(session)
|
||||
def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
|
||||
"""The route named by the latest verdict archived for the loop's open chunk; None for a chunk not yet judged."""
|
||||
transcript = transcript_file(loop.session)
|
||||
worker = latest_worker(archive_folder, transcript) if transcript else None
|
||||
if isinstance(worker, Failure):
|
||||
say(f"routing the chunk afresh: {worker.reason}", effects)
|
||||
say(f"routing the chunk afresh: {worker.reason}", loop.effects)
|
||||
return None
|
||||
route = route_from(worker) if worker else None
|
||||
if worker and route is None:
|
||||
say(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", effects)
|
||||
say(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", loop.effects)
|
||||
return route
|
||||
|
||||
|
||||
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
|
||||
facts = "" if session_open(session) else chunk_facts(preflight, root, effects)
|
||||
return facts, lambda: plan_item(fetched_plan(root), effects)
|
||||
facts = "" if session_open(loop.session) else chunk_facts(loop)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), loop.effects)
|
||||
|
||||
|
||||
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
|
||||
def chunk_facts(loop: Loop) -> str:
|
||||
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
|
||||
done = effects.python([str(preflight), "--worktree"], root)
|
||||
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree"], loop.root)
|
||||
if done.returncode:
|
||||
return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}")
|
||||
return prompts.preflight_facts(done.stdout.strip())
|
||||
|
||||
|
||||
def fetched_plan(root: str) -> DefaultPlan | Failure:
|
||||
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
"""What the default branch, as last fetched, holds for routing."""
|
||||
ref = default_ref(root, ORIGIN_TIMEOUT)
|
||||
return ref if isinstance(ref, Failure) else default_plan(root, ref)
|
||||
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
|
||||
return ref if isinstance(ref, Failure) else default_plan(loop.root, ref, loop.effects.git)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
|
||||
|
||||
@@ -3,31 +3,31 @@ import dataclasses
|
||||
import pathlib
|
||||
|
||||
from loop_claude.cycle.run import archived_step, archived_stop, Concluded
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.verdicts import Finished
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_claude.stop import needs_human, Stop
|
||||
from loop_claude.routing import next_route, step_up
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import Session, transcript_file
|
||||
from claude_code.session import transcript_file
|
||||
|
||||
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
|
||||
UNFINISHED_LIMIT = 6
|
||||
|
||||
|
||||
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, session: Session, effects: Effects) -> LoopRun | Stop:
|
||||
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop:
|
||||
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
|
||||
after = after_verdict(loop_run, project, concluded)
|
||||
# A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts.
|
||||
if after.route is None:
|
||||
return after
|
||||
# The unfinished verdict, archived as the cycle closed, names the route its cycle ended on; the step-up names the one the next cycle runs on.
|
||||
path = transcript_file(session)
|
||||
if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), effects)):
|
||||
path = transcript_file(loop.session)
|
||||
if path and (failure := archived_step(archive_folder, path, after.task, step_up(concluded.route, after.route), loop.effects)):
|
||||
return Stop(1, failure.reason)
|
||||
if limit := reached_limit(after):
|
||||
# Archived with the route the next cycle would run on, so a rerun resumes there.
|
||||
return archived_stop(archive_folder, session, after.task, after.route, limit, limit.reason, effects)
|
||||
return archived_stop(archive_folder, loop.session, after.task, after.route, limit, limit.reason, loop.effects)
|
||||
return after
|
||||
|
||||
|
||||
|
||||
@@ -9,17 +9,18 @@ from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.loop.close import closed_cycle
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from loop_claude.loop.usage import HELP
|
||||
from loop_claude.running_loops import Listed, shown_running
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from model_routing.ladder import project_rung
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.session import Session, session_named
|
||||
from claude_code.session import session_named
|
||||
from loop_state.running_loops import shown_running
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
@@ -42,45 +43,46 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts)
|
||||
with shown_running(paths.waiting, str(session.id), loop_run.root, effects) as listed:
|
||||
loop = Loop(root=loop_run.root, session=session, listed=listed, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
while True:
|
||||
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||
if stop := exec_if_edited(loop, baseline, loop_run):
|
||||
return stop
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
cycle = next_cycle(loop_run, session, listed, paths, env, launcher, effects)
|
||||
cycle = next_cycle(loop_run, loop)
|
||||
if isinstance(cycle, Stop):
|
||||
return cycle
|
||||
concluded = run_cycle(cycle)
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, session, effects)
|
||||
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
# Off the ladder the worker runs on the project's model itself, which its route names.
|
||||
if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), cycle.project or cycle.route.rung, paths, listed.folder, effects):
|
||||
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
|
||||
return stop
|
||||
|
||||
|
||||
def next_cycle(loop_run: LoopRun, session: Session, listed: Listed, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> Cycle | Stop:
|
||||
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
"""The cycle loop_run runs next, from the premises, the records and the project's models read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
|
||||
premises = read_premises(loop_run.root)
|
||||
premises = read_premises(loop.root)
|
||||
if isinstance(premises, Failure):
|
||||
return Stop(1, premises.reason)
|
||||
records = read_records(loop_run.root, paths.claude_dir)
|
||||
records = read_records(loop.root, loop.paths.claude_dir)
|
||||
if isinstance(records, Failure):
|
||||
return Stop(1, records.reason)
|
||||
models = get_or_ask_models(project_key(loop_run.root, paths.home), paths, env, effects)
|
||||
models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, loop.effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
archive_folder = project_archive(loop_run.root, paths.home, env)
|
||||
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
|
||||
# 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)
|
||||
facts, item = chunk_start(loop)
|
||||
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)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), item)
|
||||
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
|
||||
show_taken_in = shown_items(loop, route.item)
|
||||
show_taken_in(loop_run.items_taken_in)
|
||||
return Cycle(effects=effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=listed.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)
|
||||
return Cycle(effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
|
||||
|
||||
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
|
||||
|
||||
@@ -5,9 +5,9 @@ import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from model_routing.route import Route, route_of
|
||||
from loop_effects.effects import say
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
@@ -67,23 +67,20 @@ def decoded_ids(value: object) -> tuple[int, ...]:
|
||||
return tuple(exactly(int)(each) for each in value)
|
||||
|
||||
|
||||
def decoded_rung(value: object) -> Rung:
|
||||
return Rung(**decoded_fields(value, {"model": exactly(str), "effort": exactly(str)}, "model"))
|
||||
|
||||
|
||||
def decoded_route(value: object) -> Route | None:
|
||||
"""The Route the JSON holds; None for null, or for a route holding a key Route.RETIRED names, so the chunk routes afresh."""
|
||||
if value is None or (isinstance(value, dict) and value.keys() & Route.RETIRED):
|
||||
"""The Route the JSON holds; None for null. dataclasses.asdict wrote it as a worker line's fields, with the rung nested and the unfinished count added. route_of reads it once the rung's model and effort are lifted to the top and the count is set aside."""
|
||||
if value is None:
|
||||
return None
|
||||
fields = decoded_fields(value, ROUTE_FIELDS, "rung")
|
||||
if not Route.fits(fields):
|
||||
if not isinstance(value, dict) or not isinstance(value.get("rung"), dict) or not value["rung"].keys() <= {"model", "effort"} or value.keys() & {"model", "effort"}:
|
||||
raise Unreadable
|
||||
return Route(**fields)
|
||||
route = route_of({**{name: field for name, field in value.items() if name not in ("rung", "unfinished")}, **value["rung"]})
|
||||
if route is None:
|
||||
raise Unreadable
|
||||
return dataclasses.replace(route, unfinished=exactly(int)(value.get("unfinished", 0)))
|
||||
|
||||
|
||||
# One decoder per field of LoopRun and of Route, which tests hold to those dataclasses' fields: a field missing here stops a loop at the reload after it joined.
|
||||
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
|
||||
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "items_taken_in": decoded_ids}
|
||||
ROUTE_FIELDS = {"rung": decoded_rung, **{name: exactly(int) for name in ("item", "likelihood", "escape_and_impact", "unfinished", "escape_and_impact_taken_in", "escalated_at")}}
|
||||
|
||||
|
||||
def fingerprint(launcher: pathlib.Path) -> str:
|
||||
@@ -98,15 +95,15 @@ def fingerprint(launcher: pathlib.Path) -> str:
|
||||
|
||||
|
||||
# A loop runs unattended for hours, often on its own checkout: reloading puts each edit to loop-claude to use without the human rerunning it.
|
||||
def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, effects: Effects) -> Stop | None:
|
||||
if fingerprint(launcher) == baseline:
|
||||
def exec_if_edited(loop: Loop, baseline: str, loop_run: LoopRun) -> Stop | None:
|
||||
if fingerprint(loop.launcher) == baseline:
|
||||
return None
|
||||
trial = effects.python([str(launcher), "--help"], loop_run.root)
|
||||
trial = loop.effects.python([str(loop.launcher), "--help"], loop.root)
|
||||
if trial.returncode != 0:
|
||||
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", effects)
|
||||
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", loop.effects)
|
||||
return None
|
||||
try:
|
||||
effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
|
||||
loop.effects.execv(sys.executable, [sys.executable, str(loop.launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
|
||||
except OSError as failure:
|
||||
return Stop(1, f"could not reload loop-claude: {failure.strerror}; rerun loop-claude <task>")
|
||||
return None
|
||||
|
||||
@@ -2,13 +2,14 @@
|
||||
import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from loop_claude.waiting.ask import Ask, OpenOnTerminal
|
||||
from loop_state.waiting.ask import Ask, OpenOnTerminal
|
||||
from routing_figures.calls import Call, calls, totals
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.waiting.listing import listed
|
||||
from loop_claude.paths import Paths
|
||||
from loop_state.waiting.listing import listed
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
from routing_figures.render import render
|
||||
from model_routing.ladder import Rung
|
||||
from routing_figures import state
|
||||
@@ -16,14 +17,14 @@ from loop_claude.stop import Stop
|
||||
from records.utc_stamp import utc
|
||||
|
||||
|
||||
def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, questions: pathlib.Path, 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."""
|
||||
def check_routing(root: pathlib.Path, rung: Rung, loop: Loop) -> 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. root is the archive's, 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 []
|
||||
new = new_calls(root, loop.paths, loop.effects) if held else []
|
||||
if isinstance(new, Failure):
|
||||
say(f"routing figures: {new.reason}", effects)
|
||||
say(f"routing figures: {new.reason}", loop.effects)
|
||||
return None
|
||||
return raise_calls(root, checkout, session, new, rung, paths, questions, effects) if new else None
|
||||
return raise_calls(root, new, rung, loop) if new else None
|
||||
|
||||
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure:
|
||||
@@ -48,21 +49,21 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
|
||||
return [call for call in found if call not in raised.calls]
|
||||
|
||||
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[Call], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None:
|
||||
def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
bullets = "".join(f"- {call.sentence()}\n" for call in new)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
|
||||
say(f"\n{question}", effects)
|
||||
if not effects.on_terminal():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
say(f"\n{question}", loop.effects)
|
||||
if not loop.effects.on_terminal():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", loop.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{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 in this checkout, the development clone, 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(questions, ask, effects):
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.config_clone), {}), effects)
|
||||
ask = Ask(loop.effects.new_id(), str(loop.session.id), loop.root, question, loop.effects.now(), OpenOnTerminal())
|
||||
with listed(loop.listed.folder, ask, loop.effects):
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls in {paths.config_clone}, the setup's development clone: {unstarted.reason}")
|
||||
return Stop(1, f"could not start claude for the routing calls in {loop.paths.config_clone}, the setup's development clone: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := state.mark_raised(root, new, utc(effects.now())):
|
||||
say(f"routing figures: {unmarked.reason}", effects)
|
||||
if unmarked := state.mark_raised(root, new, utc(loop.effects.now())):
|
||||
say(f"routing figures: {unmarked.reason}", loop.effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_effects.effects import Effects
|
||||
from loop_state.running_loops import Listed
|
||||
from loop_state.paths import Paths
|
||||
from claude_code.session import Session
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Loop:
|
||||
"""What stays the same through one run of loop-claude; run_loop builds it once per process, so a reload builds it afresh."""
|
||||
# The checkout the loop runs in. LoopRun.root names it too, since a reload hands it on there.
|
||||
root: str
|
||||
# The worker's session, under whose id loop-inbox lists the loop and its questions.
|
||||
session: Session
|
||||
listed: Listed
|
||||
paths: Paths
|
||||
env: typing.Mapping[str, str]
|
||||
# The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies.
|
||||
launcher: pathlib.Path
|
||||
effects: Effects
|
||||
@@ -35,7 +35,7 @@ A release ready to cut opens that session on the terminal at once, since only th
|
||||
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
||||
as bin/loop_claude/running_loops.py describes.
|
||||
as bin/loop_state/running_loops.py describes.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
||||
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
||||
|
||||
@@ -2,7 +2,7 @@ import pathlib
|
||||
|
||||
from failure import Failure
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_effects.effects import Effects
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
|
||||
|
||||
@@ -5,10 +5,10 @@ import sys
|
||||
import typing
|
||||
|
||||
from claude_code.model_catalog import catalog_models
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from loop_state.paths import Paths
|
||||
from records.file_writes import replace_json
|
||||
|
||||
|
||||
|
||||
+38
-14
@@ -4,7 +4,7 @@ The worker, and the session /talk opens, run on a Route (model_routing/route.py)
|
||||
|
||||
- Start. routed_item finds the plan item that routes a fresh chunk, if there is one with L, E and I scored; first_route picks the worker's rung from its L, or the project's rung without an item.
|
||||
- Rerun. kept decides whether a rerun resumes the route its archive last names.
|
||||
- Step-up. next_route raises the route after an unfinished verdict, or an interrupt or a quoted answer that carries an escalation; escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule. step_up names the change where it changes the worker line, which the archive records.
|
||||
- Step-up. next_route raises the route after an unfinished verdict (unfinished_route), or an interrupt or a quoted answer that carries an escalation (escalated_route); escalation_cap bounds an escalation, and loop_claude/escalation_mark.py states the escalation mark's rule. step_up names the change where it changes the worker line, which the archive records.
|
||||
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
|
||||
"""
|
||||
import dataclasses
|
||||
@@ -82,25 +82,49 @@ class StepUp:
|
||||
|
||||
|
||||
def next_route(project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route:
|
||||
"""The route the worker runs on after the judge's verdict. Off the ladder, project is None, and the route holds.
|
||||
|
||||
The rung never falls. It first rises to floor_rung, which the verdict's highest L taken in may raise. From there it steps one rung up on an escalation while below escalation_cap, and moves the mark, as loop_claude/escalation_mark.py says.
|
||||
An unfinished verdict also counts towards UNFINISHED_PER_STEP, and the second such verdict steps the rung once, keeping the mark; where both fall on one verdict, it steps once. Last, it takes in the verdict's highest E + I, as Route.taking_in does.
|
||||
An interrupt or a quoted answer without an escalation leaves the route as it is, since neither is an unfinished verdict.
|
||||
"""
|
||||
"""The route the worker runs on after the judge's verdict. Off the ladder, project is None, and the route holds. The rung never falls."""
|
||||
if project is None:
|
||||
return route
|
||||
if isinstance(verdict, Unfinished):
|
||||
return unfinished_route(project, route, verdict)
|
||||
return escalated_route(project, route, verdict)
|
||||
|
||||
|
||||
def unfinished_route(project: Rung, route: Route, verdict: Unfinished) -> Route:
|
||||
"""The route after an unfinished verdict. The rung rises to floor_rung, which the verdict's highest L taken in may raise.
|
||||
|
||||
The verdict counts towards UNFINISHED_PER_STEP. Where steps says so, the rung steps once from the floor, and the mark moves only where the verdict escalates. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
|
||||
"""
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
|
||||
escalated_at = route.escalated_at if mark is None else mark
|
||||
escalates = mark is not None and position(floor) < position(escalation_cap(project, route))
|
||||
if isinstance(verdict, Unfinished):
|
||||
counted = route.unfinished + 1
|
||||
after = one_rung_up(route, floor, escalated_at) if counted >= UNFINISHED_PER_STEP or escalates else dataclasses.replace(route, rung=floor, unfinished=counted)
|
||||
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
|
||||
counted = route.unfinished + 1
|
||||
if steps(counted, mark is not None and below_cap(project, route, floor)):
|
||||
after = one_rung_up(route, floor, route.escalated_at if mark is None else mark)
|
||||
else:
|
||||
after = dataclasses.replace(route, rung=floor, unfinished=counted)
|
||||
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
|
||||
|
||||
|
||||
def escalated_route(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
|
||||
"""The route after an interrupt or a quoted answer. Without an escalation it holds, since neither is an unfinished verdict.
|
||||
|
||||
With one, the rung rises to floor_rung, which the verdict's highest L taken in may raise. Where floor_rung lies below escalation_cap, the rung steps one up from it and the mark moves, as loop_claude/escalation_mark.py says; at the cap the rung stays on floor_rung and the mark holds.
|
||||
"""
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if mark is None:
|
||||
return route
|
||||
return one_rung_up(route, floor, escalated_at) if escalates else dataclasses.replace(route, rung=floor)
|
||||
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
|
||||
return one_rung_up(route, floor, mark) if below_cap(project, route, floor) else dataclasses.replace(route, rung=floor)
|
||||
|
||||
|
||||
def steps(counted: int, escalates: bool) -> bool:
|
||||
"""Whether an unfinished verdict steps the rung: it is the UNFINISHED_PER_STEP-th since the last step, or it escalates below escalation_cap. Where both hold, the rung still steps once."""
|
||||
return counted >= UNFINISHED_PER_STEP or escalates
|
||||
|
||||
|
||||
def below_cap(project: Rung, route: Route, floor: Rung) -> bool:
|
||||
"""Whether an escalation from floor may step the rung: floor lies below escalation_cap."""
|
||||
return position(floor) < position(escalation_cap(project, route))
|
||||
|
||||
|
||||
def step_up(before: Route, after: Route) -> StepUp | None:
|
||||
|
||||
@@ -18,9 +18,9 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from loop_claude.waiting.answers import send, Typed
|
||||
from loop_claude import session_lock
|
||||
from loop_claude.waiting.listing import waiting
|
||||
from loop_state.waiting.answers import send, Typed
|
||||
from loop_state import session_lock
|
||||
from loop_state.waiting.listing import waiting
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
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
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import uuid
|
||||
@@ -20,31 +17,32 @@ import uuid
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from routing_figures import archive, state
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from routing_figures.calls import Call
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from loop_claude.loop import chunk_start, close
|
||||
from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed
|
||||
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send, Typed
|
||||
from release_plan.release_standing import DefaultPlan, LastCut
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from loop_effects.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT
|
||||
from claude_code import entries, reply, session
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished
|
||||
from loop_claude import hand_over, paths, routing, running_loops, session_lock
|
||||
from loop_state import hand_over, paths, running_loops, session_lock
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.loop import main, reload, routing_check, usage
|
||||
from loop_claude.waiting.talk import make_way
|
||||
from loop_claude.loop import main, reload, routing_check, this_loop, usage
|
||||
from loop_state.waiting.talk import make_way
|
||||
from machine_load import memory
|
||||
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 import routing
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.running_loops import Taken
|
||||
from loop_state.running_loops import Taken
|
||||
from records.utc_stamp import utc
|
||||
from loop_claude.cycle.judge import verdict_from
|
||||
from loop_claude.waiting.listing import waiting
|
||||
from loop_state.waiting.listing import waiting
|
||||
|
||||
# How the archive records a worker that runs off the ladder.
|
||||
OFF_LADDER = '{"model": "worker-model"}'
|
||||
@@ -82,6 +80,13 @@ def asks_and_answers(folder):
|
||||
return [path for path in sorted(folder.iterdir()) if path.suffix != ".lock"]
|
||||
|
||||
|
||||
def a_loop(effects, **fields):
|
||||
"""A loop in /r on effects, with fields in place of its defaults."""
|
||||
home = pathlib.Path("/h")
|
||||
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "listed": running_loops.Listed(home / "waiting", lambda items: None), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude")}
|
||||
return this_loop.Loop(**{**defaults, **fields}, effects=effects)
|
||||
|
||||
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
@@ -637,39 +642,6 @@ class Retried(unittest.TestCase):
|
||||
self.assertEqual(said.getvalue(), f"{STAMP} the judge hit a usage limit (You've hit your session limit); retrying at <{NOW + 3720}>\n")
|
||||
|
||||
|
||||
class Said(unittest.TestCase):
|
||||
def test_opens_a_line_with_the_local_time_of_the_effects_clock(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
|
||||
say("hello", FakeEffects().effects())
|
||||
self.assertEqual((stderr.getvalue(), stdout.getvalue()), (f"{STAMP} hello\n", ""))
|
||||
|
||||
def test_stamps_only_the_first_line_of_a_question_after_its_blank_line(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
say("\nWhich one?\n\nA or B?", FakeEffects().effects())
|
||||
self.assertEqual(stderr.getvalue(), f"\n{STAMP} Which one?\n\nA or B?\n")
|
||||
|
||||
def test_says_on_stdout_where_asked(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
|
||||
say("\n=== cycle 2 ===", FakeEffects().effects(), stdout=True)
|
||||
self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n"))
|
||||
|
||||
def test_keeps_the_indent_of_the_first_line_after_the_time(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
say("\n indented", FakeEffects().effects())
|
||||
self.assertEqual(stderr.getvalue(), f"\n{STAMP} indented\n")
|
||||
|
||||
def test_flushes_so_piped_lines_arrive_when_said(self):
|
||||
flushes = []
|
||||
|
||||
class Counting(io.StringIO):
|
||||
def flush(self):
|
||||
flushes.append(self.getvalue())
|
||||
|
||||
with contextlib.redirect_stderr(Counting()):
|
||||
say("hello", FakeEffects().effects())
|
||||
self.assertEqual(flushes, [f"{STAMP} hello\n"])
|
||||
|
||||
|
||||
class Limits(unittest.TestCase):
|
||||
def test_the_worker_reports_the_latest_reset_its_stream_names(self):
|
||||
rejected = [{"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": resets_at}} for resets_at in (NOW + 60, NOW + 600)]
|
||||
@@ -869,6 +841,11 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.addCleanup(shutil.rmtree, self.home)
|
||||
self.root = self.home / "archive"
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.session = session.session_named("A log loop-claude", self.paths.claude_code_transcripts)
|
||||
|
||||
def loop(self, fake):
|
||||
"""The loop in /code/log, whose questions loop-inbox lists."""
|
||||
return a_loop(fake.effects(), root="/code/log", session=self.session, listed=running_loops.Listed(self.paths.waiting, lambda items: None), paths=self.paths)
|
||||
|
||||
def chunks(self, count, verdicts, project="log"):
|
||||
"""count finished chunks, each closed by verdicts verdicts, each with one Explore subagent whose report outgrew its searches."""
|
||||
@@ -887,15 +864,15 @@ class RoutingCheck(unittest.TestCase):
|
||||
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:
|
||||
self.enterContext(session_lock.held(self.paths.waiting, "s1"))
|
||||
stop = routing_check.check_routing(self.root, "/code/log", "s1", Rung("m", "high"), self.paths, self.paths.waiting, fake.effects())
|
||||
self.enterContext(session_lock.held(self.paths.waiting, str(self.session.id)))
|
||||
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.loop(fake))
|
||||
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(self.paths.waiting), [Ask(ASK_ID, "s1", "/code/log", question, NOW, OpenOnTerminal())])
|
||||
self.assertEqual(waiting(self.paths.waiting), [Ask(ASK_ID, str(self.session.id), "/code/log", question, NOW, OpenOnTerminal())])
|
||||
return 0
|
||||
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD]))
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
@@ -980,7 +957,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
new = [Call("reports", ("Explore",)), Call("rounds", ("x", "y"))]
|
||||
fake = FakeEffects(on_terminal_claude=[0])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")):
|
||||
self.assertIsNone(routing_check.raise_calls(self.root, "/code/log", "s1", new, Rung("m", "high"), self.paths, self.paths.waiting, fake.effects()))
|
||||
self.assertIsNone(routing_check.raise_calls(self.root, new, Rung("m", "high"), self.loop(fake)))
|
||||
((args),) = fake.made("claude_on_terminal")
|
||||
self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
|
||||
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue())
|
||||
@@ -1211,25 +1188,25 @@ class RouteSources(unittest.TestCase):
|
||||
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsNone(chunk_start.archived_route(archive, opened, FakeEffects().effects()))
|
||||
self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
|
||||
self.assertIsNone(chunk_start.archived_route(archive, opened, FakeEffects().effects()))
|
||||
self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.worker_line(), "working", "j", ""), NOW))
|
||||
with contextlib.redirect_stderr(stderr):
|
||||
self.assertEqual(chunk_start.archived_route(archive, opened, FakeEffects().effects()), route)
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), route)
|
||||
self.assertEqual(stderr.getvalue(), "")
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.stepped_up(WorkerLine('{"model": "claude-opus-5-5", "rung": 3}')), NOW + 1))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsNone(chunk_start.archived_route(archive, opened, FakeEffects().effects()))
|
||||
self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
self.assertEqual(stderr.getvalue(), f'{STAMP} routing the chunk afresh: the archive\'s latest Worker: line names no route loop-claude can read: {{"model": "claude-opus-5-5", "rung": 3}}\n')
|
||||
(chunk,) = archive.iterdir()
|
||||
chunk.chmod(0)
|
||||
try:
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsNone(chunk_start.archived_route(archive, opened, FakeEffects().effects()))
|
||||
self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
finally:
|
||||
chunk.chmod(0o700)
|
||||
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
|
||||
@@ -1274,14 +1251,14 @@ 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 = close.closed_cycle(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), archive, opened, FakeEffects().effects())
|
||||
self.assertEqual(chunk_start.archived_route(archive, opened, FakeEffects().effects()), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
after = close.closed_cycle(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), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
close.closed_cycle(after, self.OPUS, run.Concluded(Finished("done"), after.route), archive, opened, FakeEffects().effects())
|
||||
self.assertEqual(chunk_start.archived_route(archive, opened, FakeEffects().effects()), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
close.closed_cycle(after, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
blocked = pathlib.Path(home, "blocked")
|
||||
blocked.write_text("")
|
||||
stop = close.closed_cycle(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), blocked, opened, FakeEffects().effects())
|
||||
stop = close.closed_cycle(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), blocked, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript"))
|
||||
|
||||
def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self):
|
||||
@@ -1299,8 +1276,8 @@ 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))
|
||||
close.closed_cycle(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), archive, opened, FakeEffects().effects())
|
||||
self.assertEqual(chunk_start.archived_route(archive, opened, FakeEffects().effects()), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
|
||||
close.closed_cycle(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), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
|
||||
|
||||
|
||||
class ChunkFacts(unittest.TestCase):
|
||||
@@ -1310,11 +1287,12 @@ class ChunkFacts(unittest.TestCase):
|
||||
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")
|
||||
# The launcher beside which chunk_start finds /b/chunk-preflight.
|
||||
LAUNCHER = pathlib.Path("/b/loop-claude")
|
||||
|
||||
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
|
||||
fake = FakeEffects(python=[ran("- A fact.\n")])
|
||||
said = chunk_start.chunk_facts(self.PREFLIGHT, "/r", fake.effects())
|
||||
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
|
||||
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
|
||||
self.assertIn("\n\n- A fact.", said)
|
||||
self.assertNotIn("yourself", said)
|
||||
@@ -1322,7 +1300,7 @@ class ChunkFacts(unittest.TestCase):
|
||||
def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self):
|
||||
for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")):
|
||||
with self.subTest(why=why):
|
||||
said = chunk_start.chunk_facts(self.PREFLIGHT, "/r", FakeEffects(python=[failed]).effects())
|
||||
said = chunk_start.chunk_facts(a_loop(FakeEffects(python=[failed]).effects(), launcher=self.LAUNCHER))
|
||||
self.assertIn("yourself", said)
|
||||
self.assertIn(why, said)
|
||||
|
||||
@@ -1330,100 +1308,16 @@ class ChunkFacts(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
|
||||
fresh = FakeEffects(python=[ran("- A fact.\n")])
|
||||
facts, _ = chunk_start.chunk_start(opened, self.PREFLIGHT, "/r", fresh.effects())
|
||||
facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER))
|
||||
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree"], "/r")], True))
|
||||
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text("")
|
||||
resumed = FakeEffects()
|
||||
facts, _ = chunk_start.chunk_start(opened, self.PREFLIGHT, "/r", resumed.effects())
|
||||
facts, _ = chunk_start.chunk_start(a_loop(resumed.effects(), session=opened, launcher=self.LAUNCHER))
|
||||
self.assertEqual((resumed.made("python"), facts), ([], ""))
|
||||
|
||||
|
||||
class LocalTime(unittest.TestCase):
|
||||
def test_renders_seconds_in_the_machines_zone(self):
|
||||
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
|
||||
self.addCleanup(time.tzset)
|
||||
zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"})
|
||||
zone.start()
|
||||
self.addCleanup(zone.stop)
|
||||
time.tzset()
|
||||
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:
|
||||
self.assertEqual(run_python(["-c", "import os; print(os.getcwd())"], cwd, 60).stdout.strip(), os.path.realpath(cwd))
|
||||
|
||||
def test_stops_a_script_still_running_after_the_timeout_and_reads_it_as_exit_1(self):
|
||||
done = run_python(["-c", "import threading; threading.Event().wait()"], "/", 0.5)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn("0.5 s", done.stderr)
|
||||
|
||||
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
self.assertEqual(run_python(["-c", "import sys; sys.stdout.buffer.write(b'caf\\xe9')"], cwd, 60).stdout, "caf�")
|
||||
|
||||
def test_reads_a_script_that_cannot_start_as_exit_1_saying_why(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
gone = str(pathlib.Path(temp, "gone"))
|
||||
done = run_python(["-c", "pass"], gone, 60)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn(gone, done.stderr)
|
||||
|
||||
|
||||
class TypedAnswers(unittest.TestCase):
|
||||
def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self):
|
||||
route = Route(Rung("worker-model"))
|
||||
@@ -1803,11 +1697,10 @@ class LoopRuns(unittest.TestCase):
|
||||
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1, 7, 9), unfinished_run=2, items_taken_in=(12, 14))
|
||||
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
|
||||
self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)})
|
||||
self.assertEqual(set(reload.ROUTE_FIELDS), {field.name for field in dataclasses.fields(Route)})
|
||||
|
||||
def test_rejects_a_field_of_another_type_or_an_unknown_field(self):
|
||||
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1, 7, 9), unfinished_run=2))
|
||||
for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1)):
|
||||
for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1), (("route", "model"), "claude-opus-5-5"), (("route", "effort"), "high")):
|
||||
with self.subTest(path=path, wrong=wrong):
|
||||
handed = json.loads(json.dumps(state))
|
||||
target = handed
|
||||
@@ -1858,10 +1751,6 @@ class LoopRuns(unittest.TestCase):
|
||||
handed["route"]["escape_and_impact_taken_in"] = taken_in
|
||||
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
|
||||
|
||||
def test_drops_a_route_an_older_loop_claude_handed_under_r_plus_c_so_the_chunk_routes_afresh(self):
|
||||
older = {"cycle_number": 3, "root": "/r", "task": "do it", "unfinished_evidence": "", "route": {"rung": {"model": "claude-opus-5-5", "effort": "high"}, "item": 3, "risk_and_complexity": 11, "unfinished": 1}}
|
||||
self.assertEqual(reload.decode_handed(json.dumps(older)), main.LoopRun(3, "/r", "do it", ""))
|
||||
|
||||
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(3, "/r", "do it", ""))
|
||||
|
||||
@@ -1877,7 +1766,7 @@ class LoopRuns(unittest.TestCase):
|
||||
launcher = pathlib.Path(root, "loop-claude")
|
||||
launcher.write_text("")
|
||||
fake = FakeEffects(python=[ran()])
|
||||
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence=""), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
||||
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
||||
|
||||
|
||||
class HelpLimits(unittest.TestCase):
|
||||
@@ -1923,7 +1812,7 @@ class ExitContract(unittest.TestCase):
|
||||
("loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
|
||||
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
|
||||
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
|
||||
("loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {paths.config_clone}", "claude cannot start for an interrupt"),
|
||||
("loop/routing_check.py", "raise_calls", "1", "f\"could not start claude for the routing calls in {loop.paths.config_clone}", "claude cannot start for an interrupt"),
|
||||
("project/checkout.py", "checkout_root", "1", "found.reason", git),
|
||||
("project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
|
||||
("project/model_choice.py", "get_or_ask_model", "1", "models.reason", models_),
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
"""The effects loop-claude reaches the world through, such as its terminal, clock, processes, git and the machine's memory. loop-inbox runs on them too, so a change here, such as to how input reads a line, changes both tools."""
|
||||
"""The effects a tool reaches the world through, such as its terminal, clock, processes, git and the machine's memory.
|
||||
|
||||
A change here, such as to how input reads a line, changes every tool that runs on them.
|
||||
"""
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
@@ -0,0 +1,117 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import os
|
||||
import pathlib
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_effects.effects import run_python, say, system_effects
|
||||
|
||||
NOW = 1790000000
|
||||
# How a line said at NOW opens, with clocked's local_time.
|
||||
STAMP = f"<{NOW}>"
|
||||
|
||||
|
||||
def clocked():
|
||||
"""The system's effects on a clock stopped at NOW, which renders a time as <seconds>."""
|
||||
return dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: NOW)
|
||||
|
||||
|
||||
class Said(unittest.TestCase):
|
||||
def test_opens_a_line_with_the_local_time_of_the_effects_clock(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
|
||||
say("hello", clocked())
|
||||
self.assertEqual((stderr.getvalue(), stdout.getvalue()), (f"{STAMP} hello\n", ""))
|
||||
|
||||
def test_stamps_only_the_first_line_of_a_question_after_its_blank_line(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
say("\nWhich one?\n\nA or B?", clocked())
|
||||
self.assertEqual(stderr.getvalue(), f"\n{STAMP} Which one?\n\nA or B?\n")
|
||||
|
||||
def test_says_on_stdout_where_asked(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr, contextlib.redirect_stdout(io.StringIO()) as stdout:
|
||||
say("\n=== cycle 2 ===", clocked(), stdout=True)
|
||||
self.assertEqual((stderr.getvalue(), stdout.getvalue()), ("", f"\n{STAMP} === cycle 2 ===\n"))
|
||||
|
||||
def test_keeps_the_indent_of_the_first_line_after_the_time(self):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
say("\n indented", clocked())
|
||||
self.assertEqual(stderr.getvalue(), f"\n{STAMP} indented\n")
|
||||
|
||||
def test_flushes_so_piped_lines_arrive_when_said(self):
|
||||
flushes = []
|
||||
|
||||
class Counting(io.StringIO):
|
||||
def flush(self):
|
||||
flushes.append(self.getvalue())
|
||||
|
||||
with contextlib.redirect_stderr(Counting()):
|
||||
say("hello", clocked())
|
||||
self.assertEqual(flushes, [f"{STAMP} hello\n"])
|
||||
|
||||
|
||||
|
||||
class LocalTime(unittest.TestCase):
|
||||
def test_renders_seconds_in_the_machines_zone(self):
|
||||
# A POSIX zone two hours ahead of UTC, so a time in UTC would read 14:13:20. Cleanups run last in, first out: the zone is restored before time.tzset makes the clock read it again.
|
||||
self.addCleanup(time.tzset)
|
||||
zone = unittest.mock.patch.dict(os.environ, {"TZ": "XXX-2"})
|
||||
zone.start()
|
||||
self.addCleanup(zone.stop)
|
||||
time.tzset()
|
||||
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 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:
|
||||
self.assertEqual(run_python(["-c", "import os; print(os.getcwd())"], cwd, 60).stdout.strip(), os.path.realpath(cwd))
|
||||
|
||||
def test_stops_a_script_still_running_after_the_timeout_and_reads_it_as_exit_1(self):
|
||||
done = run_python(["-c", "import threading; threading.Event().wait()"], "/", 0.5)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn("0.5 s", done.stderr)
|
||||
|
||||
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
self.assertEqual(run_python(["-c", "import sys; sys.stdout.buffer.write(b'caf\\xe9')"], cwd, 60).stdout, "caf�")
|
||||
|
||||
def test_reads_a_script_that_cannot_start_as_exit_1_saying_why(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
gone = str(pathlib.Path(temp, "gone"))
|
||||
done = run_python(["-c", "pass"], gone, 60)
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn(gone, done.stderr)
|
||||
@@ -10,9 +10,9 @@ import dataclasses
|
||||
import textwrap
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.running_loops import RunningLoop, Taken
|
||||
from loop_claude.waiting.talk import TALK
|
||||
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_state.running_loops import RunningLoop, Taken
|
||||
from loop_state.waiting.talk import TALK
|
||||
|
||||
ENTER = "enter"
|
||||
BACKSPACE = "backspace"
|
||||
|
||||
+11
-11
@@ -26,8 +26,8 @@ above where it waits for an answer, and a line per todo.md item its chunk takes,
|
||||
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/ describes; the running loops are files beside them, as
|
||||
bin/loop_claude/running_loops.py describes.
|
||||
bin/loop_state/waiting/ describes; the running loops are files beside them, as
|
||||
bin/loop_state/running_loops.py describes.
|
||||
|
||||
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
|
||||
"""
|
||||
@@ -39,16 +39,16 @@ 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.ask import Ask, Asking, read_ask
|
||||
from loop_claude.waiting.listing import ask_file, drop_ended, waiting
|
||||
from loop_claude.waiting.talk import claim_talk, MAKE_WAY_SECONDS
|
||||
from loop_claude.waiting.answers import ClaudeEnded, send, Typed
|
||||
from loop_claude.running_loops import drop_ended_loops, running_loops
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from loop_state.waiting.ask import Ask, Asking, read_ask
|
||||
from loop_state.waiting.listing import ask_file, drop_ended, waiting
|
||||
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
|
||||
from loop_state.waiting.answers import ClaudeEnded, send, Typed
|
||||
from loop_state.running_loops import drop_ended_loops, running_loops
|
||||
from loop_effects.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
|
||||
from loop_state.hand_over import hand_over
|
||||
from loop_state.paths import Paths, paths_from
|
||||
from loop_state.session_lock import running
|
||||
|
||||
USAGE = "usage: loop-inbox"
|
||||
# Milliseconds between refreshes of the list while no key is pressed.
|
||||
|
||||
@@ -12,18 +12,18 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.waiting.answers import answered, claude_ended, ClaudeEnded, ClaudeOpening, send, Typed
|
||||
from loop_state.waiting.answers import answered, claude_ended, ClaudeEnded, ClaudeOpening, send, Typed
|
||||
from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal, read_ask
|
||||
from loop_claude.waiting.listing import ask_file, drop_ended, listed, publish, waiting, withdraw
|
||||
from loop_claude.waiting.talk import claim_talk, MAKE_WAY_SECONDS
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal, read_ask
|
||||
from loop_state.waiting.listing import ask_file, drop_ended, listed, publish, waiting, withdraw
|
||||
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
|
||||
from loop_state.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
|
||||
from loop_claude.running_loops import RunningLoop, Taken
|
||||
from loop_claude.effects import system_effects
|
||||
from loop_state.paths import paths_from
|
||||
from loop_state import running_loops, session_lock
|
||||
from loop_state.running_loops import RunningLoop, Taken
|
||||
from loop_effects.effects import system_effects
|
||||
|
||||
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
|
||||
# The pid of this loop-inbox.
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
"""The files loop-claude and loop-inbox share: a running loop lists itself (running_loops.py, session_lock.py) and its question (waiting/), and both read the same paths (paths.py) and open claude for the human the same way (hand_over.py).
|
||||
|
||||
A change here changes both tools. It imports nothing from loop_claude/.
|
||||
"""
|
||||
@@ -1,7 +1,7 @@
|
||||
"""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."""
|
||||
"""Opens claude on the terminal for the human."""
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
@@ -11,7 +11,7 @@ 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/).
|
||||
# Where a loop shows its interrupt to loop-inbox (bin/loop_state/waiting/).
|
||||
waiting: pathlib.Path
|
||||
|
||||
|
||||
@@ -6,8 +6,6 @@ branch as last fetched. The items are the one the chunk was routed on, then thos
|
||||
worker took in, each listed once. loop-inbox lists a loop, and its question (waiting/), 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.listing.drop_ended.
|
||||
|
||||
This module, waiting/ and session_lock.py hold loop-claude's state, which loop-inbox reads. They stay in loop_claude/ because they import its effects.py and hand_over.py: a package of their own would import loop_claude, and loop_claude would import it, a cycle.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
@@ -16,8 +14,8 @@ import pathlib
|
||||
import shutil
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_claude.session_lock import ended, held, running
|
||||
from loop_effects.effects import Effects, say
|
||||
from loop_state.session_lock import ended, held, running
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import items
|
||||
from records.file_writes import replace_json
|
||||
@@ -0,0 +1,41 @@
|
||||
import errno
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from loop_state import session_lock
|
||||
|
||||
|
||||
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"))
|
||||
@@ -5,7 +5,7 @@ import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
from loop_claude.waiting.ask import Ask, tagged
|
||||
from loop_state.waiting.ask import Ask, tagged
|
||||
from failure import Failure
|
||||
from records.file_writes import replace_json
|
||||
|
||||
@@ -6,7 +6,7 @@ import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from loop_state.hand_over import ClaudeCommand
|
||||
from records.utc_stamp import seconds, utc
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
@@ -3,10 +3,10 @@ import contextlib
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting.answers import answer_file
|
||||
from loop_claude.waiting.ask import Ask, ask_fields, read_ask
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_claude.session_lock import ended, running
|
||||
from loop_state.waiting.answers import answer_file
|
||||
from loop_state.waiting.ask import Ask, ask_fields, read_ask
|
||||
from loop_effects.effects import Effects, say
|
||||
from loop_state.session_lock import ended, running
|
||||
from failure import Failure
|
||||
from records.file_writes import make_private, replace_json
|
||||
|
||||
@@ -9,10 +9,10 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, read_ask
|
||||
from loop_claude.waiting.listing import ask_file, shown
|
||||
from loop_claude.waiting.answers import ClaudeEnded, ClaudeOpening, send
|
||||
from loop_claude.effects import Effects, POLL_SECONDS
|
||||
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, read_ask
|
||||
from loop_state.waiting.listing import ask_file, shown
|
||||
from loop_state.waiting.answers import ClaudeEnded, ClaudeOpening, send
|
||||
from loop_effects.effects import Effects, POLL_SECONDS
|
||||
from failure import Failure
|
||||
|
||||
# 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.
|
||||
@@ -92,17 +92,20 @@ def stepped_up(rung: Rung) -> Rung:
|
||||
return climbed(rung, 1)
|
||||
|
||||
|
||||
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind) -> Rung:
|
||||
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I.
|
||||
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
|
||||
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
|
||||
|
||||
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay …`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
"""
|
||||
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact)
|
||||
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact, markdown_only)
|
||||
|
||||
|
||||
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's."""
|
||||
return highest(worker, review_floor(project, escape_and_impact))
|
||||
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int, markdown_only: bool = False) -> Rung:
|
||||
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's, which is never below the project's.
|
||||
|
||||
markdown_only means the branch changes only Markdown no agent follows. Such a branch holds no code or config for a higher rung to catch a defect in, so its reviewer runs on the project's rung: skills/larv-review/SKILL.md → "Markdown only".
|
||||
"""
|
||||
return project if markdown_only else highest(worker, review_floor(project, escape_and_impact))
|
||||
|
||||
|
||||
def highest(*rungs: Rung) -> Rung:
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
import dataclasses
|
||||
|
||||
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
|
||||
from model_routing.ladder import reviewers_rung, Rung
|
||||
from model_routing.ladder import review_rung, reviewers_rung, Rung
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReviewChoice:
|
||||
# The rung of each pass's reviewer.
|
||||
reviewers: Rung
|
||||
# The rung of each pass's reviewer where the branch changes only Markdown no agent follows.
|
||||
markdown_only: Rung
|
||||
seat: Rung
|
||||
security: Rung
|
||||
# Each rung a higher E + I than the route's picks for the reviewers, with the lowest E + I that picks it, in rising order.
|
||||
@@ -22,5 +24,5 @@ def chosen(project: Rung, route: Route) -> ReviewChoice:
|
||||
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
|
||||
if (rung := reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
|
||||
higher.setdefault(rung, escape_and_impact)
|
||||
# A seat and the security pass run on the project's rung, as ladder.review_rung says.
|
||||
return ReviewChoice(reviewers, project, project, higher)
|
||||
markdown_only = reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True)
|
||||
return ReviewChoice(reviewers, markdown_only, review_rung(project, route.rung, route.reviewed_on(), "seat"), review_rung(project, route.rung, route.reviewed_on(), "security"), higher)
|
||||
|
||||
+10
-13
@@ -38,8 +38,6 @@ class Route:
|
||||
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
|
||||
"""
|
||||
# Each field below but rung and unfinished is a key of the archive's worker lines, so renaming one makes the lines already archived unreadable, and their chunks route afresh.
|
||||
# The fields a loop-claude from before L and E + I replaced R + C hands on reload; the reloaded script drops such a route, and the chunk routes afresh.
|
||||
RETIRED: typing.ClassVar[frozenset[str]] = frozenset({"risk_and_complexity"})
|
||||
rung: Rung
|
||||
item: int = 0
|
||||
likelihood: int = 0
|
||||
@@ -51,7 +49,7 @@ class Route:
|
||||
escalated_at: int = 0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check fits before they build a route.
|
||||
# Raises on a programming error only, so nothing catches it: route_of checks fits before it builds a route.
|
||||
if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in):
|
||||
raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}")
|
||||
|
||||
@@ -80,19 +78,18 @@ WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if
|
||||
|
||||
def route_from(worker: str) -> Route | None:
|
||||
"""The route an archived worker line names; None for a line Route.worker_line could not have written, such as text that isn't JSON."""
|
||||
fields = json_fields(worker)
|
||||
if fields is None or not Route.fits(fields):
|
||||
return None
|
||||
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
|
||||
|
||||
|
||||
def json_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
"""The fields of a line Route.worker_line wrote; None for any other text."""
|
||||
try:
|
||||
fields = json.loads(line)
|
||||
fields = json.loads(worker)
|
||||
except ValueError:
|
||||
return None
|
||||
return route_of(fields)
|
||||
|
||||
|
||||
def route_of(fields: object) -> Route | None:
|
||||
"""The route these fields of a worker line name, with an unfinished count of 0; None for fields Route.worker_line could not have written. A reload decodes its route through it too (loop_claude/loop/reload.py), so Route has one decoder."""
|
||||
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *WORKER_LINE_FIELDS}):
|
||||
return None
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
|
||||
if not all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) or not Route.fits(fields):
|
||||
return None
|
||||
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
|
||||
|
||||
@@ -103,3 +103,7 @@ class Ladder(unittest.TestCase):
|
||||
|
||||
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
|
||||
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS])
|
||||
|
||||
def test_puts_every_review_of_a_branch_changing_only_markdown_no_agent_follows_on_the_projects_rung(self):
|
||||
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
|
||||
self.assertEqual(review_rung(OPUS, LADDER[0], 4, "stability", markdown_only=True), OPUS)
|
||||
|
||||
@@ -11,3 +11,7 @@ FABLE = Rung("claude-fable-5-1", "max")
|
||||
class Chosen(unittest.TestCase):
|
||||
def test_names_no_higher_rung_on_the_top_one(self):
|
||||
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
|
||||
|
||||
def test_reviews_a_branch_changing_only_markdown_on_the_projects_rung_and_the_seats_and_security_pass_there_always(self):
|
||||
choice = chosen(OPUS, Route(FABLE, 3, 4, 5))
|
||||
self.assertEqual((choice.reviewers, choice.markdown_only, choice.seat, choice.security), (FABLE, OPUS, OPUS, OPUS))
|
||||
|
||||
+3
-3
@@ -89,7 +89,7 @@ import pathlib
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from release_plan import ranking
|
||||
from release_plan import plan_file
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -101,11 +101,11 @@ def main(argv: list[str]) -> int:
|
||||
return fail(args)
|
||||
check, todo = args
|
||||
if check:
|
||||
failures = ranking.check_failures(todo)
|
||||
failures = plan_file.check_failures(todo)
|
||||
for line in failures:
|
||||
print(line, file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
ranked = ranking.rank_file(todo)
|
||||
ranked = plan_file.rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return fail(ranked)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The order blockers impose on the ranked items: each blocker above every item it blocks, no blocker in a later release than an item it blocks, and no blockers in a loop."""
|
||||
import dataclasses
|
||||
import graphlib
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.release import version
|
||||
|
||||
|
||||
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
|
||||
"""scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped from the Blocked by cells."""
|
||||
held = {item.id: (item, value) for item, value in scored}
|
||||
position = {item.id: index for index, (item, _) in enumerate(scored)}
|
||||
for item, _ in scored:
|
||||
for blocker in item.blocked_by:
|
||||
if blocker in held and held[blocker][0].release > item.release:
|
||||
later, earlier = version(held[blocker][0].release), version(item.release)
|
||||
return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later")
|
||||
if loop := blocking_loop(held):
|
||||
return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers")
|
||||
placed: set[int] = set()
|
||||
return [entry for item, _ in scored for entry in place(item.id, held, position, placed)]
|
||||
|
||||
|
||||
def blocking_loop(held: dict[int, tuple[Item, float]]) -> list[int] | None:
|
||||
"""The IDs of items that block each other in a loop, sorted; None where there is no loop."""
|
||||
graph = {id_: {blocker for blocker in item.blocked_by if blocker in held} for id_, (item, _) in held.items()}
|
||||
try:
|
||||
graphlib.TopologicalSorter(graph).prepare()
|
||||
except graphlib.CycleError as cycle:
|
||||
return sorted(set(cycle.args[1]))
|
||||
return None
|
||||
|
||||
|
||||
def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int]) -> list[tuple[Item, float]]:
|
||||
"""id_'s item, preceded by each of its blockers not yet in placed, in score order, each of them preceded in turn by its own blockers; empty where placed already holds id_. Each item returned joins placed. blocking_loop has ruled out a loop, so the recursion ends."""
|
||||
if id_ in placed:
|
||||
return []
|
||||
placed.add(id_)
|
||||
item, value = held[id_]
|
||||
blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__)
|
||||
before = [entry for blocker in blockers for entry in place(blocker, held, position, placed)]
|
||||
return [*before, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)]
|
||||
|
||||
|
||||
def blocked_through(id_: int, items: list[Item]) -> set[int]:
|
||||
"""The IDs of the items id_ blocks, and of those they block in turn."""
|
||||
found: set[int] = set()
|
||||
reached = {id_}
|
||||
while reached:
|
||||
reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found
|
||||
found |= reached
|
||||
return found
|
||||
@@ -0,0 +1,65 @@
|
||||
"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can hold nothing else, and evaluated to a float."""
|
||||
import ast
|
||||
import math
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# The most parts and characters a formula may hold.
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
|
||||
|
||||
def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure:
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
# Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts.
|
||||
if len(source) > LONGEST_FORMULA:
|
||||
return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters")
|
||||
try:
|
||||
tree = ast.parse(source, mode="eval")
|
||||
except (SyntaxError, ValueError):
|
||||
return Failure(f"the formula {source!r} does not parse")
|
||||
nodes = list(ast.walk(tree))
|
||||
if len(nodes) > LARGEST_FORMULA:
|
||||
return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts")
|
||||
for node in nodes:
|
||||
numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300
|
||||
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)):
|
||||
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses")
|
||||
return tree
|
||||
|
||||
|
||||
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
"""Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan."""
|
||||
match node:
|
||||
case ast.Expression(body):
|
||||
return evaluate(body, values)
|
||||
case ast.Constant(value) if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
case ast.Name(name):
|
||||
return values[name]
|
||||
case ast.UnaryOp(ast.USub(), operand):
|
||||
return -evaluate(operand, values)
|
||||
case ast.UnaryOp(ast.UAdd(), operand):
|
||||
return evaluate(operand, values)
|
||||
case ast.BinOp(left, ast.Add(), right):
|
||||
return evaluate(left, values) + evaluate(right, values)
|
||||
case ast.BinOp(left, ast.Sub(), right):
|
||||
return evaluate(left, values) - evaluate(right, values)
|
||||
case ast.BinOp(left, ast.Mult(), right):
|
||||
return evaluate(left, values) * evaluate(right, values)
|
||||
case ast.BinOp(left, ast.Div(), right):
|
||||
divisor = evaluate(right, values)
|
||||
return evaluate(left, values) / divisor if divisor else math.nan
|
||||
case ast.BinOp(left, ast.Pow(), right):
|
||||
base, exponent = evaluate(left, values), evaluate(right, values)
|
||||
# A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1.
|
||||
if math.isnan(base) or math.isnan(exponent):
|
||||
return math.nan
|
||||
# math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three.
|
||||
try:
|
||||
return math.pow(base, exponent)
|
||||
except (OverflowError, ValueError):
|
||||
return math.nan
|
||||
return math.nan
|
||||
@@ -0,0 +1,62 @@
|
||||
"""todo.md on disk: read it with the project files ranking reads, then rank or check it, write it back, and print what ranking reports."""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from review_rules.comprehension_history import HISTORY
|
||||
from release_plan.ranking import rank, Ranked
|
||||
from records.file_writes import replace_file
|
||||
|
||||
|
||||
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
|
||||
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
|
||||
return unwritten
|
||||
print_report(todo, ranked)
|
||||
return ranked
|
||||
|
||||
|
||||
def print_report(todo: pathlib.Path, ranked: Ranked) -> None:
|
||||
"""Print ranking's notes and under-bar lines on stderr, each prefixed with todo's path."""
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
|
||||
|
||||
def check_failures(todo: pathlib.Path) -> list[str]:
|
||||
"""Why --check fails on todo, empty when it passes."""
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return [texts.reason]
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return [ranked.reason]
|
||||
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
|
||||
return unranked + [f"{todo}: {line}" for line in ranked.under_bar]
|
||||
|
||||
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md. The last two are empty when missing; a missing todo.md or README.md is a Failure."""
|
||||
texts = []
|
||||
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
|
||||
try:
|
||||
texts.append(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
if missing:
|
||||
return Failure(f"{path}: not found; {missing}")
|
||||
texts.append("")
|
||||
except OSError as failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{path}: not UTF-8")
|
||||
return texts[0], texts[1], texts[2], texts[3]
|
||||
|
||||
|
||||
def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
unwritten = replace_file(path.resolve(), text.encode("utf-8"))
|
||||
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
|
||||
+7
-161
@@ -1,19 +1,18 @@
|
||||
"""Rank todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar; rank_todo.py --help states the rules."""
|
||||
"""Rank todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar; rank_todo.py --help states the rules.
|
||||
"""
|
||||
import ast
|
||||
import dataclasses
|
||||
import decimal
|
||||
import graphlib
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
|
||||
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
|
||||
from release_plan.blockers import blocked_through, blockers_first
|
||||
from release_plan.formula import evaluate, parse_formula
|
||||
from failure import Failure
|
||||
from review_rules.comprehension_history import FLOOR, HISTORY, latest_overall
|
||||
from review_rules.comprehension_history import FLOOR, latest_overall
|
||||
from records.markdown_text import listed, sections
|
||||
from records.file_writes import replace_file
|
||||
from release_plan.release import version
|
||||
|
||||
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
|
||||
@@ -26,12 +25,9 @@ MAINTAIN_WEIGHT = 0.5
|
||||
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
|
||||
# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it.
|
||||
OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M)
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
WEIGHTS_HEADER = "| Goal | W |"
|
||||
# The Exempt reasons that rank ahead of the rest of their release, in this order: a question first, since its answer may change other items, then a security finding.
|
||||
FIRST = {"question": 0, "security": 1}
|
||||
FIRST: dict[Exempt, int] = {"question": 0, "security": 1}
|
||||
# How README.md marks a goal; None where it marks it neither way.
|
||||
Mark = typing.Literal["Maintain", "Achieve"] | None
|
||||
RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, score its L, E and I in place of C, and set the bar below the score of every item to keep"
|
||||
@@ -57,55 +53,6 @@ class Ranked:
|
||||
notes: list[str]
|
||||
|
||||
|
||||
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
|
||||
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
|
||||
return unwritten
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return ranked
|
||||
|
||||
|
||||
def check_failures(todo: pathlib.Path) -> list[str]:
|
||||
"""Why --check fails on todo, empty when it passes."""
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return [texts.reason]
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return [ranked.reason]
|
||||
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
|
||||
return unranked + [f"{todo}: {line}" for line in ranked.under_bar]
|
||||
|
||||
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none."""
|
||||
texts = []
|
||||
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
|
||||
try:
|
||||
texts.append(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
if missing:
|
||||
return Failure(f"{path}: not found; {missing}")
|
||||
texts.append("")
|
||||
except OSError as failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{path}: not UTF-8")
|
||||
return texts[0], texts[1], texts[2], texts[3]
|
||||
|
||||
|
||||
def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
unwritten = replace_file(path.resolve(), text.encode("utf-8"))
|
||||
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
table = read_table(lines)
|
||||
@@ -156,16 +103,6 @@ def notes(items: list[Item], scoring: Scoring) -> list[str]:
|
||||
return unweighed + dropped
|
||||
|
||||
|
||||
def blocked_through(id_: int, items: list[Item]) -> set[int]:
|
||||
"""The IDs of the items id_ blocks, and of those they block in turn."""
|
||||
found: set[int] = set()
|
||||
reached = {id_}
|
||||
while reached:
|
||||
reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found
|
||||
found |= reached
|
||||
return found
|
||||
|
||||
|
||||
def ordered(items: list[Item], scoring: Scoring) -> list[tuple[Item, float]] | Failure:
|
||||
"""Each item with its score, by release, then questions and security findings first, then by score from highest, then by ID; then each blocker above every item it blocks."""
|
||||
by_score = []
|
||||
@@ -298,42 +235,6 @@ def outside_items(lines: list[str], table: Table) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
|
||||
"""scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped."""
|
||||
held = {item.id: (item, value) for item, value in scored}
|
||||
position = {item.id: index for index, (item, _) in enumerate(scored)}
|
||||
for item, _ in scored:
|
||||
for blocker in item.blocked_by:
|
||||
if blocker in held and held[blocker][0].release > item.release:
|
||||
later, earlier = version(held[blocker][0].release), version(item.release)
|
||||
return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later")
|
||||
if loop := blocking_loop(held):
|
||||
return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers")
|
||||
placed: set[int] = set()
|
||||
return [entry for item, _ in scored for entry in place(item.id, held, position, placed)]
|
||||
|
||||
|
||||
def blocking_loop(held: dict[int, tuple[Item, float]]) -> list[int] | None:
|
||||
"""The IDs of items that block each other in a loop, sorted; None where there is no loop."""
|
||||
graph = {id_: {blocker for blocker in item.blocked_by if blocker in held} for id_, (item, _) in held.items()}
|
||||
try:
|
||||
graphlib.TopologicalSorter(graph).prepare()
|
||||
except graphlib.CycleError as cycle:
|
||||
return sorted(set(cycle.args[1]))
|
||||
return None
|
||||
|
||||
|
||||
def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int]) -> list[tuple[Item, float]]:
|
||||
"""The item id_, unless placed holds it, preceded by those of its blockers placed doesn't hold yet, each in score order, and theirs before them. Each item it returns joins placed. blocking_loop has ruled out a loop."""
|
||||
if id_ in placed:
|
||||
return []
|
||||
placed.add(id_)
|
||||
item, value = held[id_]
|
||||
blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__)
|
||||
before = [entry for blocker in blockers for entry in place(blocker, held, position, placed)]
|
||||
return [*before, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)]
|
||||
|
||||
|
||||
def check_citations(items: list[Item], decisions: str) -> Failure | None:
|
||||
"""Holds todo.md and docs/decisions.md to each other: a cited item is exempt, a decision row is cited."""
|
||||
cited = set(cited_items(decisions))
|
||||
@@ -390,61 +291,6 @@ def stated(text: str, name: str) -> str | Failure:
|
||||
return found[0]
|
||||
|
||||
|
||||
def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure:
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
# Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts.
|
||||
if len(source) > LONGEST_FORMULA:
|
||||
return Failure(f"the formula {source[:40]!r}... holds more than {LONGEST_FORMULA} characters")
|
||||
try:
|
||||
tree = ast.parse(source, mode="eval")
|
||||
except (SyntaxError, ValueError):
|
||||
return Failure(f"the formula {source!r} does not parse")
|
||||
nodes = list(ast.walk(tree))
|
||||
if len(nodes) > LARGEST_FORMULA:
|
||||
return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts")
|
||||
for node in nodes:
|
||||
numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300
|
||||
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)):
|
||||
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses")
|
||||
return tree
|
||||
|
||||
|
||||
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
"""Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan."""
|
||||
match node:
|
||||
case ast.Expression(body):
|
||||
return evaluate(body, values)
|
||||
case ast.Constant(value) if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
case ast.Name(name):
|
||||
return values[name]
|
||||
case ast.UnaryOp(ast.USub(), operand):
|
||||
return -evaluate(operand, values)
|
||||
case ast.UnaryOp(ast.UAdd(), operand):
|
||||
return evaluate(operand, values)
|
||||
case ast.BinOp(left, ast.Add(), right):
|
||||
return evaluate(left, values) + evaluate(right, values)
|
||||
case ast.BinOp(left, ast.Sub(), right):
|
||||
return evaluate(left, values) - evaluate(right, values)
|
||||
case ast.BinOp(left, ast.Mult(), right):
|
||||
return evaluate(left, values) * evaluate(right, values)
|
||||
case ast.BinOp(left, ast.Div(), right):
|
||||
divisor = evaluate(right, values)
|
||||
return evaluate(left, values) / divisor if divisor else math.nan
|
||||
case ast.BinOp(left, ast.Pow(), right):
|
||||
# math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three.
|
||||
base, exponent = evaluate(left, values), evaluate(right, values)
|
||||
# A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1.
|
||||
if math.isnan(base) or math.isnan(exponent):
|
||||
return math.nan
|
||||
try:
|
||||
return math.pow(base, exponent)
|
||||
except (OverflowError, ValueError):
|
||||
return math.nan
|
||||
return math.nan
|
||||
|
||||
|
||||
def goal_term(shape: Shape) -> str:
|
||||
"""The name of the formula's goal term, which score builds: W in OLD_SHAPE, V in the current shape."""
|
||||
return "W" if shape is OLD_SHAPE else "V"
|
||||
|
||||
@@ -45,9 +45,9 @@ def dated_heading_pattern(release: Release) -> str:
|
||||
return "^## " + re.escape(version(release)) + " - " + "-".join("[0-9]" * digits for digits in DATE_DIGITS) + "$"
|
||||
|
||||
|
||||
def newest_tag(cwd: str | None = None, merged_into: str | None = None) -> str | None | Failure:
|
||||
def newest_tag(cwd: str | None = None, merged_into: str | None = None, run: git_repo.Git = git_repo.git) -> str | None | Failure:
|
||||
"""The newest `v*` tag, read in cwd, else in the current directory, and merged into merged_into where it is given; None when there is none."""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0.
|
||||
merged = ["--merged", merged_into] if merged_into else []
|
||||
tags = git_repo.git("-c", "versionsort.suffix=-", "tag", "--list", "v*", *merged, "--sort=-v:refname", cwd=cwd)
|
||||
tags = run("-c", "versionsort.suffix=-", "tag", "--list", "v*", *merged, "--sort=-v:refname", cwd=cwd)
|
||||
return tags if isinstance(tags, Failure) else next(iter(tags.split()), None)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""How the plan stands to the last release cut: the next release, whether work has landed towards it, and whether it is to be planned, reviewed or cut; and, from that standing, the item the next chunk takes first, with what the default branch holds for the pick."""
|
||||
import dataclasses
|
||||
|
||||
from git_cli.git_repo import commits_since, file_at, git
|
||||
from git_cli.git_repo import commits_since, file_at, git, Git
|
||||
from release_plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item, items, next_item, renames
|
||||
@@ -90,46 +90,46 @@ class DefaultPlan:
|
||||
cut: LastCut
|
||||
|
||||
|
||||
def default_plan(root: str, ref: str) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root."""
|
||||
tag = newest_tag(root, merged_into=ref)
|
||||
changelog = file_at(ref, "CHANGELOG.md", root)
|
||||
def default_plan(root: str, ref: str, run: Git = git) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run."""
|
||||
tag = newest_tag(root, merged_into=ref, run=run)
|
||||
changelog = file_at(ref, "CHANGELOG.md", root, run)
|
||||
after = dated_cut(tag, changelog)
|
||||
since = tag if after is None else heading_commit(after, ref, root)
|
||||
commits = since if isinstance(since, Failure) else commits_since(since, ref, root)
|
||||
reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after)
|
||||
return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, changelog, commits, todos_since(tag, ref, root), reviewed))
|
||||
since = tag if after is None else heading_commit(after, ref, root, run)
|
||||
commits = since if isinstance(since, Failure) else commits_since(since, ref, root, run)
|
||||
reviewed = tag if isinstance(tag, Failure) else release_reviewed(tag, ref, root, after, run)
|
||||
return DefaultPlan(file_at(ref, "todo.md", root, run), LastCut(tag, changelog, commits, todos_since(tag, ref, root, run), reviewed))
|
||||
|
||||
|
||||
def heading_commit(release: Release, ref: str, cwd: str) -> str | None | Failure:
|
||||
def heading_commit(release: Release, ref: str, cwd: str, run: Git = git) -> str | None | Failure:
|
||||
"""The oldest commit on ref that added release's dated heading to CHANGELOG.md, which a branch with no tag counts the unreleased commits from; None where git finds none."""
|
||||
# -G matches the heading line itself, so a changelog entry that quotes the heading doesn't count.
|
||||
added = git("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", "CHANGELOG.md", cwd=cwd)
|
||||
added = run("log", "--reverse", "--format=%H", "-G", dated_heading_pattern(release), ref, "--", "CHANGELOG.md", cwd=cwd)
|
||||
return added if isinstance(added, Failure) else next(iter(added.split()), None)
|
||||
|
||||
|
||||
def release_reviewed(tag: str | None, ref: str, cwd: str, after: Release | None = None) -> bool | Failure:
|
||||
def release_reviewed(tag: str | None, ref: str, cwd: str, after: Release | None = None, run: Git = git) -> bool | Failure:
|
||||
"""Whether ref holds a commit titled as a release review opens, `Release review of <release>`: after tag, or anywhere where tag is None.
|
||||
|
||||
after is the version a branch with no tag counts as cut, or None. Where it is given, a title counts only where its release is later than after.
|
||||
"""
|
||||
titles = git("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd)
|
||||
titles = run("log", "--format=%s", f"{tag}..{ref}" if tag else ref, cwd=cwd)
|
||||
if isinstance(titles, Failure):
|
||||
return titles
|
||||
reviews = [title.removeprefix("Release review of ") for title in titles.splitlines() if title.startswith("Release review of ")]
|
||||
return any(after is None or ((named := parsed(review)) is not None and named > after) for review in reviews)
|
||||
|
||||
|
||||
def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure:
|
||||
def todos_since(tag: str | None | Failure, ref: str, cwd: str, run: Git = git) -> list[str] | Failure:
|
||||
"""LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent."""
|
||||
if isinstance(tag, Failure):
|
||||
return []
|
||||
changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", "todo.md", cwd=cwd)
|
||||
changed = run("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}" if tag else ref, "--", "todo.md", cwd=cwd)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
texts = []
|
||||
for commit in [*([tag] if tag else []), *changed.split()]:
|
||||
text = file_at(commit, "todo.md", cwd)
|
||||
text = file_at(commit, "todo.md", cwd, run)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
texts.append(text)
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from failure import Failure
|
||||
from release_plan import ranking, todo_table
|
||||
|
||||
|
||||
class Blockers(unittest.TestCase):
|
||||
def ranked(self, todo):
|
||||
return ranking.rank(todo, README, DECISIONS, "")
|
||||
|
||||
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
|
||||
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
|
||||
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
|
||||
""", ranked.text)
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
|
||||
def test_ranks_an_items_blockers_in_score_order(self):
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
|
||||
self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"])
|
||||
|
||||
def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self):
|
||||
chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |")
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
|
||||
self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"])
|
||||
|
||||
def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self):
|
||||
# Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release.
|
||||
waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |"))
|
||||
self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), [])
|
||||
answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |"))
|
||||
self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5])
|
||||
|
||||
def test_ships_an_item_above_r_5_alone(self):
|
||||
# Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins.
|
||||
found = todo_table.items(TODO)
|
||||
self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
|
||||
self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
|
||||
self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), [])
|
||||
# At R 6, item 3 ships alone too.
|
||||
riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |"))
|
||||
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))])
|
||||
# Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6.
|
||||
unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |"))
|
||||
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))])
|
||||
|
||||
def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self):
|
||||
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
|
||||
ranked = self.ranked(finished)
|
||||
self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text)
|
||||
self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
|
||||
self.assertEqual(self.ranked(ranked.text).notes, [])
|
||||
|
||||
def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self):
|
||||
cases = {
|
||||
"| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later",
|
||||
"| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by",
|
||||
"| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held",
|
||||
"| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held",
|
||||
}
|
||||
for cell, reason in cases.items():
|
||||
with self.subTest(cell=cell):
|
||||
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason))
|
||||
looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")
|
||||
self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers"))
|
||||
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \""))
|
||||
|
||||
def test_adds_the_column_to_a_table_without_it(self):
|
||||
without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without)
|
||||
self.assertEqual(self.ranked(without), self.ranked(TODO))
|
||||
unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n")
|
||||
self.assertEqual(self.ranked(unscored), self.ranked(TODO))
|
||||
|
||||
def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_one_an_older_shape_held(self):
|
||||
extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, L, E, I, R, S, Moves, Score. Rename it, or move this machine to the release that added it"))
|
||||
self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5])
|
||||
with_c = TODO.replace("| S | Moves |", "| S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
with_c = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+ \| \d+ \| \d+) \|", r"\1 | 3 |", with_c)
|
||||
self.assertEqual(self.ranked(with_c), Failure("todo.md's items table has C, a column of an older shape; drop it, as rank_todo.py --help shows"))
|
||||
|
||||
def test_refuses_text_under_items_beside_the_table(self):
|
||||
last = TODO.split("\n## Details")[0] + "\n"
|
||||
self.assertIsInstance(self.ranked(last), ranking.Ranked)
|
||||
beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail")
|
||||
for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"):
|
||||
with self.subTest(ordered=ordered[-60:]):
|
||||
self.assertEqual(self.ranked(ordered), beside)
|
||||
|
||||
def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self):
|
||||
self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n")
|
||||
self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items")
|
||||
table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n"
|
||||
above = table + "\n" + TODO.replace(table, "")
|
||||
self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items")
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table"))
|
||||
repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one"))
|
||||
|
||||
def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self):
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |"
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), [])
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line"))
|
||||
@@ -0,0 +1,24 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from failure import Failure
|
||||
from release_plan import ranking
|
||||
|
||||
|
||||
class Formula(unittest.TestCase):
|
||||
def ranked(self, todo):
|
||||
return ranking.rank(todo, README, DECISIONS, "")
|
||||
|
||||
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
|
||||
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
|
||||
with self.subTest(formula=formula):
|
||||
self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure)
|
||||
self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text)
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score"))
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score"))
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses"))
|
||||
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10"))
|
||||
@@ -9,7 +9,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from release_plan import ranking
|
||||
from release_plan import plan_file, ranking
|
||||
from repo_checks import ROOT
|
||||
from release_plan import todo_table
|
||||
|
||||
@@ -207,16 +207,6 @@ class Rank(unittest.TestCase):
|
||||
weighted = TODO.replace("## Items\n", "| Goal | W |\n|---|---|\n| 1 | 1.00 |\n\n## Items\n")
|
||||
self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs the goals itself, as its --help says"))
|
||||
|
||||
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
|
||||
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
|
||||
with self.subTest(formula=formula):
|
||||
self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure)
|
||||
self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text)
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score"))
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score"))
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses"))
|
||||
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10"))
|
||||
|
||||
def test_refuses_a_file_off_the_format(self):
|
||||
row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |"
|
||||
broken = {
|
||||
@@ -351,7 +341,7 @@ class CodeHealth(unittest.TestCase):
|
||||
pathlib.Path(temp, "docs").mkdir()
|
||||
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
ranked = ranking.rank_file(todo)
|
||||
ranked = plan_file.rank_file(todo)
|
||||
self.assertIsInstance(ranked, ranking.Ranked)
|
||||
self.assertEqual(ranked.under_bar, [])
|
||||
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
|
||||
@@ -451,111 +441,6 @@ class OldShape(unittest.TestCase):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
|
||||
|
||||
|
||||
class Blockers(unittest.TestCase):
|
||||
def ranked(self, todo):
|
||||
return ranking.rank(todo, README, DECISIONS, "")
|
||||
|
||||
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
|
||||
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
|
||||
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
|
||||
""", ranked.text)
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
|
||||
def test_ranks_an_items_blockers_in_score_order(self):
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
|
||||
self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"])
|
||||
|
||||
def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self):
|
||||
chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |")
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
|
||||
self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"])
|
||||
|
||||
def test_bundles_with_the_next_item_each_item_of_its_release_that_no_question_or_item_outside_the_chunk_blocks(self):
|
||||
# Item 2 is the next item. Item 5 is a question, 3 waits on 5, and 4 waits on 3; item 1 is in a later release.
|
||||
waits = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |"))
|
||||
self.assertEqual(todo_table.bundle_candidates(waits, todo_table.next_item(waits)), [])
|
||||
answered = todo_table.items(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 4 | 0.1.0 | | security |", "| 4 | 0.1.0 | 3 | security |"))
|
||||
self.assertEqual([item.id for item in todo_table.bundle_candidates(answered, todo_table.next_item(answered))], [3, 5])
|
||||
|
||||
def test_ships_an_item_above_r_5_alone(self):
|
||||
# Item 4 has R 9: it joins no chunk, and none joins it. Item 5, at R 5, still joins.
|
||||
found = todo_table.items(TODO)
|
||||
self.assertNotIn(4, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
|
||||
self.assertIn(5, [item.id for item in todo_table.bundle_candidates(found, todo_table.next_item(found))])
|
||||
self.assertEqual(todo_table.bundle_candidates(found, next(item for item in found if item.id == 4)), [])
|
||||
# At R 6, item 3 ships alone too.
|
||||
riskier = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | 6 | 7 |"))
|
||||
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(riskier, todo_table.next_item(riskier))])
|
||||
# Before rank_todo.py fills its R cell, item 3's L 3, E 2 and I 3 still make R 6.
|
||||
unranked = todo_table.items(TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 3 | 2 | 3 | | 7 |"))
|
||||
self.assertNotIn(3, [item.id for item in todo_table.bundle_candidates(unranked, todo_table.next_item(unranked))])
|
||||
|
||||
def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self):
|
||||
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
|
||||
ranked = self.ranked(finished)
|
||||
self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text)
|
||||
self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
|
||||
self.assertEqual(self.ranked(ranked.text).notes, [])
|
||||
|
||||
def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self):
|
||||
cases = {
|
||||
"| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later",
|
||||
"| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by",
|
||||
"| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held",
|
||||
"| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held",
|
||||
}
|
||||
for cell, reason in cases.items():
|
||||
with self.subTest(cell=cell):
|
||||
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason))
|
||||
looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")
|
||||
self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers"))
|
||||
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \""))
|
||||
|
||||
def test_adds_the_column_to_a_table_without_it(self):
|
||||
without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without)
|
||||
self.assertEqual(self.ranked(without), self.ranked(TODO))
|
||||
unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n")
|
||||
self.assertEqual(self.ranked(unscored), self.ranked(TODO))
|
||||
|
||||
def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_one_an_older_shape_held(self):
|
||||
extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, L, E, I, R, S, Moves, Score. Rename it, or move this machine to the release that added it"))
|
||||
self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5])
|
||||
with_c = TODO.replace("| S | Moves |", "| S | C | Moves |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
with_c = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+ \| \d+ \| \d+) \|", r"\1 | 3 |", with_c)
|
||||
self.assertEqual(self.ranked(with_c), Failure("todo.md's items table has C, a column of an older shape; drop it, as rank_todo.py --help shows"))
|
||||
|
||||
def test_refuses_text_under_items_beside_the_table(self):
|
||||
last = TODO.split("\n## Details")[0] + "\n"
|
||||
self.assertIsInstance(self.ranked(last), ranking.Ranked)
|
||||
beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail")
|
||||
for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"):
|
||||
with self.subTest(ordered=ordered[-60:]):
|
||||
self.assertEqual(self.ranked(ordered), beside)
|
||||
|
||||
def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self):
|
||||
self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n")
|
||||
self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items")
|
||||
table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n"
|
||||
above = table + "\n" + TODO.replace(table, "")
|
||||
self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items")
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table"))
|
||||
repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one"))
|
||||
|
||||
def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self):
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |"
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), [])
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line"))
|
||||
|
||||
|
||||
class Renamed(unittest.TestCase):
|
||||
def test_reads_the_releases_the_renamed_section_names(self):
|
||||
self.assertEqual(todo_table.renames("## Items\n\n## Details\n"), set())
|
||||
|
||||
@@ -13,7 +13,9 @@ LEVELS = {"L": 4, "E": 3, "I": 5}
|
||||
RISK_FLOOR = {4: 5, 5: 7}
|
||||
# The highest R an item may have and still share a chunk; `docs/decisions.md` → `chunks:` says why 5.
|
||||
BUNDLE_MAX_R = 5
|
||||
EXEMPTIONS = ("", "decision", "defect", "owner", "principle", "question", "security")
|
||||
# What an Exempt cell may hold: empty, or a reason ~/.claude/rules/todo-items.md defines.
|
||||
Exempt = typing.Literal["", "decision", "defect", "owner", "principle", "question", "security"]
|
||||
EXEMPTIONS: tuple[Exempt, ...] = typing.get_args(Exempt)
|
||||
# The column naming the items that block an item: each must be done before the item starts.
|
||||
BLOCKED_BY = "Blocked by"
|
||||
# The column naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`.
|
||||
@@ -94,7 +96,7 @@ OLD_SHAPE = Shape(("R", "S", "C", "A", "G"), (BLOCKED_BY, "C", "Score"), (), (),
|
||||
class Item:
|
||||
id: int
|
||||
release: Release
|
||||
exempt: str
|
||||
exempt: Exempt
|
||||
tagline: str
|
||||
scores: dict[str, int]
|
||||
moves: Moves
|
||||
@@ -263,8 +265,9 @@ def parse_row(row: str, table: Table) -> Item | Failure:
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
named = dict(zip(table.columns, found))
|
||||
if misformed := check_cells(row, named):
|
||||
return misformed
|
||||
exempt = check_cells(row, named)
|
||||
if isinstance(exempt, Failure):
|
||||
return exempt
|
||||
shape = shape_of(table.columns)
|
||||
scores = parse_scores(named["ID"], {name: cell for name, cell in named.items() if cell or name not in shape.derived}, shape.score_columns)
|
||||
if isinstance(scores, Failure):
|
||||
@@ -275,21 +278,25 @@ def parse_row(row: str, table: Table) -> Item | Failure:
|
||||
moves = shape.read_goals(named["ID"], named[shape.goals_column])
|
||||
if isinstance(moves, Failure):
|
||||
return moves
|
||||
return Item(int(named["ID"]), release_of(named["Release"]), named["Exempt"], named["Item"], scores, moves, blocked_by)
|
||||
return Item(int(named["ID"]), release_of(named["Release"]), exempt, named["Item"], scores, moves, blocked_by)
|
||||
|
||||
|
||||
def check_cells(row: str, named: dict[str, str]) -> Failure | None:
|
||||
"""Holds the row's ID, Release, Exempt and Item cells to the format: why one breaks it, None when none does."""
|
||||
def is_exempt(cell: str) -> typing.TypeGuard[Exempt]:
|
||||
return cell in EXEMPTIONS
|
||||
|
||||
|
||||
def check_cells(row: str, named: dict[str, str]) -> Exempt | Failure:
|
||||
"""Holds the row's ID, Release, Exempt and Item cells to the format: the row's Exempt cell, or why a cell breaks it."""
|
||||
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
|
||||
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
|
||||
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
|
||||
if parsed(release) is None:
|
||||
return Failure(f"item {id_}'s release {release!r} is not a semver version")
|
||||
if exempt not in EXEMPTIONS:
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
|
||||
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
|
||||
return None
|
||||
return exempt
|
||||
|
||||
|
||||
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import ast
|
||||
import importlib
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from repo_checks import ROOT
|
||||
|
||||
TRIALS = ROOT / "reviewer-merge-trials"
|
||||
|
||||
|
||||
def bin_imports(source: str) -> list[tuple[str, str | None]]:
|
||||
"""Each module the source imports from bin/, with each name it takes from that module or reads through a name bound to it, or None for the module itself."""
|
||||
tree = ast.parse(source)
|
||||
found: list[tuple[str, str | None]] = []
|
||||
# A name the source binds to a module, such as rm in `from review_replay import main as rm`.
|
||||
modules: dict[str, str] = {}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
|
||||
found += [(node.module, alias.name) for alias in node.names]
|
||||
modules |= {alias.asname or alias.name: f"{node.module}.{alias.name}" for alias in node.names if is_module(f"{node.module}.{alias.name}")}
|
||||
elif isinstance(node, ast.Import):
|
||||
found += [(alias.name, None) for alias in node.names]
|
||||
modules |= {alias.asname: alias.name for alias in node.names if alias.asname}
|
||||
found += [(modules[node.value.id], node.attr) for node in ast.walk(tree) if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in modules]
|
||||
return [(module, name) for module, name in found if in_bin(module)]
|
||||
|
||||
|
||||
def is_module(dotted: str) -> bool:
|
||||
path = ROOT / "bin" / dotted.replace(".", "/")
|
||||
return path.is_dir() or path.with_suffix(".py").is_file()
|
||||
|
||||
|
||||
def in_bin(module: str) -> bool:
|
||||
return is_module(module.split(".")[0])
|
||||
|
||||
|
||||
class TrialsImports(unittest.TestCase):
|
||||
"""docs/decisions.md says to rerun the trials' scripts when a new model joins the ladder or a reviewer's definition changes, so a refactor of bin/ must not break what they import."""
|
||||
|
||||
def test_each_name_a_trials_script_imports_from_bin_exists(self):
|
||||
scripts = sorted(TRIALS.glob("*.py"))
|
||||
self.assertTrue(scripts)
|
||||
for script in scripts:
|
||||
for module, name in bin_imports(script.read_text(encoding="utf-8")):
|
||||
with self.subTest(script=script.name, module=module, name=name):
|
||||
imported = importlib.import_module(module)
|
||||
if name is not None:
|
||||
self.assertTrue(hasattr(imported, name) or importlib.util.find_spec(f"{module}.{name}"))
|
||||
|
||||
def test_an_import_of_a_bin_module_is_found_and_a_stdlib_one_is_not(self):
|
||||
self.assertEqual(bin_imports("import json\nfrom failure import Failure\nimport review_replay.main as rm\n"), [("failure", "Failure"), ("review_replay.main", None)])
|
||||
|
||||
def test_a_name_read_through_a_module_alias_is_found(self):
|
||||
source = "from review_replay import main as rm\nimport review_replay.rounds as rr\nrm.code_of(rr.Round)\n"
|
||||
self.assertEqual(bin_imports(source), [("review_replay", "main"), ("review_replay.rounds", None), ("review_replay.main", "code_of"), ("review_replay.rounds", "Round")])
|
||||
+1
-1
@@ -6,6 +6,6 @@ import sys
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from review_replay import main
|
||||
from loop_claude.effects import system_effects
|
||||
from loop_effects.effects import system_effects
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
|
||||
|
||||
@@ -43,7 +43,7 @@ from rung_replay.command import arguments_or_exit, down_from, failed, limited_ex
|
||||
from review_replay.rounds import authored_by, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from transcript_archive.project_key import checkout_of
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
|
||||
@@ -15,7 +15,7 @@ import unittest.mock
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from loop_effects.effects import Effects, system_effects
|
||||
from claude_code.entries import entry_from
|
||||
from failure import Failure
|
||||
from review_replay import main
|
||||
|
||||
@@ -95,7 +95,7 @@ def print_overrides(directory: str) -> int:
|
||||
return 1
|
||||
found = guarded_git(directory, "branch", "--show-current")
|
||||
branch = found if isinstance(found, str) and found else "HEAD"
|
||||
reflog = guarded_git(directory, "reflog", "show", "--format=%H", branch)
|
||||
reflog = guarded_git(directory, "reflog", "show", "--format=%H", branch, "--")
|
||||
head = guarded_git(directory, "rev-parse", "HEAD")
|
||||
unread = unread_reflog(reflog, head)
|
||||
if unread:
|
||||
|
||||
@@ -29,10 +29,7 @@ def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Bre
|
||||
kind = review_kind(call.given)
|
||||
if kind is None or project is None or worker is None:
|
||||
return []
|
||||
required = review_rung(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
|
||||
required = review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd))
|
||||
named = named_rung(call.given, worker)
|
||||
if position(named) >= position(required):
|
||||
return []
|
||||
|
||||
@@ -7,13 +7,14 @@ import resource
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import typing
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rule_hook.repeat_read import Asked, modified, read_breaches, result_lines
|
||||
from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides
|
||||
from rule_hook.rules import blocks, Breach, check, command_breaches, file_breaches, overrides, RuleName, RULES
|
||||
from rule_hook.main import breaches_of
|
||||
from rule_hook.call import Call, parsed_call
|
||||
from git_cli.git_command import commit_message, CommitCall, commits
|
||||
@@ -682,6 +683,15 @@ class Hook(unittest.TestCase):
|
||||
git(self.repo, "branch", "-m", "renamed")
|
||||
self.assertIn("\timage-pin\t", self.listed(), "the reflog keeps the amended commit")
|
||||
|
||||
def test_a_folder_named_like_the_branch_doesn_t_hide_the_overrides(self):
|
||||
os.mkdir(f"{self.repo}/chunk")
|
||||
pathlib.Path(self.repo, "chunk", "notes.md").write_text("x\n", encoding="utf-8")
|
||||
git(self.repo, "add", "chunk")
|
||||
git(self.repo, "commit", "-q", "-m", "a folder named like the branch")
|
||||
content = "# rule-override image-pin: the vendor tags no patch versions\nFROM vendor/tool:2\n"
|
||||
hook({"cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/Dockerfile", "content": content}, "tool_name": "Write"}, self.repo)
|
||||
self.assertIn("\timage-pin\t", self.listed())
|
||||
|
||||
def test_an_unreadable_reflog_fails_the_listing(self):
|
||||
unborn = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", unborn])
|
||||
@@ -901,3 +911,8 @@ class TodoRankCheck(unittest.TestCase):
|
||||
reasons = self.details(self.changed_plan(self.other, self.STUB))
|
||||
self.assertTrue(reasons)
|
||||
self.assertNotIn("own script", " ".join(reasons))
|
||||
|
||||
|
||||
class RuleNames(unittest.TestCase):
|
||||
def test_every_rule_name_has_a_rule_and_every_rule_a_name(self):
|
||||
self.assertEqual(set(RULES), set(typing.get_args(RuleName)))
|
||||
|
||||
@@ -6,7 +6,7 @@ import sys
|
||||
from rule_hook.rules import Breach
|
||||
from failure import Failure
|
||||
from rule_hook.git import guarded_git
|
||||
from release_plan import ranking
|
||||
from release_plan import plan_file
|
||||
|
||||
|
||||
# The checkout this hook runs from: bin/rule_hook/ sits two folders below it.
|
||||
@@ -27,7 +27,7 @@ def check_failures(top: str, todo: pathlib.Path, own: pathlib.Path) -> list[str]
|
||||
"""Why rank_todo.py --check fails on todo. A checkout of the repo the hook runs from checks with its own bin/rank_todo.py, so a branch that changes the table's shape is held to its own rules. Any other checkout checks with the hook's ranking: running its script would run its code before every commit."""
|
||||
script = pathlib.Path(top) / "bin" / "rank_todo.py"
|
||||
if not script.is_file() or not same_repo(top, own):
|
||||
return ranking.check_failures(todo)
|
||||
return plan_file.check_failures(todo)
|
||||
try:
|
||||
ran = subprocess.run([sys.executable, str(script), "--check", str(todo)], capture_output=True, cwd=top, text=True, timeout=OWN_CHECK_SECONDS)
|
||||
except subprocess.TimeoutExpired:
|
||||
|
||||
@@ -6,7 +6,7 @@ import typing
|
||||
from failure import Failure
|
||||
from model_routing.ladder import LADDER, position, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_state.paths import paths_from
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
|
||||
# What a tool reads from its arguments, such as the project's rung of the model they name.
|
||||
|
||||
+8
-13
@@ -30,7 +30,7 @@ import typing
|
||||
from todo_item.edits import added, finished, with_bullet
|
||||
from release_plan.todo_table import BLOCKED_BY, MOVES
|
||||
from failure import Failure
|
||||
from release_plan import ranking
|
||||
from release_plan import plan_file, ranking
|
||||
|
||||
# Each score flag, as --l or --L, and the column it fills.
|
||||
LETTERS = ("L", "E", "I", "S")
|
||||
@@ -70,7 +70,7 @@ def parser() -> argparse.ArgumentParser:
|
||||
|
||||
def add(args: argparse.Namespace, folder: pathlib.Path, stdin: typing.TextIO) -> str | Failure:
|
||||
todo = folder / "todo.md"
|
||||
texts = ranking.read_all(todo)
|
||||
texts = plan_file.read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
named = {"Release": args.release, BLOCKED_BY: args.blocked_by, "Exempt": args.exempt, "Item": args.tagline, MOVES: args.moves}
|
||||
@@ -84,9 +84,9 @@ def add(args: argparse.Namespace, folder: pathlib.Path, stdin: typing.TextIO) ->
|
||||
return Failure(f"not filed: {ranked.reason}")
|
||||
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
|
||||
return Failure(f"not filed: {under[0]}")
|
||||
if unwritten := ranking.write(todo, ranked.text):
|
||||
if unwritten := plan_file.write(todo, ranked.text):
|
||||
return unwritten
|
||||
report(todo, ranked)
|
||||
plan_file.print_report(todo, ranked)
|
||||
return f"Filed item {id_}."
|
||||
|
||||
|
||||
@@ -96,11 +96,11 @@ def finish(args: argparse.Namespace, folder: pathlib.Path) -> str | Failure:
|
||||
if isinstance(texts, Failure):
|
||||
return Failure(f"not finished: {texts.reason}")
|
||||
ranked, news = texts
|
||||
if unwritten := ranking.write(todo, ranked.text):
|
||||
if unwritten := plan_file.write(todo, ranked.text):
|
||||
return Failure(f"not finished: {unwritten.reason}")
|
||||
if news is not None and (unwritten := ranking.write(changelog, news)):
|
||||
if news is not None and (unwritten := plan_file.write(changelog, news)):
|
||||
return Failure(f"{unwritten.reason}; todo.md no longer holds item {args.id}, so add its bullet by hand")
|
||||
report(todo, ranked)
|
||||
plan_file.print_report(todo, ranked)
|
||||
return f"Finished item {args.id}."
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ def finish_texts(args: argparse.Namespace, todo: pathlib.Path, changelog: pathli
|
||||
"""What finish writes: todo ranked without item args.id, and changelog's new text, None where finish leaves it as is."""
|
||||
if changelog.exists() and args.changelog is None and not args.no_changelog:
|
||||
return Failure("CHANGELOG.md exists beside todo.md; pass --changelog <bullet>, or --no-changelog where the repo publishes nothing")
|
||||
texts = ranking.read_all(todo)
|
||||
texts = plan_file.read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
text = finished(texts[0], args.id)
|
||||
@@ -127,8 +127,3 @@ def finish_texts(args: argparse.Namespace, todo: pathlib.Path, changelog: pathli
|
||||
return Failure(f"{changelog}: not UTF-8")
|
||||
return news if isinstance(news, Failure) else (ranked, news)
|
||||
|
||||
|
||||
def report(todo: pathlib.Path, ranked: ranking.Ranked) -> None:
|
||||
"""Print ranking's notes and under-bar lines on stderr, each prefixed with todo.md's path, as rank_todo.py does."""
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
|
||||
@@ -10,7 +10,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from todo_item import edits, main
|
||||
from failure import Failure
|
||||
from release_plan import ranking
|
||||
from release_plan import plan_file, ranking
|
||||
|
||||
ADD = ["add", "--release", "0.1.0", "--l", "1", "--e", "1", "--i", "1", "--s", "1", "--moves", "1 by 9", "Count the `a | b` runs."]
|
||||
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- Older news.\n\n## 0.1.0\n\n- First.\n"
|
||||
@@ -50,7 +50,7 @@ class TodoItem(unittest.TestCase):
|
||||
return raised.exception.code
|
||||
|
||||
def assert_ranked(self):
|
||||
self.assertEqual(ranking.check_failures(self.todo), [])
|
||||
self.assertEqual(plan_file.check_failures(self.todo), [])
|
||||
|
||||
def details(self):
|
||||
text = self.todo.read_text()
|
||||
|
||||
@@ -58,8 +58,8 @@ def interrupted(question: str, evidence: str, judge: str, escalation: str, worke
|
||||
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
|
||||
|
||||
|
||||
def answered(question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine, judge_cost: float = 0.0) -> str:
|
||||
"""escalation and worker are as on interrupted."""
|
||||
def answered(*, question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: WorkerLine, judge_cost: float = 0.0) -> str:
|
||||
"""escalation and worker are as on interrupted. Every parameter is keyword-only, since a swap of two str ones would still type-check."""
|
||||
escalated = escalation_block(escalation)
|
||||
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{judge_lines(judge, judge_cost)}\n{WORKER}{worker}"
|
||||
|
||||
|
||||
@@ -72,9 +72,9 @@ class Outcomes(unittest.TestCase):
|
||||
self.assertEqual(outcomes.interrupted("q?", "e", "j", "", "w"), "Verdict: interrupt\n\nq?\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
|
||||
|
||||
def test_archives_the_escalation_and_the_worker_a_quoted_answer_names(self):
|
||||
self.assertEqual(outcomes.answered("q?", "AGENTS.md", "A.", "e", "round 2: 🔴", "j", "w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.answered("q?", "AGENTS.md", "A.", "e", "", "j", "w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.answered('q?', 'AGENTS.md', 'A.', 'e', '', 'j', 'w')}\n"), [(utc(NOW), "w")])
|
||||
self.assertEqual(outcomes.answered(question="q?", sources="AGENTS.md", answer="A.", evidence="e", escalation="round 2: 🔴", judge="j", worker="w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.answered(question="q?", sources="AGENTS.md", answer="A.", evidence="e", escalation="", judge="j", worker="w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.answered(question='q?', sources='AGENTS.md', answer='A.', evidence='e', escalation='', judge='j', worker='w')}\n"), [(utc(NOW), "w")])
|
||||
|
||||
def test_reads_no_worker_from_an_outcome_written_before_the_worker_line(self):
|
||||
kept = f"Task: Do it.\n\n{utc(NOW)} Stopped: Ctrl-C\n\n{utc(NOW)} Verdict: unfinished\n\nEvidence:\n> Worker: no\n"
|
||||
|
||||
@@ -3409,3 +3409,122 @@ Inherited architect, decided by:
|
||||
- Shape, Locality: `bin/routing_figures/chunk.py:62` `chunk_figures`: four concerns split into files with typed entries.
|
||||
- Locality: `bin/routing_figures/state.py:45` `due`: the archive-root state has one owner.
|
||||
- Locality: `bin/release_plan/ranking.py:469` `weight_of`: item 274's rule for a maintain point's weight sits in one function instead of two places.
|
||||
|
||||
## 2026-11-10T21:39:35Z, PR #467 at 05539e2, against 98b7bfd
|
||||
|
||||
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:
|
||||
|
||||
- Navigation, Locality: `bin/loop_state/__init__.py:1` `loop_state`: the files loop-claude and loop-inbox share have their own package, whose docstring says a change there changes both tools
|
||||
- Navigation, Shape: `bin/loop_effects/effects.py:1` `Effects`: the replay tools and the trials driver import `loop_effects.effects`, not a private-looking `loop_claude.effects`
|
||||
- Locality, Shape: `bin/release_plan/ranking.py:1` `ranking`: blocker order, formula parser and disk I/O moved to named files, so one can change without the score weighting in view
|
||||
- Locality, Shape: `bin/loop_claude/loop/this_loop.py:12` `Loop`: seven to nine positional arguments, two of them swappable strings, became one frozen value
|
||||
- Locality: `bin/loop_claude/cycle/run.py:93` `archived`: five copies of the archive call became one named helper
|
||||
- Navigation: `README.md:116` "bin/ map": the map follows the tools directly and testing has its own heading
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Navigation, Locality: `bin/loop_state/__init__.py:1` `loop_state`: an inbox symptom now lands in a package named for the shared state, not seven modules inside `loop_claude/`
|
||||
- Shape, Locality: `bin/release_plan/ranking.py:56` `rank`: the 550-line module's I/O, formula and blocker order each have an obvious file
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:84` `next_route`: each verdict kind has its own function, and `steps` and `below_cap` name the two conditions
|
||||
- Locality: `bin/model_routing/route.py:88` `route_of`: the archive line and the reload hand-over decode a Route through one decoder
|
||||
- Shape: `bin/loop_claude/loop/main.py:66` `next_cycle`: signatures of seven or eight positional parameters shrink to `(loop_run, loop)`
|
||||
|
||||
## 2026-11-10T23:11:34Z, PR #473 at 13d1550
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 5.5 | 6 | 6.5 | 6 |
|
||||
| Maintainability senior | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Inherited architect | 7 | 5.5 | 6 | 7 | 6 |
|
||||
| Mean | 7.00 | 5.50 | 6.00 | 6.38 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:93` `unfinished_route`: the floor rung, the escalation mark, the unfinished count and the cap are held at once, with escalation_mark.py open beside it
|
||||
- Locality, Shape: `bin/larv_review/plan.py:66` `plan_reasons`: eight failure branches mix git reads, file reads and logic, and a parameter named `default` receives a merge-base commit
|
||||
- Locality: `bin/larv_review/owed.py:37` `shortfall`: whether one or two runs are owed hangs on the wording of an English sentence that SKILL.md also keys on
|
||||
- Shape: `bin/loop_claude/cycle/run.py:59` `run_cycle`: four near-identical archive helpers and a route replaced partway through the loop
|
||||
- Shape: `bin/release_plan/ranking.py:56` `rank`: nearly every function forks on the table's two shapes
|
||||
- Self-sufficiency: `skills/larv-review/SKILL.md:147` "Scoring run": dense rule prose with many cross-references, three sections to rebuild one rule
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/larv_review/plan.py:66` `plan_reasons`: `default` holds a merge-base commit on one call path and `after` means the checkout's text, then its items
|
||||
- Locality: `bin/loop_claude/routing.py:93` `unfinished_route`: six concepts meet in about twelve lines and need four modules open beside it
|
||||
- Locality: `bin/larv_review/owed.py:37` `shortfall`: a rule keyed on the text of a sentence that plan.py builds, and `scoring_runs` defines a scoring run differently from `Entry.scored`
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:211` `quotes_checked`: a verdict is rewritten four times, half the behaviour in prompt prose and half in code
|
||||
- Shape: `bin/release_plan/ranking.py:304` `score`: every function branches on the old and the current table shape
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/larv_review/plan.py:66` `plan_reasons`: a merge-base commit enters the parameter named for the default branch, and its error text would print the commit as a branch
|
||||
- Locality: `bin/larv_review/owed.py:37` `shortfall`: the one-run-or-two rule is spread over three files and a skill document
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:93` `unfinished_route`: the six inputs interlock and a wrong answer runs the worker on the wrong rung without failing
|
||||
- Locality: `bin/model_routing/route.py:88` `route_of`: a route has two serializations, a flat archive line and a nested handover
|
||||
- Self-sufficiency: `bin/larv_review/plan.py:66` `plan_reasons`: its docstring doesn't say the first argument may be a commit
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Navigation, Shape: `bin/larv_review/owed.py:10` `owed_scoring_run`: the name gives the merge gate's question, not the module's subject, and the scoring-run logic sits in three files whose imports read as circular
|
||||
- Locality: `bin/larv_review/plan.py:14` `EMPTIED_WORDS`: prose and code share an exact string that SKILL.md keys on
|
||||
- Locality: `bin/loop_claude/routing.py:93` `unfinished_route`: routing logic spreads over about eight places, so a new trigger touches five files in three packages
|
||||
- Shape: `bin/rule_hook/rules.py:25` `RULES`: rules sit inline in one module while five others have a module each
|
||||
- Navigation: `bin/` README.md:116 "bin/": 56 entries in one flat list, the worst fan-out level
|
||||
|
||||
## 2026-11-11T12:55:06Z, PR #475 at 52da15e
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Mid A | 7.5 | 6 | 6.5 | 6.5 | 6.5 |
|
||||
| Maintainability senior | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.13 | 6.00 | 6.25 | 6.38 | 6.38 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:93` `unfinished_route`: the floor, the escalation cap, the escalation mark, the unfinished count and the taken-in E + I are held at once
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:211` `quotes_checked`: the judge's contract is split over prose constants, schema descriptions and post-hoc checks that change a verdict's type
|
||||
- Locality: `bin/loop_claude/cycle/run.py:146` `rule`: archive order carries meaning across `run_cycle` and `loop/close.py:18` `closed_cycle`
|
||||
- Shape: `bin/release_plan/release_standing.py:145` `next_release`: tag, changelog, before-first-release and renamed branches meet in the `is_earliest` expression
|
||||
- Shape: `bin/release_plan/ranking.py:56` `rank`: `OLD_SHAPE` and `SHAPE` forks run through nearly every function
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:59` `review_launches`: the worker's prompt is built from about ten conditional sentence builders
|
||||
- Locality: `skills/larv-review/SKILL.md:76` "Round cap": the cap is enforced in four units in two places
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:93` `unfinished_route`: five things applied in a fixed order across about six helpers; the reason for the floor and cap sits in the decision log
|
||||
- Locality: `bin/loop_claude/cycle/run.py:146` `rule`: the order of ruling, rejection and step-up archive writes is stated piecemeal
|
||||
- Shape: `bin/release_plan/ranking.py:315` `weight_of`: old-shape branches double the module, and the constants are magic until rules/todo-items.md is open
|
||||
- Shape: `bin/release_plan/release_standing.py:145` `next_release`: a three-way boolean on line 167 with no comment for the `None` and `nothing_cut` case
|
||||
- Locality: `bin/rule_hook/repeat_read.py:119` `shown_lines`: rebuilds which lines are in the agent's context from transcript entries
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:211` `quotes_checked`: half of the judge's rules are English constants edited in step with Python
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:119` `escalation`: about 20 sentence builders restate the routing logic
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Shape, Locality: `bin/release_plan/release_standing.py:145` `next_release`: four fallbacks held at once, and `is_earliest` took three reads
|
||||
- Locality: `bin/loop_claude/routing.py:93` `unfinished_route`: the escalation mark's meaning lives in `escalation_mark.py`, which has to stay open beside it
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:211` `quotes_checked`: a bad quote silently changes the verdict's type
|
||||
- Shape: `bin/release_plan/ranking.py:304` `score`: every path forks on `SHAPE` versus `OLD_SHAPE`
|
||||
- Locality: `bin/rule_hook/reviewer_rung.py:40` `skill_breaches`: three cases rest on assumptions made in another function
|
||||
- Locality: `bin/loop_claude/cycle/run.py:146` `rule`: order-dependent archive writes that nothing enforces
|
||||
- Shape: `bin/review_rules/comprehension_history.py:127` `entries`: a line-by-line parser that tolerates two legacy formats
|
||||
- Self-sufficiency: `skills/larv-review/SKILL.md:76` "Round cap": dense cross-referencing rules, with the enforcing code in other modules
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Navigation, Shape: `README.md:116` `bin/`: 55 entries at one level, about 31 packages, the worst fan-out level
|
||||
- Locality: `bin/larv_review/reviewer_header.py:49` `unanswered_round`: the round cap counts answer commits, so a worker that relaunches without committing gets the same round number, and the rule is split over SKILL.md and three modules
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:93` `unfinished_route`: seven counters and limits across five files, with field names frozen by the reload handover
|
||||
- Locality: `bin/chunk_pr/main.py:42` `forge`: the forge helpers live in `chunk_preflight` and `deploy_release`, so a second forge needs edits in four packages
|
||||
- Shape: `bin/records/__init__.py:1` `records`: one name for three concepts, as `cut` and `Plan` also name several
|
||||
- Locality: `bin/loop_claude/cycle/run.py:86` `archived`: the archive helpers that `loop/close.py` imports sit in the cycle runner
|
||||
|
||||
+7
-5
@@ -24,7 +24,7 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo
|
||||
|
||||
The cap is 5, `bin/release_plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it.
|
||||
|
||||
## comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
## comprehension floor: every dimension and the overall at 7.0 or above is the target, and no score blocks a merge or release
|
||||
|
||||
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor blocks nothing, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats.
|
||||
|
||||
@@ -103,7 +103,7 @@ The trials: four stability rounds and five principles rounds archived on 2026-10
|
||||
- A cap on tool results. Claude Code caps a Bash result at about 30k characters already. A PostToolUse hook capping it at 12k, which `updatedToolOutput` allows, left the stability reviewers 3 of 6 findings, two lost in one round. Read results, 59.9M characters in subagents' threads with 58% of their characters in results over 12k, are out of such a hook's reach. Not worth an item.
|
||||
- A scout: Haiku 5.5 reading raw content, whole files or long output, and returning facts as path:line and the ranges worth reading, so the agent's own context holds the summary and the chosen lines. In session, as an agent under `agents/`, its first request writes 37k tokens, $0.005, and a read of a 38KB file costs $0.008 in 8 seconds. As a slim headless `claude -p` with its own system prompt, no setting sources and no dynamic sections, which keeps the subscription login, it starts at 6k tokens and $0.0003 in 3 to 5 seconds, its prefix cached across calls, and the same read costs $0.004 in 7 seconds; a direct API call and `claude --bare` need an API key, so they are out. Stability reviewers with the agent scout found 5 of 6 findings and read 29% fewer characters at 6% less cost and 14% more time; with the CLI scout 4 of 6, 38% fewer, 17% less and 39% more; the auditors with the agent scout 3 of 6, the 🔴 among the lost, at the same cost and twice the time. Workers offered the scout never called it.
|
||||
- What a reviewer reads: the auditors read the project whole by design. Of their 🔴 and 🟡 findings since the reset, 47% named a file the chunk edited and 51% another file, so reading only the change would drop half of them (`review: the principles audit runs only in the release review, and reads the project whole with one auditor checking the goals and every principles file that applies`).
|
||||
- The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loads as user instructions into every project's sessions; `todo.md` item 52), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record.
|
||||
- The base context: every thread starts with `~/.claude/CLAUDE.md` (19k characters), `~/.claude/AGENTS.md` (11k, this repo's decisions, which Claude Code loads as user instructions into every project's sessions), the project's `AGENTS.md`, and, for the worker and general-purpose subagents, the skill listing (18k) and the agent listing (12k). Subagents' first messages wrote $97 of it. Trimming the listings would save about $20, 2%, and is not worth an item: `disableBundledSkills` would also drop `/security-review`, the security pass of record.
|
||||
|
||||
Quality. Under the 200k window, every figure's mean per chunk fell. Measured on 2026-11-04, the first 20 chunks whose worker started under it, from 2026-10-28, took a mean 4.0 review rounds past each pass's first against 5.8 for the 20 before them, from 2026-10-23 to 2026-10-26; 0.20 unfinished verdicts against 0.30; 1.15 🔴 against 1.90; 11.9 🟡 against 19.4; 0.11 misread findings against 0.25; $22 against $34; and 9.6 hours against 42. Only the median dollars went up, $15.17 against $11.72: the 20 before held four chunks of $94 to $167, and the 20 after none above $76. This decision weighs all spend, so the mean is the figure that counts. The two groups also differ in projects and routing, so how much of the fall the window caused is unknown. Before the window, 19 chunks compacted between 2026-10-10 and 2026-10-22, at the compaction points Claude Code set then, 214k to 972k tokens. Per 100 worker messages they took a median 3.6 review rounds past each pass's first against 4.0 for the 68 uncompacted chunks of 100 messages or more, and 13.9 🔴 and 🟡 findings against 16.6. 4 of 19 had an unfinished verdict against 3 of 68, each 8 to 10 hours after the compaction and followed by a finished verdict within minutes; in those four verdicts the judge quoted the worker's own passages and the human's typed answers, never a summary. One cause was possible and is closed here: Claude Code writes the summary as a user entry, which `bin/claude_code/entries.py` read as the human's words, so the judge would see a `[human]` line of thousands of words and `/talk` would count it as typed; it now reads as Claude Code's. Two summaries read whole kept the chunk's intent, files, errors and next step in 12k to 20k characters, and the worker resumed without re-reading.
|
||||
|
||||
@@ -113,7 +113,7 @@ Valid while cache reads cost a twentieth of input and Claude Code's compaction k
|
||||
|
||||
## 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/` holds the protocol:
|
||||
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_state/waiting/` 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.
|
||||
@@ -254,7 +254,7 @@ Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without
|
||||
|
||||
2026-10-28, lilleman: prose findings stay, since Claude's prose needs them, though prose's 105 first rounds since 2026-10-21 raised 498 🟡 and only 3 🔴.
|
||||
|
||||
## review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
## review: the comprehension check records how hard a project is to read, and no score blocks a merge: a paired ruling against the last measured commit in the release review, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
|
||||
2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that changed nothing (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/release_plan/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do.
|
||||
|
||||
@@ -264,6 +264,8 @@ The base is the last measured commit: the default branch's newest merged change
|
||||
|
||||
2026-10-17, lilleman. Serves goal 1.1. Nothing checked the 2026-10-08 validity condition. The history's successive scoring runs of one PR read changed code, not near-identical code, so they cannot stand for two absolute runs. So each release's scoring run is done twice on the same head, the second recorded under `<PR> rerun at <commit>`, and `larv-review agreement` compares two rates: how often Mid A and the inherited architect vote alike overall in paired rulings, and how often their overall scores move alike between two scoring runs on one commit. It gives no verdict until the history holds 10 such pairs of runs, as `score-outcomes` waits for 10 chunks before it shows a median. The human chose the second run's cost, four more seats per release (goal 1.4), over a weaker check on the old pairs.
|
||||
|
||||
2026-11-11, lilleman. Serves goal 1.1. Item 296 made `chunk-pr merge` refuse while a scoring run the plan calls is unrecorded on the branch, so a missing run can block a merge. No score or ruling does, and the titles say so: "no score blocks a merge".
|
||||
|
||||
## review: the premises chunk's whole review is the human's approval
|
||||
|
||||
2026-09-20, lilleman. Serves goal 1.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
|
||||
@@ -288,7 +290,7 @@ A trial checked that it keeps goal 1.1. It replayed the 6 latest first rounds th
|
||||
|
||||
2026-10-13, lilleman through todo item 108, implemented by claude. Serves goals 1.1 and 1.4. Coverage counts the lines a test runs, so a test without a meaningful assertion still raises it. A surviving mutant shows a test that would let behaviour break. Every mutant of an untested changed line survives, so mutation testing of the changed lines also shows what a coverage drop on them would. Coverage would also catch a deleted test; the stability reviewer sees one in the diff without it. Measuring coverage beside it would add cost without raising quality, so todo item 69 was dropped and `principles/technical-principles.md` replaced "Test coverage should not decline" with the mutant rule.
|
||||
|
||||
The reviewer limits each run to the changed lines, so its cost grows with the chunk. The tools are widely deployed, each with its own way to limit a run to a diff: cargo-mutants `--in-diff` (https://mutants.rs/in-diff.html), Infection `--git-diff-lines` (https://infection.github.io/guide/command-line-options.html), Stryker's mutation ranges (https://stryker-mutator.io/docs/stryker-js/configuration/). mutmut has no such option, so the reviewer mutates the changed files and keeps the mutants on changed lines. On 2026-10-13 mutmut 3 ran on this repo's `larv_review/rounds.py` in under two seconds, set up as README → "Tools" says.
|
||||
The reviewer limits each run to the changed lines, so its cost grows with the chunk. The tools are widely deployed, each with its own way to limit a run to a diff: cargo-mutants `--in-diff` (https://mutants.rs/in-diff.html), Infection `--git-diff-lines` (https://infection.github.io/guide/command-line-options.html), Stryker's mutation ranges (https://stryker-mutator.io/docs/stryker-js/configuration/). mutmut has no such option, so the reviewer mutates the changed files and keeps the mutants on changed lines. On 2026-10-13 mutmut 3 ran on this repo's `larv_review/rounds.py` in under two seconds, set up as README → "Test" says.
|
||||
|
||||
The run has no time cap. Limiting it to the changed lines already bounds it by the chunk's size, and no published standard gives a cap to copy. Each run's wall time in the reviewer's report shows when the premise below fails.
|
||||
|
||||
|
||||
@@ -1470,3 +1470,69 @@ Read most (opens and searches):
|
||||
- `bin/review-replay` 1
|
||||
- `bin/review_replay/rounds.py` 1
|
||||
- `bin/review_replay/test_review_replay.py` 1
|
||||
|
||||
## Reading cost, chunk cd3529c360f1, finished 2026-11-10T10:16:31Z
|
||||
|
||||
62832 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 2
|
||||
- `bin/chunk_pr/main.py` 2
|
||||
- `bin/chunk_pr/test_chunk_pr.py` 2
|
||||
- `skills/larv-review/SKILL.md` 2
|
||||
- `CLAUDE.md` 1
|
||||
- `bin/chunk-pr` 1
|
||||
- `bin/deploy_release/forge.py` 1
|
||||
- `bin/git_cli/test_git_repo.py` 1
|
||||
- `bin/test_env.py` 1
|
||||
- `ci.sh` 1
|
||||
|
||||
## Reading cost, chunk 28ce38e83321, finished 2026-11-10T10:22:17Z
|
||||
|
||||
45353 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 5
|
||||
- `bin/rule_hook/test_rule_hook.py` 3
|
||||
- `bin/rule_hook/override_log.py` 2
|
||||
- `AGENTS.md` 1
|
||||
- `CHANGELOG.md` 1
|
||||
- `README.md` 1
|
||||
- `docs/decisions.md` 1
|
||||
|
||||
## Reading cost reset, 2026-11-10T10:24:57Z
|
||||
|
||||
## Reading cost, chunk 45957f8ee8a3, finished 2026-11-10T10:30:06Z
|
||||
|
||||
101515 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 6
|
||||
- `CHANGELOG.md` 3
|
||||
- `docs/decisions.md` 3
|
||||
- `skills/larv-review/SKILL.md` 3
|
||||
- `AGENTS.md` 2
|
||||
- `CLAUDE.md` 1
|
||||
- `agents/stability-reviewer.md` 1
|
||||
- `bin/chunk_preflight/facts.py` 1
|
||||
- `docs/reading-cost.md` 1
|
||||
- `todo.md` 1
|
||||
|
||||
## Reading cost, chunk 3ea737667ec0, finished 2026-11-10T20:38:11Z
|
||||
|
||||
168988 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 5
|
||||
|
||||
## Reading cost, chunk 31a25a029608, finished 2026-11-10T22:36:58Z
|
||||
|
||||
40731 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 1
|
||||
|
||||
@@ -47,6 +47,7 @@ h1, h2, h3 { font-family: var(--display); text-wrap: balance; margin: 0; line-he
|
||||
h1 { font-size: 3.4rem; font-weight: 800; letter-spacing: -0.02em; }
|
||||
h2 { font-size: 2rem; font-weight: 800; letter-spacing: -0.01em; }
|
||||
h3 { font-size: 1.15rem; font-weight: 600; }
|
||||
.intro3 h2 { font-size: 1.15rem; font-weight: 600; letter-spacing: normal; }
|
||||
p { margin: 0; max-width: 65ch; }
|
||||
.lead { font-size: 1.25rem; color: var(--muted); max-width: 52ch; }
|
||||
.eyebrow { font: 700 0.75rem/1 var(--body); letter-spacing: 0.12em; text-transform: uppercase; color: var(--muted); }
|
||||
@@ -199,7 +200,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
|
||||
<p class="lead">You write down what you want and who it is for. An AI plans the work, writes the code, gets it reviewed and merges it, one pull request at a time, for as long as the plan holds work.</p>
|
||||
<div class="intro3">
|
||||
<div class="col">
|
||||
<h3>The problem</h3>
|
||||
<h2>The problem</h2>
|
||||
<ul>
|
||||
<li><b>You babysit the agent.</b> Every few minutes it asks something, or waits for a yes.</li>
|
||||
<li><b>It forgets.</b> Long sessions drift, and you explain the same context again.</li>
|
||||
@@ -208,7 +209,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
|
||||
</ul>
|
||||
</div>
|
||||
<div class="col">
|
||||
<h3>What loop-claude does</h3>
|
||||
<h2>What loop-claude does</h2>
|
||||
<ul>
|
||||
<li><b>It runs unattended.</b> A judge reads every run, and interrupts you only for a choice that is yours.</li>
|
||||
<li><b>It starts fresh every chunk.</b> The repo is the memory: goals, plan and decisions are written down.</li>
|
||||
@@ -217,7 +218,7 @@ dl.gloss dt { font-weight: 700; } dl.gloss dd { margin: 0; color: var(--muted);
|
||||
</ul>
|
||||
</div>
|
||||
<div class="col">
|
||||
<h3>What it aims for</h3>
|
||||
<h2>What it aims for</h2>
|
||||
<ul>
|
||||
<li><b>Maintainable for years.</b> Code that stays easy to read, change and debug, tomorrow and after seven years.</li>
|
||||
<li>The highest quality, with the fewest interruptions.</li>
|
||||
|
||||
@@ -172,7 +172,7 @@ Each match and new-finding count costs about $0.30 on Opus 5.5 at medium.
|
||||
|
||||
## How to rerun
|
||||
|
||||
Run every script from this folder, on the host's Python. They import review-replay from `~/code/claude-config/bin`; the trials ran against commit 82eb8ff, and candidate 4 against 0442074, where review-replay was unchanged.
|
||||
Run every script from this folder, on the host's Python. They import from this checkout's `bin/`, and `bin/repo_checks/test_trials_imports.py` checks that every name they import from it still exists. The trials ran against commit 82eb8ff, and candidate 4 against 0442074, where review-replay was unchanged.
|
||||
The scripts name the candidates `wave3` (candidate 1), `release` (candidate 2) and `pair` (candidate 4).
|
||||
|
||||
To replay on another model, change two places: `collect.py` keeps only projects on `claude-opus-5-5`, and `driver.py`'s `RUNG` is Opus 5.5 at medium.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Match each variant's replay reports to the archived findings, and list new findings. Usage: analyze.py <candidate> <variant>-<run>..."""
|
||||
import concurrent.futures, json, pathlib, pickle, re, sys
|
||||
sys.path.insert(0, str(pathlib.Path.home() / "code/claude-config/bin"))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "bin"))
|
||||
from claude_code.reply import claude_reply
|
||||
import driver as d
|
||||
from failure import Failure
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Pickle to runs.pkl one flat list of the archived reviewer runs of the projects on claude-opus-5-5, with or without findings, each with its round number from the prompt."""
|
||||
import json, pathlib, pickle, re, sys
|
||||
sys.path.insert(0, str(pathlib.Path.home() / "code/claude-config/bin"))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "bin"))
|
||||
from claude_code.entries import AssistantTurn, parse_entry, Text, UserText
|
||||
from transcript_archive.project_key import checkout_of
|
||||
from failure import Failure
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import collections, glob, json, pathlib, re, sys
|
||||
sys.path.insert(0, str(pathlib.Path.home() / "code/claude-config/bin"))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "bin"))
|
||||
from review_replay.rounds import recorded_findings
|
||||
cand=sys.argv[1]
|
||||
for vr in sys.argv[2:]:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Replay archived review rounds separately or merged, and save each replay's reply, reports and cost; analyze.py matches them. Usage: driver.py <candidate> <sep|merged> <run> [case ids...]"""
|
||||
import concurrent.futures, json, os, pathlib, pickle, re, shutil, sys, tempfile
|
||||
sys.path.insert(0, str(pathlib.Path.home() / "code/claude-config/bin"))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "bin"))
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from review_replay.main import clone_reviewed, Copies, copy_reports, match, redirected
|
||||
from failure import Failure
|
||||
@@ -8,7 +8,7 @@ from review_replay.rounds import lost_inputs, Round
|
||||
from review_rules.review_folder import REPORTS, review_folder
|
||||
from review_replay import main as rm
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.effects import system_effects
|
||||
from loop_effects.effects import system_effects
|
||||
|
||||
HERE = pathlib.Path(__file__).resolve().parent
|
||||
HOME = pathlib.Path.home()
|
||||
|
||||
@@ -136,7 +136,7 @@ Launch one principles-auditor on the trigger in §3, so the project is read once
|
||||
|
||||
### Comprehension check
|
||||
|
||||
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and blocks no merge. Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs once, in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
|
||||
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs once, in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
|
||||
|
||||
**Paired ruling.** Each seat votes whether the project reads better, the same or worse at this branch's head than at the base.
|
||||
|
||||
@@ -144,7 +144,7 @@ The comprehension check records how hard the project is for its contributor to r
|
||||
- **Head.** The head holds `origin/<default branch>`, merged in at §4 step 1, so it differs from the default branch only by this branch's change.
|
||||
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a votes file in the chunk's review folder, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <votes file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again.
|
||||
|
||||
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`.
|
||||
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
|
||||
|
||||
- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means.
|
||||
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to 7.0. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to 7.0, and quotes those places. Its tagline holds the words `comprehension floor`, so its own chunk runs a scoring run; while a mean stays under 7.0, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
|
||||
@@ -194,7 +194,7 @@ Launch prose-reviewer with what the diff touched and every section this review c
|
||||
1. Read the finished PR against the README goals and code health, unless the README voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict.
|
||||
2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded.
|
||||
3. Remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch, commit and push that, and wait for the forge's checks (§4 step 4); the commit re-enters no pass.
|
||||
4. Aligned, every pass done and everything green → **merge** with `~/.claude/bin/chunk-pr merge --gate-passed`, which takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
4. Aligned, every pass done and everything green → **merge** with `~/.claude/bin/chunk-pr merge --gate-passed`, which takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, after `~/.claude/bin/larv-review scoring-run-owed` exits 0. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary.
|
||||
6. Stop. The next chunk gets a fresh session.
|
||||
|
||||
|
||||
@@ -6,80 +6,109 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 291`
|
||||
`Next ID = 303`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 277 | 0.7.0 | | question | **Map the size of the code an item names onto S, on a scale the human picks, and have `score-outcomes` print that S for the item being scored and for each finished item it lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 4, 1.4 by 3 | 2.4 |
|
||||
| 1 | 0.7.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
|
||||
| 290 | 0.7.0 | | defect | **Have `rule-hook overrides` read the branch's reflog when a file or folder shares the branch's name.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 286 | 0.7.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 4 | 1.0 |
|
||||
| 287 | 0.8.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 |
|
||||
| 294 | 0.8.0 | | | **Check the files a commit stages against rule-hook's file rules, so a file a Bash command wrote is held to them as an Edit or Write is.** | 2 | 2 | 3 | 5 | 4 | 1.3 by 5 | 5.2 |
|
||||
| 297 | 0.8.0 | | | **Have loop-claude compute the judge's taken-in items, release-ready and escalation fields from `chunk-preflight`, git and the worker's structured lines, and leave the judge only the verdict kind.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 2, code health by 2 | 3.7 |
|
||||
| 302 | 0.8.0 | | | **Call a scoring run for an item whose tagline makes the comprehension floor its target, and not for one that only names the floor, such as in a quoted decision title.** | 2 | 2 | 3 | 5 | 3 | code health by 2 | 3.6 |
|
||||
| 293 | 0.8.0 | | | **Run mutation tests on a chunk's changed lines in the worker's pre-review gate, through one command that picks the tool by language, and hand stability-reviewer the surviving mutants.** | 3 | 2 | 3 | 6 | 5 | 1.1 by 5, 1.4 by 4, 1.5 by 2 | 2.8 |
|
||||
| 284 | 0.8.0 | | owner | **Script each step that 0.7.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.6 |
|
||||
| 288 | 0.8.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 |
|
||||
| 77 | 0.8.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 |
|
||||
| 273 | 0.8.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 |
|
||||
| 171 | 0.8.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 2.0 |
|
||||
| 149 | 0.8.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 1.8 |
|
||||
| 165 | 0.8.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 1.8 |
|
||||
| 151 | 0.8.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 1.8 |
|
||||
| 68 | 0.8.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 1.8 |
|
||||
| 102 | 0.8.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 1.7 |
|
||||
| 135 | 0.8.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 1.7 |
|
||||
| 270 | 0.8.0 | | | **Compare each review pass's share of chunks that go to a second round, and move each check stability repeats across chunks into the worker's pre-review gate.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 2, 1.4 by 2 | 1.6 |
|
||||
| 5 | 0.8.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.6 |
|
||||
| 156 | 0.8.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.4 |
|
||||
| 196 | 0.8.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 260 | 0.8.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 269 | 0.8.0 | | | **Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 51 | 0.8.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.3 |
|
||||
| 268 | 0.8.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 3 | 1.3 |
|
||||
| 201 | 0.8.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.3 |
|
||||
| 267 | 0.8.0 | | | **Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.** | 2 | 1 | 3 | 4 | 2 | 1.5 by 3 | 1.3 |
|
||||
| 4 | 0.8.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 1.3 |
|
||||
| 187 | 0.8.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 264 | 0.8.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 266 | 0.8.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 52 | 0.8.0 | | principle | **Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4, 1.4 by 2 | 1.0 |
|
||||
| 181 | 0.8.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 192 | 0.8.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 193 | 0.8.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 194 | 0.8.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 202 | 0.8.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 265 | 0.8.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 1.0 |
|
||||
| 169 | 0.8.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 0.8 |
|
||||
| 174 | 0.8.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 1 | 1.1 by 1 | 0.5 |
|
||||
| 197 | 0.8.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 0.4 |
|
||||
| 270 | 0.8.0 | | | **Move each check a review pass repeats across chunks, other than the mutation tests item 293 moves, into the worker's pre-review gate, starting with the passes most often taken to a second round.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 3, 1.4 by 3 | 2.5 |
|
||||
| 292 | 0.8.0 | | owner | **Rebuild the routing ladder for Fable 5.2, placing each of its efforts by the Artificial Analysis Intelligence Index beside Opus 5.5's and Sonnet 5.5's, and replace Fable 5.1 wherever it is named.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 4, 1.4 by 3 | 2.4 |
|
||||
| 295 | 0.8.0 | | | **Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 2, 1.5 by 2 | 1.6 |
|
||||
| 299 | 0.8.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 298 | 0.8.0 | 297 | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 1.0 |
|
||||
| 287 | 0.9.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 3.4 |
|
||||
| 288 | 0.9.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.6 |
|
||||
| 77 | 0.9.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.4 |
|
||||
| 273 | 0.9.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.3 |
|
||||
| 268 | 0.9.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 2.2 |
|
||||
| 171 | 0.9.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 2.0 |
|
||||
| 300 | 0.9.0 | | owner | **Restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first: today the comprehension floor run at 52da15e scored Locality 6.00, Shape 6.25, Self-sufficiency 6.38 and Overall 6.38.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 2.0 |
|
||||
| 264 | 0.9.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 2.0 |
|
||||
| 149 | 0.9.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 1.8 |
|
||||
| 165 | 0.9.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 1.8 |
|
||||
| 151 | 0.9.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 1.8 |
|
||||
| 68 | 0.9.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 1.8 |
|
||||
| 102 | 0.9.0 | | | **Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 3 | 1.1 by 4 | 1.7 |
|
||||
| 135 | 0.9.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 1.7 |
|
||||
| 5 | 0.9.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.6 |
|
||||
| 291 | 0.9.0 | | owner | **Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.** | 1 | 2 | 3 | 4 | 1 | 1.2 by 3 | 1.4 |
|
||||
| 156 | 0.9.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.4 |
|
||||
| 196 | 0.9.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and, where a run qualifies a rung, add back the code that lowers a pass to it.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 260 | 0.9.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.3 |
|
||||
| 51 | 0.9.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.3 |
|
||||
| 201 | 0.9.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.3 |
|
||||
| 267 | 0.9.0 | | | **Keep waiting when an interrupt gets an empty answer, at the terminal or in the claude opened for it, in place of stopping the loop.** | 2 | 1 | 3 | 4 | 2 | 1.5 by 3 | 1.3 |
|
||||
| 4 | 0.9.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 1.3 |
|
||||
| 187 | 0.9.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 266 | 0.9.0 | | | **Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.** | 3 | 2 | 2 | 5 | 3 | 1.4 by 3 | 1.2 |
|
||||
| 181 | 0.9.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 192 | 0.9.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 193 | 0.9.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 194 | 0.9.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 202 | 0.9.0 | | | **Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 1.0 |
|
||||
| 265 | 0.9.0 | | | **Archive each wait that costs a chunk wall time, for a usage limit, low memory, a failed worker start or a heavy slot, with its start and end stamps, so goal 1.5's hours split waiting from work.** | 3 | 2 | 2 | 5 | 4 | 1.5 by 3 | 1.0 |
|
||||
| 169 | 0.9.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 0.8 |
|
||||
| 174 | 0.9.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 1 | 1.1 by 1 | 0.5 |
|
||||
| 197 | 0.9.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 2 | 2 | 3 | 5 | 2 | 1.5 by 1 | 0.4 |
|
||||
| 1 | 0.10.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
|
||||
|
||||
## Details
|
||||
|
||||
### 277. Map the size of the code an item names onto S, on a scale the human picks, and have `score-outcomes` print that S for the item being scored and for each finished item it lists.
|
||||
### 294. Check the files a commit stages against rule-hook's file rules, so a file a Bash command wrote is held to them as an Edit or Write is.
|
||||
|
||||
Item 113 shipped the figure: beside each finished item it lists, `score-outcomes` prints how many tracked files the item's tagline or detail names in backticks, as full paths from the repo root with a folder counting the files it holds, and how many lines they held before its chunk. It maps nothing onto S's 1 to 10 scale, prints nothing for the item being scored, and counts a unit named without its file, such as a function, as nothing.
|
||||
From 2026-11-08 to 2026-11-10, workers in other projects wrote 1,266 files through Bash (a python heredoc, `sed -i`, `cat >`) against 260 through Edit and Write, and `rule-hook --help` says it doesn't check a file a Bash command writes. So `action-pin`, `image-pin`, `ignorefile-sorted` and the attribution check miss most edits. rule-hook already checks at `git commit` for `todo-rank-check`, so checking staged files there follows a pattern the repo has. Ship item 192 in the same chunk: its unsorted `.gitignore` block is one symptom of this gap.
|
||||
|
||||
Question for the human: which scale maps named lines to S? No published scale maps lines to S, so the threshold is yours (`CLAUDE.md` → "Web research"). One option, from this repo's data: give the S whose finished items' median lines changed sits nearest the named lines. On 2026-11-08 those medians were S 1 → 11, 2 → 36, 3 → 83, 4 → 219, 5 → 370, 6 → 848. A named file's size bounds a change only loosely: item 84 named files holding 2422 lines and changed 227, and item 132 named 385 and changed 2.
|
||||
### 297. Have loop-claude compute the judge's taken-in items, release-ready and escalation fields from `chunk-preflight`, git and the worker's structured lines, and leave the judge only the verdict kind.
|
||||
|
||||
Find units named without their file too, such as a function in backticks, and count the lines of the file that defines each. Once `score-outcomes` prints the S, point `~/.claude/rules/todo-items.md`'s S rule (→ "Score L, E and I against the project's anchors") at it, so a scorer sets S from the figure.
|
||||
`bin/loop_claude/cycle/judge.py` already checks quotes in code (`quotes_checked`, `grounded`, `re_ask_checked`). The `Reply` fields `items_taken_in`, `release_ready` and `escalation` state facts the plan and git already hold, so code can derive them with certainty, and the judge's prompt shrinks to what needs judgement. Before switching, recompute each field for the 668 archived verdicts offline and count where code and judge disagree; read each disagreement and keep the judge for a field where code is wrong. Seats found `quotes_checked` hard to read (PR #397's scoring run: the misquote rule is split across `judge.py` and `escalation_mark.py`); make it easier to read where the change touches it.
|
||||
|
||||
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
|
||||
### 302. Call a scoring run for an item whose tagline makes the comprehension floor its target, and not for one that only names the floor, such as in a quoted decision title.
|
||||
|
||||
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
|
||||
`bin/larv_review/scoring.py` sets `FLOOR_ITEM = "comprehension floor"` (line 7) and tests it as a substring of the tagline at line 35 and in `bin/larv_review/plan.py:28`. So any item whose tagline holds those words counts as a floor item. Item 301's tagline quoted the title of the decision "comprehension floor: …", so its chunk was due a scoring run it did not need. The deployed `chunk-pr` (release 0.7.0) did not refuse the merge, so it merged without one, and the run was recorded late, in PR #476.
|
||||
|
||||
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed; do not remind them. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
|
||||
Recommendation: a floor item's tagline opens with one fixed phrase, `Reach the comprehension floor:`, and both checks test that the tagline, with its leading `**` stripped, starts with it, in place of the substring test. Reason: a quoted title or a passing mention never sits at a tagline's start, so the check needs no parsing and keeps one constant. An Exempt reason such as `floor` was the alternative; it would change `rank_todo.py`'s schema and every project's table for the same effect.
|
||||
|
||||
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3).
|
||||
The same chunk names the phrase where a floor item is filed: `skills/larv-review/SKILL.md` → "Floor item", the `Next:` lines `floor_step` prints, and `larv-review --help` (`bin/larv_review/main.py`, lines 35 and 89). It rewords open floor item 300's tagline to open with the phrase, and updates the tests in `bin/larv_review/test_larv_review.py` that use floor taglines (lines 120, 361, 435, 537), adding one where a tagline quotes the floor mid-sentence and is due no run.
|
||||
|
||||
### 290. Have `rule-hook overrides` read the branch's reflog when a file or folder shares the branch's name.
|
||||
### 293. Run mutation tests on a chunk's changed lines in the worker's pre-review gate, through one command that picks the tool by language, and hand stability-reviewer the surviving mutants.
|
||||
|
||||
`bin/rule_hook/override_log.py:98` runs `git reflog show --format=%H <branch>` without a `--` after the branch. When a tracked path has the branch's name, git stops with "ambiguous argument … both revision and filename", and `rule-hook overrides` exits saying it cannot tell which overrides are the chunk's. larv-review's Overrides pass then has no list to judge, so an override in such a chunk would go unreviewed. Found on 2026-11-09 in PR #456, whose branch and new folder were both `reviewer-merge-trials`. Fix by passing `--` after the branch, and test it with a branch named after a tracked folder.
|
||||
Of stability-reviewer's 428 round-1 findings from 2026-11-02 to 2026-11-10, 223 (52%) were test gaps, such as a surviving mutant or an unpinned boundary, and 31 of its 50 round 2s held one. 133 of its 144 reports ran mutation tests by hand: today the reviewer picks and runs mutmut, Stryker, cargo-mutants or Infection itself, per `agents/stability-reviewer.md` step 5. A command run once before review, on the lines the branch changed, finds the same survivors deterministically, so the worker kills them before review and the reviewer judges only what remains. This takes over the stability half of item 270. Ship it alone: the nearest finished items, 227, 210, 180 and 73, changed 261 to 402 lines and took 3 to 8 rounds past the first.
|
||||
|
||||
### 286. Lower the reading cost of the files a chunk reads most before its first commit.
|
||||
### 284. Script each step that 0.7.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
|
||||
|
||||
`reading-cost` reports Rising: the last five chunks' median is 151,930 new input tokens before the first commit, against 103,215 for the five before them. Those five chunks opened or searched these files most: `todo.md` 42 times, `README.md` 16, `docs/decisions.md` 12, `AGENTS.md` 10, `bin/rank_todo.py` 9, `bin/release_plan/ranking.py` 8, `docs/reading-cost.md` 8, `CHANGELOG.md` 7, `rules/todo-items.md` 7 and `bin/rule_hook/test_rule_hook.py` 6.
|
||||
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). This audit reads the archived transcripts of the chunks that shipped release 0.7.0 for every step that chunks repeated by hand, before, during or after review. It keeps the steps whose answer a program computes the same way each time, such as a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model. Run item 283's tool first, once it has shipped.
|
||||
|
||||
Item 285 removed the `todo.md` reads for a joining item's detail; the rest are for edits. Find why a worker opens each of them before its first commit, and cut that cause, such as a test file too large to read in parts.
|
||||
The chunk that ships this item files a copy of this audit in the release after this item's own, to audit this item's release, rewording "0.7.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it.
|
||||
|
||||
### 270. Move each check a review pass repeats across chunks, other than the mutation tests item 293 moves, into the worker's pre-review gate, starting with the passes most often taken to a second round.
|
||||
|
||||
The review folders under `~/.local/state/larv-review/`, review replays left out, hold a stability round 2 beside 137 of 211 round-1 reports (65%), product-owner 73 of 173 (42%) and prose 8 of 277 (3%), on 2026-11-08. The architecture and principles passes run up to five rounds in a release review, so they don't compare. From 2026-11-02 to 2026-11-10, 223 of stability's 428 round-1 findings (52%) were test gaps, and 31 of its 50 round 2s held one; item 293 moves the mutation tests that find most of them. Check which kinds of finding the other round 2s repeat, such as an unhandled error or a product-owner wording fix. Move only a check a program or the worker can run before review; leave judgement with the reviewer.
|
||||
|
||||
### 292. Rebuild the routing ladder for Fable 5.2, placing each of its efforts by the Artificial Analysis Intelligence Index beside Opus 5.5's and Sonnet 5.5's, and replace Fable 5.1 wherever it is named.
|
||||
|
||||
Fable 5.2 (`claude-fable-5-2`) has been released. The ladder in `bin/model_routing/ladder.py` tops out at `Rung("claude-fable-5-1", "max")`, and the decision `routing: one ladder of (model, effort) rungs` holds "while no newer model joins the catalog", so it is due for a rebuild.
|
||||
|
||||
Read the index again (https://artificialanalysis.ai/leaderboards/models), at each effort it scores, with its cost per task. Rebuild the ladder by the decision's cut: a rung stays only where no cheaper rung scores as high. Fable 5.2 may earn more than one rung, and a cheaper effort of it may push an Opus 5.5 rung off. Where the order changes which rung a project's model starts on, or how far the L and E + I steps reach, say so in the decision. The rungs are the human's choice (`CLAUDE.md` → "Working loop", "Ask, don't guess"), so propose the new ladder with the index's figures and get the human's approval before changing code.
|
||||
|
||||
Then replace `claude-fable-5-1` where it is named: `ladder.py`, `bin/routing_figures/prices.py` (Fable 5.2's prices), `settings.json` → `modelSettings`, the tests in `bin/model_routing/`, `bin/loop_claude/`, `bin/judge_replay/` and `bin/rule_hook/`, `AGENTS.md`, `docs/decisions.md` and `presentation/index.html`. Keep Fable 5.1 in `prices.py` while archived chunks that ran on it are still priced from there.
|
||||
|
||||
### 295. Have `chunk-pr merge` wait for the forge's required checks itself, and give workers one command that waits for a background log or report file.
|
||||
|
||||
In 0.7.0's 35 chunks, workers made 65 `tea api` calls in 26 chunks, mostly polling commit status and trying merge methods in turn, and ran 25 `until … sleep` loops that took 1,744 seconds. `chunk-pr merge` takes `--gate-passed` on the worker's word; waiting for the required checks itself makes that flag a fact, not a claim. This is the kind of step item 284 files, and can count as its first.
|
||||
|
||||
### 299. Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.
|
||||
|
||||
The judge's verdict kind is the one judge decision that item 297 leaves an LLM. No single rule found so far separates interrupts: a "?" in the worker's final message appears in 48 interrupts and misses 66. A smaller LLM already failed the replay (`docs/decisions.md` → `routing: on a model judge-replay covered, …`: Sonnet returned another kind on 3 interrupts, Haiku missed 7). Untested are combined code rules, a decision table, and a small classifier trained and run on this machine on the archived verdicts (372 finished, 234 interrupt, 42 unfinished, 20 quoted). Run each offline, nothing sent to an outside service (goal 4), and count disagreements by kind; the bar is zero missed interrupts. A hosted decision model is out of scope, since it would send transcripts to an outside service.
|
||||
|
||||
### 298. Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.
|
||||
|
||||
153 `Judge cost:` entries total $109.76, a median of about $0.76 a verdict at every rung, and the cost follows the size of the records, not the transcript: about 76k characters in log and 188k in claude-config. In 224 of 251 recent verdicts (89%) the evidence sits in the worker's final message. A missed interrupt is the costly error, so the bar is zero changed interrupts and zero new rejections across the replay. It waits for item 297, which moves the judge's factual fields into code, since that shrinks the prompt first and changes what this cut measures. The judge is about 4.5% of dollars, so the saving is small; each cycle also gets faster.
|
||||
|
||||
### 287. Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at` and `gitea` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.
|
||||
|
||||
@@ -87,13 +116,7 @@ Today the helpers live in two tools. `Forge` is defined in `bin/chunk_preflight/
|
||||
|
||||
Both comprehension seats of PR #453's paired ruling (2026-11-09) named this web as a place that cost them time, and neither saw a reason for it: a second forge would need edits in `chunk_preflight`, `deploy_release`, `chunk_pr` and `larv_review`.
|
||||
|
||||
Put the five helpers in a folder named by what it holds, such as `bin/forge/`, and import them from there. Keep each helper's behaviour and its tests. `chunk_preflight/choices.py` keeps `pulls_command`, which is preflight's own. Check `AGENTS.md` and `docs/decisions.md` for a mention of where a helper lives, and update it.
|
||||
|
||||
### 284. Script each step that 0.7.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
|
||||
|
||||
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). This audit reads the archived transcripts of the chunks that shipped release 0.7.0 for every step that chunks repeated by hand, before, during or after review. It keeps the steps whose answer a program computes the same way each time, such as a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model. Run item 283's tool first, once it has shipped.
|
||||
|
||||
The chunk that ships this item files a copy of this audit in the release after this item's own, to audit this item's release, rewording "0.7.0" to the release that copy audits, and marks the copy `owner`, so the audit recurs each release until lilleman drops it.
|
||||
Put the seven helpers in a folder named by what it holds, such as `bin/forge/`, and import them from there. Keep each helper's behaviour and its tests. `chunk_preflight/choices.py` keeps `pulls_command`, which is preflight's own. Check `AGENTS.md` and `docs/decisions.md` for a mention of where a helper lives, and update it.
|
||||
|
||||
### 288. Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.
|
||||
|
||||
@@ -133,17 +156,56 @@ Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run t
|
||||
|
||||
`docs/decisions.md` → `routing: one ladder…` records why lilleman kept the steps on 2026-11-08. Of the 36 chunks it measured, 1 scored an E + I of 6 or more and none 7 or more, so the steps for 6 to 8 are untested. Start once `score-outcomes` shows 10 finished chunks with an E + I of 6 or more. Then read its rank correlation for E + I, and the routed-chunks table of `routing-figures.md` in loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Propose new steps to lilleman, whose call they are.
|
||||
|
||||
### 268. End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.
|
||||
|
||||
On 2026-11-08 the human answered notice only: the loop prints that the release is ready to cut and ends; no interrupt, and nothing waits in loop-inbox.
|
||||
|
||||
Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the loop once a release is ready to cut, so the ask settles nothing. 15 interrupts in the archive ask whether the human will cut a release, and about 6 of the 45 interrupts from 2026-11-02 to 2026-11-10 said a release was ready to cut; log's 2.5.0 was asked twice within an hour on 2026-11-10. On 2026-11-08 one of the 4 questions waiting in `~/.local/state/loop-claude/` is such an ask, plainpages-plugin-fastjira's 0.3.0 since 2026-11-03. Today a release ready to cut opens claude's session at once (`bin/loop_claude/cycle/run.py` `ask`), and the loop stops if the human leaves it with nothing typed. The change also touches what an interrupt covers in `CLAUDE.md` → "Vocabulary". Where the change touches `ask`, make it easier to read, as the seats named it.
|
||||
|
||||
### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.
|
||||
|
||||
Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
|
||||
|
||||
### 300. Restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first: today the comprehension floor run at 52da15e scored Locality 6.00, Shape 6.25, Self-sufficiency 6.38 and Overall 6.38.
|
||||
|
||||
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the run of PR #475 at 52da15e. The lowest mean is Locality, 6.00. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
|
||||
|
||||
Aim: one ambitious refactor of the areas below, sized so every mean reaches 7.0 on the chunk's own scoring run. Where a place is already easier to read when the chunk starts, drop it.
|
||||
|
||||
Places the seats named, hardest first (`larv-review places`):
|
||||
|
||||
- Locality, Shape: `bin/loop_claude/routing.py:93` `unfinished_route`: the floor rung, the escalation cap, the escalation mark, the unfinished count and the taken-in E + I are held at once, across about six helpers in five files. The mark's meaning lives in `escalation_mark.py`, and the reason for the floor and the cap sits in the decision log.
|
||||
- Locality, Shape: `bin/release_plan/release_standing.py:145` `next_release`: the tag, changelog, before-first-release and renamed branches meet in the `is_earliest` expression, which took a senior three reads. Nothing comments the `None` and `nothing_cut` case.
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:211` `quotes_checked`: the judge's contract is split over prose constants, schema descriptions and checks after the fact. A bad quote silently changes the verdict's type.
|
||||
- Locality, Shape: `bin/loop_claude/cycle/run.py:146` `rule`, with `loop/close.py:18` `closed_cycle`: the order of the ruling, rejection and step-up archive writes carries meaning, and nothing enforces it. Four near-identical archive helpers, `run.py:86` `archived` among them, sit in the cycle runner though `loop/close.py` imports them, and `run_cycle` replaces the route partway through its loop.
|
||||
- Locality, Self-sufficiency: `bin/larv_review/reviewer_header.py:49` `unanswered_round` and `skills/larv-review/SKILL.md:76` "Round cap": the cap counts answer commits, so a worker that relaunches without committing gets the same round number. The cap is enforced in four units, split over SKILL.md and three modules.
|
||||
- Locality, Shape: `bin/larv_review/plan.py:66` `plan_reasons`: a merge-base commit enters the parameter that item 296's chunk renamed `ref`, eight failure branches mix git reads, file reads and logic, and `after` means the checkout's text and then its items.
|
||||
- Locality: `bin/larv_review/owed.py:37` `shortfall`: the one-run-or-two rule is keyed on the wording `EMPTIED_WORDS` that plan.py builds and SKILL.md quotes, and `scoring_runs` defines a scoring run differently from `Entry.scored`. Give the scoring-run logic one module, and have the number of runs owed come from a value, not from a sentence.
|
||||
- Locality: `bin/chunk_pr/main.py:42` `forge`: the forge helpers live in `chunk_preflight` and `deploy_release`, so a second forge needs edits in four packages.
|
||||
- Locality: `bin/rule_hook/reviewer_rung.py:40` `skill_breaches`: three cases rest on assumptions made in another function.
|
||||
- Locality: `bin/rule_hook/repeat_read.py:119` `shown_lines`: it rebuilds from transcript entries which lines are in the agent's context.
|
||||
- Locality: `bin/model_routing/route.py:88` `route_of`: a route has two serializations, a flat archive line and a nested handover.
|
||||
- Self-sufficiency, Locality: `bin/loop_claude/cycle/prompts.py:59` `review_launches` and `:119` `escalation`: the worker's prompt is built from about 20 conditional sentence builders, which restate the routing logic.
|
||||
- Shape: `bin/release_plan/ranking.py:56` `rank`, `:304` `score` and `:315` `weight_of`: nearly every function forks on `SHAPE` versus `OLD_SHAPE`, which doubles the module; item 156 removes the old shape. The constants read as magic until `rules/todo-items.md` is open.
|
||||
- Shape: `bin/review_rules/comprehension_history.py:127` `entries`: a line-by-line parser that tolerates two legacy formats.
|
||||
- Shape: `bin/records/__init__.py:1` `records`: one name for three concepts, as `cut` and `Plan` also name several.
|
||||
- Shape: `bin/rule_hook/rules.py:25` `RULES`: rules sit inline in one module while five others have a module each.
|
||||
- Navigation, Shape: `README.md:116` `bin/`: about 55 entries in one flat list, some 31 of them packages, the worst fan-out level.
|
||||
- Self-sufficiency: `skills/larv-review/SKILL.md:147` "Scoring run": dense rule prose with many cross-references; three sections rebuild one rule.
|
||||
|
||||
Scored L 4 because the refactor touches several components that hold known defects, E 2 because review and a manual check see a regression, I 3 because every session runs these tools. The chunk runs a scoring run, since its tagline names the comprehension floor.
|
||||
|
||||
### 264. Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.
|
||||
|
||||
Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. By 2026-11-10 general-purpose was the second-largest spend, $585 of about $2,385, and by transcript size about two thirds of it were seats (291 launches), then 177 security passes. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/chunk.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with.
|
||||
|
||||
### 149. Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.
|
||||
|
||||
A release's capacity is a sum of its items' cost, as the formula counts it. Each project states its own; the human sets the first value per project. Nothing is deleted by score.
|
||||
|
||||
### 165. Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.
|
||||
|
||||
A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: `bin/loop_claude/test_loop_claude.py:165`, `:271` and most asserts in `:664` to `:687` pin whole sentences of the question, archive or prompt text, up to about 750 characters, and `:864` asserts help-text wording. `:906` and `:936` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py:16` asserts `len(LADDER) == 11`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills.
|
||||
A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: many tests in `bin/loop_claude/test_loop_claude.py` pin whole sentences of the question, archive, prompt or help text, up to about 750 characters. `test_every_exit_1_stop_has_its_clause_in_help` and `test_every_failed_judge_run_has_its_clause_in_help` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py` asserts `len(LADDER) == 6`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills.
|
||||
|
||||
### 151. Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.
|
||||
|
||||
@@ -157,22 +219,24 @@ The tests also cover `workflow-bench/bench.py`'s `permission_flags`, with a prob
|
||||
|
||||
### 102. Give loop-claude's retry delay, and the file it reads the machine's memory from, environment overrides, so the black-box test stops replacing `time.sleep` and `machine_load.memory.MEMINFO` through `sitecustomize`.
|
||||
|
||||
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:117-118` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans, and the audit of PR #376 found the same block swapping `machine_load.memory.MEMINFO` at lines 120-123. An override of each lets the test run the code as production runs it.
|
||||
Found by the principles audit of PR #242. The `SITECUSTOMIZE` block in `bin/loop_claude/test_black_box.py` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans, and the audit of PR #376 found the same block swapping `machine_load.memory.MEMINFO`, the constant in `bin/machine_load/memory.py`. An override of each lets the test run the code as production runs it.
|
||||
|
||||
### 135. Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.
|
||||
|
||||
The maintainability senior and the inherited architect of PR #257's scoring run named `bin/loop_claude/loop/reload.py:38` `fingerprint` and `:50` `exec_if_edited`: the fingerprint covers every `bin/**/*.py`, so editing `statusline.py` or `rank_todo.py` re-execs a running loop. Make `fingerprint` easier to read.
|
||||
|
||||
### 270. Compare each review pass's share of chunks that go to a second round, and move each check stability repeats across chunks into the worker's pre-review gate.
|
||||
|
||||
Weak evidence: the review folders under `~/.local/state/larv-review/`, review replays left out, hold a stability round 2 beside 137 of 211 round-1 reports (65%), product-owner 73 of 173 (42%) and prose 8 of 277 (3%), on 2026-11-08. The architecture and principles passes run up to five rounds in a release review, so they don't compare. First check whether stability's round 2s repeat the same kinds of finding, such as a missing test or an unhandled error. Move only a check a program or the worker can run before review; leave judgement with the reviewer.
|
||||
The maintainability senior and the inherited architect of PR #257's scoring run named `fingerprint` and `exec_if_edited` in `bin/loop_claude/loop/reload.py`: the fingerprint covers every `bin/**/*.py`, so editing `statusline.py` or `rank_todo.py` re-execs a running loop. Make `fingerprint` easier to read.
|
||||
|
||||
### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key.
|
||||
|
||||
The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
|
||||
The key names the project's session, archive folder and models entry. `project_key`, in `bin/transcript_archive/project_key.py`, strips `~/code/` and then any leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
|
||||
|
||||
`bin/reading-cost` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading-cost` never looks. Derive both keys one way.
|
||||
|
||||
### 291. Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.
|
||||
|
||||
"Sane defaults" has a library ask for every input that can change between runs, the clock and randomness included, and leaves defaulting them to the code that wires a program together. A logging library's principles audit found that its constructor defaults both, as its first goal, useful with no config, asks. Its decision log records the defaults as a departure from the principle, and names this item as what ends it. Until then, each principles audit there may raise the defaults again.
|
||||
|
||||
2026-11-10, the human: keep the library's defaults, and give the principle an exception for this case, worded about as the tagline says. The exception has to square with "Functional core, imperative shell", which the same bullet cites and no other principle overrides.
|
||||
|
||||
### 156. Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.
|
||||
|
||||
While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `bin/release_plan/ranking.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `ranking.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `ranking.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too.
|
||||
@@ -185,19 +249,9 @@ Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet
|
||||
|
||||
Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend.
|
||||
|
||||
### 269. Measure the judge's cost per rung from the `Judge cost:` lines once 20 chunks hold them, and file an item where an xhigh verdict costs more than the interrupts it avoids.
|
||||
|
||||
The `Judge cost:` line is new under `CHANGELOG.md` → "Unreleased", and no outcomes file in the archive holds one yet (2026-11-08). Of the 460 verdicts that name their judge, 48 ran on opus at xhigh, 78 at high and 310 at medium. In this repo the judge reads about 175k characters of records each time: `AGENTS.md`, `docs/decisions.md`, `CLAUDE.md`, `rules/` and larv-review's standards. `bin/routing_figures/dollars.py` already adds the lines to the dollars by rung.
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `first_answer`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
|
||||
### 268. End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.
|
||||
|
||||
On 2026-11-08 the human answered notice only: the loop prints that the release is ready to cut and ends; no interrupt, and nothing waits in loop-inbox.
|
||||
|
||||
Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the loop once a release is ready to cut, so the ask settles nothing. 15 interrupts in the archive ask whether the human will cut a release. On 2026-11-08 one of the 4 questions waiting in `~/.local/state/loop-claude/` is such an ask, plainpages-plugin-fastjira's 0.3.0 since 2026-11-03. Today a release ready to cut opens claude's session at once (`bin/loop_claude/cycle/run.py` `ask`), and the loop stops if the human leaves it with nothing typed. The change also touches what an interrupt covers in `CLAUDE.md` → "Vocabulary". Where the change touches `ask`, make it easier to read, as the seats named it.
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `say` and `input_or` in `bin/loop_effects/effects.py` take the effects but print to stderr or stdout themselves, and `retried` and the rest print through `say`. Two bare `print(file=sys.stderr)` calls remain outside them, in `bin/loop_claude/cycle/interrupt.py` and `bin/loop_claude/project/model_choice.py`. The tests swap the global stream.
|
||||
|
||||
### 201. Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.
|
||||
|
||||
@@ -223,17 +277,9 @@ Today the folder is the SHA-256 of the transcript's first timestamped line, whic
|
||||
|
||||
Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/chunk.py`), so neither sees the report reads. Found by the architecture review of PR #310.
|
||||
|
||||
### 264. Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.
|
||||
|
||||
Seats launch as `general-purpose`, so they hide inside that type: $301.24 of the $962.17 the figures of 2026-11-04 count, from 221 subagents. Escalations are counted by trigger only, never in dollars. `bin/routing_figures/chunk.py` groups subagents by their `subagent_type`; a seat is told apart by its prompt, and an escalated subagent by the escalation marker its prompt opens with.
|
||||
|
||||
### 266. Move the chunks archived under the key `home/lilleman/.claude` to the key `claude-config`, so the routing figures and `score-outcomes` count this repo's chunks as one project.
|
||||
|
||||
The archive holds 98 chunk folders under `home/lilleman/.claude`, from 2026-10-03 to 2026-10-29, and 4 under `claude-config`, from 2026-10-30 on. The routing figures of 2026-11-04 list no project `home/lilleman/.claude`. They find a chunk's later fixes on the default branch of the checkout its key names (`bin/routing_figures/archive.py` `measure_project`), and `/home/lilleman/.claude` is a release checkout on a detached HEAD. Item 5 fixes how keys are derived, not the chunks already archived. `~/.claude/loop-claude-models.json` still holds a `home/lilleman/.claude` entry; it is machine state outside the repo, so removing it is a one-off step on each machine, not part of the change.
|
||||
|
||||
### 52. Move this checkout out of Claude Code's own directory, or record why it stays, since Claude Code loads the checkout's `AGENTS.md` as the user's instructions into every project's sessions.
|
||||
|
||||
"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory. Claude Code also loads `~/.claude/AGENTS.md`, this checkout's decision titles, as the user's instructions into every session of every project, so a worker on another project reads this repo's decisions as if they held there. That cost about $25 of cache writes and reads at list prices since 2026-10-21: 10.7k characters, about 2.7k tokens, in each of 1,084 threads.
|
||||
The archive holds 277 chunk folders under `home/lilleman/.claude`, from 2026-09-24 on, and 39 under `claude-config` (2026-11-10). The routing figures of 2026-11-04 list no project `home/lilleman/.claude`. They find a chunk's later fixes on the default branch of the checkout its key names (`bin/routing_figures/archive.py` `measure_project`), and `/home/lilleman/.claude` is a release checkout on a detached HEAD. Item 5 fixes how keys are derived, not the chunks already archived. `~/.claude/loop-claude-models.json` still holds a `home/lilleman/.claude` entry; it is machine state outside the repo, so removing it is a one-off step on each machine, not part of the change.
|
||||
|
||||
### 181. Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.
|
||||
|
||||
@@ -241,7 +287,7 @@ The archive holds 98 chunk folders under `home/lilleman/.claude`, from 2026-10-0
|
||||
|
||||
### 192. Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.
|
||||
|
||||
Found by review of PR #317. `.gitignore:56-58` holds `!bin/rule-hook` above `!bin/routing_figures/` and `!bin/routing_figures/*.py`, but `o` sorts before `u`. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
|
||||
Found by review of PR #317. The block, `.gitignore:17-142` on 2026-11-10, is out of order in several places: `!bin/chunk-preflight` sits below `!bin/chunk_pr/`, and `!bin/loop-inbox` below `!bin/loop_claude/`, though `-` sorts before `_`. `LC_ALL=C sort -c` on the block names the first one. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
|
||||
|
||||
### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
@@ -249,7 +295,7 @@ Found by review of PR #317. `bin/release_plan/ranking.py`'s `readme_goals` write
|
||||
|
||||
### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.
|
||||
|
||||
Found by review of PR #317. `bin/loop_claude/test_black_box.py:569-575` sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it.
|
||||
Found by review of PR #317. The black-box test, `bin/loop_claude/test_black_box.py:609`, not the unit test of the same name in `test_loop_claude.py`, which runs on a fake clock, sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it.
|
||||
|
||||
### 202. Add `CLAUDE.md` → "Prose"'s rule "Write negations as people say them", with its examples, to `skills/larv-review/standards/prose.md`, so the prose reviewer holds prose to it.
|
||||
|
||||
@@ -269,4 +315,12 @@ 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. 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."
|
||||
`bin/loop_effects/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."
|
||||
|
||||
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
|
||||
|
||||
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
|
||||
|
||||
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed; do not remind them. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
|
||||
|
||||
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3).
|
||||
|
||||
Reference in New Issue
Block a user