Compare commits
355 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2a07feebec | |||
| 1675904826 | |||
| 25382189b9 | |||
| 5c51b99d81 | |||
| cabde05e91 | |||
| a76daf8bd3 | |||
| 8275715b69 | |||
| f06b8f213a | |||
| 24b91feef0 | |||
| 7ad78cd6e3 | |||
| 071cc7a957 | |||
| bcacdf991a | |||
| 96f0a3b5ab | |||
| 8d9a39de1c | |||
| 25997ba9ec | |||
| df8c20d4e6 | |||
| 8e8128f56f | |||
| e66df83a3a | |||
| c082bfe6ca | |||
| fea9dde5b6 | |||
| 0490233e24 | |||
| 6494a4bee6 | |||
| 2b86540183 | |||
| d282a90804 | |||
| fbd2e62e41 | |||
| babe339430 | |||
| f0ff379251 | |||
| 0c93614f4a | |||
| 0b77d12cb2 | |||
| 4ab3648cb4 | |||
| 50b18efc05 | |||
| 8e64d30fd8 | |||
| 690a7d4454 | |||
| ed72e284ca | |||
| 134a200fba | |||
| 717ee9e24e | |||
| 193ea2bb55 | |||
| 4a0de10690 | |||
| e1651179ee | |||
| 7ddcf4fe5a | |||
| c042551aaf | |||
| 064ce09dcc | |||
| d18ceec249 | |||
| 1a5cf15a60 | |||
| ff354a90a8 | |||
| 98653923ed | |||
| 7823c4374c | |||
| c424fa66ae | |||
| 62d57344d8 | |||
| 9d4d7ddc94 | |||
| af589aea9a | |||
| df510e967f | |||
| 4172e4024f | |||
| 767ebad8c9 | |||
| 90727721ea | |||
| 86e6c50195 | |||
| ed7f3eb949 | |||
| 2321f4930d | |||
| e2aca90c9c | |||
| b948064511 | |||
| f134c6dede | |||
| 0bdea65030 | |||
| 10dd5fb527 | |||
| db993f159e | |||
| 51f5f3be29 | |||
| f6e96da675 | |||
| 29b986ca42 | |||
| 4b0d5b52d5 | |||
| 9f6241fb86 | |||
| 3ce580cd70 | |||
| 6e0ef22d0b | |||
| e7493108fb | |||
| e383f28b7a | |||
| 37a412b80e | |||
| 9fea1d8286 | |||
| c7e49983f7 | |||
| d791905391 | |||
| 36d0cf8d33 | |||
| 6e144068fc | |||
| 953d0c4176 | |||
| 3e099d6802 | |||
| 77bac16247 | |||
| 452a0c4271 | |||
| 97b35f9def | |||
| 9bc2e423ed | |||
| 8a35412a0a | |||
| 0a47507756 | |||
| 45007d54f2 | |||
| 6f9155c1d0 | |||
| c134691c01 | |||
| c0d9207131 | |||
| 5b1f903471 | |||
| 539c639dac | |||
| b1bbc2490a | |||
| 05102dcd0b | |||
| 8fe0af5689 | |||
| 0fb8cc9da2 | |||
| a795da0593 | |||
| 2f6ff46f99 | |||
| 7de6b22bcc | |||
| 7aa58404e0 | |||
| 6fc228f665 | |||
| b1707086dc | |||
| 2f1dc048fc | |||
| e93fd75fbd | |||
| 21640bda34 | |||
| 978f60b4e0 | |||
| 9b0c70fb8a | |||
| 8f61a65ffb | |||
| 533b54c4bb | |||
| 538fbfc8a0 | |||
| deddb39d86 | |||
| 610cd63ba6 | |||
| 095340da78 | |||
| 43682c819a | |||
| 87a555b7cd | |||
| 4a6cad05ea | |||
| fd878353bc | |||
| 6ffe432dba | |||
| 0a0a2207c9 | |||
| 28b714d5ca | |||
| 2d60ab11bd | |||
| fa70eb2bfe | |||
| 9b4ddb1670 | |||
| 2ee9df2e07 | |||
| 89aae3030c | |||
| a212b4ef91 | |||
| 0bb6f54a3c | |||
| 0d85dd036e | |||
| 2d0d159517 | |||
| aef3a945e9 | |||
| 8b1ba3a133 | |||
| 10f10df3e9 | |||
| fd19b90f07 | |||
| 59697806ee | |||
| 36b38cc133 | |||
| dcf7f2a434 | |||
| 9dc52691af | |||
| f5f866c08d | |||
| d566e9ebae | |||
| 0e223be019 | |||
| bc2971e956 | |||
| c8be3a3181 | |||
| 5a8644c2f5 | |||
| 687ff858d3 | |||
| 7681c2b4c0 | |||
| d0619342c3 | |||
| 6bc1e9ac9c | |||
| 9f161ac87b | |||
| 6e6fb88d77 | |||
| 1723469017 | |||
| 01326f41c2 | |||
| 72b7149740 | |||
| 9debeb03cb | |||
| 2eae23fcd1 | |||
| ac9d107066 | |||
| 142959dfd3 | |||
| 0a9fe07084 | |||
| 326866e85b | |||
| 9f71b9aa91 | |||
| 40e8267152 | |||
| dcdb8b5868 | |||
| 9bcfaebb83 | |||
| 8bddfdc282 | |||
| 45439294ea | |||
| a9605317ab | |||
| 2f27e66f50 | |||
| bf78fedc54 | |||
| 74a4a90b10 | |||
| 33834d2b04 | |||
| fb22bc33db | |||
| 5df105033c | |||
| 93d413f5f3 | |||
| 77ab11e6af | |||
| 47bfac2cea | |||
| ad8515b811 | |||
| 9ebd06e748 | |||
| 60cb0dc851 | |||
| 00e0bc223d | |||
| bbb33f5f72 | |||
| 81894f5dac | |||
| 55f151b2c5 | |||
| 13dcef2c6e | |||
| e3cd8ae0cf | |||
| abf4f67ca8 | |||
| 192b36fada | |||
| 4d6926e790 | |||
| ba8a0df807 | |||
| 8a19e6f75f | |||
| 3409ab3d07 | |||
| a7fe878631 | |||
| d13c4fb0db | |||
| 45955a6c49 | |||
| 5e0ed821d6 | |||
| bc62ec4982 | |||
| 81a3372543 | |||
| e9da351e40 | |||
| 862a5cb91e | |||
| 4307240e8c | |||
| b00aa61a88 | |||
| b743228928 | |||
| 115b8a394f | |||
| ae29817dae | |||
| 6e12ee911e | |||
| 6a9af88aed | |||
| 2866b828bc | |||
| 4c552e0e58 | |||
| 9d243ac4bd | |||
| d0d41fc1d1 | |||
| d967219f7e | |||
| f7532827db | |||
| eb06202283 | |||
| a16f0e4625 | |||
| 1a81b55925 | |||
| f2149adc46 | |||
| 77bc635659 | |||
| c2d72c97c6 | |||
| f1d749e0f5 | |||
| b1f89a9952 | |||
| 382ebde51e | |||
| 29e055584c | |||
| 9fc1392bc8 | |||
| c583900199 | |||
| 6e171fe2c0 | |||
| 4d40cc81bc | |||
| 08855e8055 | |||
| 43e7e96b41 | |||
| 9014fd0a2c | |||
| 3927dc280c | |||
| 3ef47907d0 | |||
| d3fd16d4ed | |||
| f7b448ccbf | |||
| cd7926b5ad | |||
| 18d0bb6b6d | |||
| 365b0f82a6 | |||
| 720ffd58b6 | |||
| 9240cd68ea | |||
| 4f831316d2 | |||
| 865f5b0306 | |||
| fe975488ec | |||
| 0254e427f2 | |||
| 47a40757c3 | |||
| fc5e463594 | |||
| 0447f2e07a | |||
| 155dedcf5c | |||
| 312a8b590d | |||
| e9e130cb77 | |||
| f4a2ea823d | |||
| dd90d109fd | |||
| e68100b35e | |||
| 53459014a4 | |||
| 5ea156a67b | |||
| b1a90abff4 | |||
| e41f4e0979 | |||
| 71e2e0f893 | |||
| 488d9b0eee | |||
| 8602b8a7ee | |||
| 248e46f616 | |||
| d583f8d48c | |||
| f5afc7f6d3 | |||
| 058804bb13 | |||
| 592a6052fe | |||
| 1d2f3d14d2 | |||
| 2d3ec3a636 | |||
| 37df9b7805 | |||
| cde7720750 | |||
| b2aa02eb22 | |||
| 722dd5e451 | |||
| d371869f4a | |||
| 4193165c5d | |||
| 17fb0ac247 | |||
| 6ca9b4a2e7 | |||
| dd4bcbd1c4 | |||
| 084d763412 | |||
| d57727ec39 | |||
| 53e663c8f8 | |||
| d7806d0b16 | |||
| b086e7bf2a | |||
| b6548d32e6 | |||
| 6c059e0545 | |||
| f6f21fc38c | |||
| b7cadb328e | |||
| 14ed4f9cdc | |||
| 7daa3268da | |||
| 83171df2ce | |||
| 9b089d3c30 | |||
| 9d888c9e47 | |||
| 12e3d4ffa6 | |||
| 67e4b36dfd | |||
| c37c80297e | |||
| 69f05a8c3c | |||
| bb3eb4fac6 | |||
| 7c5af45aaf | |||
| 0c1e92943a | |||
| 6917092fd7 | |||
| 499b111071 | |||
| e83ed096c4 | |||
| dac60ccf7b | |||
| d6ff9e26b5 | |||
| 64a7242139 | |||
| 22265be7fd | |||
| 31edfe0c37 | |||
| efa98dae4a | |||
| c31f367771 | |||
| 3af346ef75 | |||
| 9bb27ce493 | |||
| 3833c91bc0 | |||
| d9b4939b99 | |||
| 27e61c4c9d | |||
| ba5fc55539 | |||
| 31e363a469 | |||
| debabc40fd | |||
| 44974bcd02 | |||
| ecff799cb6 | |||
| 15e22a79f3 | |||
| 48f795b1a3 | |||
| 243a9d872d | |||
| 946815a495 | |||
| 51faf71ecc | |||
| c64b3f362d | |||
| 7a7528fba8 | |||
| 8caf92dfbe | |||
| 4bcead0b89 | |||
| 2815b89589 | |||
| f41b549ff7 | |||
| ca6bce76ce | |||
| 0d706c7240 | |||
| 83cf3897a7 | |||
| 9accc68ec3 | |||
| b23bf4f9c3 | |||
| c36d7a2f9c | |||
| b46d5374ff | |||
| 172e72ae07 | |||
| d96e5c35ef | |||
| 34a623e261 | |||
| b569f638ac | |||
| 34c13f97cd | |||
| 2b2e18ec6d | |||
| 9abc5f4781 | |||
| 56b9077e4c | |||
| 78837aabc6 | |||
| 23fbf853d8 | |||
| 14736e8e6e | |||
| f2e239d111 | |||
| aa020f15f7 | |||
| a0458e0a2c | |||
| ea6300a432 | |||
| 5a0c3f47b9 | |||
| d66c0bb317 | |||
| cd76c1f511 | |||
| 4aa8eb9467 | |||
| 3bde9cd6dd | |||
| 2135afe8d7 | |||
| 008c187192 | |||
| 4fa114905a |
+21
-17
@@ -18,18 +18,21 @@
|
||||
!agents/
|
||||
!agents/*.md
|
||||
!bin/
|
||||
!bin/branch_chunks/
|
||||
!bin/branch_chunks/*.py
|
||||
!bin/chunk-preflight
|
||||
!bin/chunk_pick.py
|
||||
!bin/chunk_preflight/
|
||||
!bin/chunk_preflight/*.py
|
||||
!bin/claude_code/
|
||||
!bin/claude_code/*.py
|
||||
!bin/comprehension_history.py
|
||||
!bin/docker_command.py
|
||||
!bin/command_lines/
|
||||
!bin/command_lines/*.py
|
||||
!bin/deploy-release
|
||||
!bin/deploy_release/
|
||||
!bin/deploy_release/*.py
|
||||
!bin/failure.py
|
||||
!bin/file_writes.py
|
||||
!bin/git_command.py
|
||||
!bin/git_repo.py
|
||||
!bin/git_cli/
|
||||
!bin/git_cli/*.py
|
||||
!bin/judge-replay
|
||||
!bin/judge_replay/
|
||||
!bin/judge_replay/*.py
|
||||
@@ -40,53 +43,54 @@
|
||||
!bin/loop_claude/
|
||||
!bin/loop_claude/**/
|
||||
!bin/loop_claude/**/*.py
|
||||
!bin/loop-inbox
|
||||
!bin/loop_inbox/
|
||||
!bin/loop_inbox/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/markdown_text.py
|
||||
!bin/metric-bench
|
||||
!bin/metric_bench/
|
||||
!bin/metric_bench/*.py
|
||||
!bin/model_routing/
|
||||
!bin/model_routing/*.py
|
||||
!bin/project_key.py
|
||||
!bin/rank_todo.py
|
||||
!bin/reading-cost
|
||||
!bin/reading_cost/
|
||||
!bin/reading_cost/*.py
|
||||
!bin/records/
|
||||
!bin/records/*.py
|
||||
!bin/release_plan/
|
||||
!bin/release_plan/*.py
|
||||
!bin/repo_checks/
|
||||
!bin/repo_checks/*.py
|
||||
!bin/review-replay
|
||||
!bin/review_folder.py
|
||||
!bin/review_passes.py
|
||||
!bin/review_replay/
|
||||
!bin/review_replay/*.py
|
||||
!bin/round_titles.py
|
||||
!bin/rule-hook
|
||||
!bin/review_rules/
|
||||
!bin/review_rules/*.py
|
||||
!bin/routing_figures/
|
||||
!bin/routing_figures/*.py
|
||||
!bin/rule-hook
|
||||
!bin/rule_hook/
|
||||
!bin/rule_hook/*.py
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/run-heavy
|
||||
!bin/run_heavy/
|
||||
!bin/run_heavy/*.py
|
||||
!bin/run_heavy/path_entry/
|
||||
!bin/run_heavy/path_entry/docker
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/score-outcomes
|
||||
!bin/score_outcomes/
|
||||
!bin/score_outcomes/*.py
|
||||
!bin/settings_filter.py
|
||||
!bin/shell_command.py
|
||||
!bin/statusline.py
|
||||
!bin/subagent-rung
|
||||
!bin/subagent_rung/
|
||||
!bin/subagent_rung/*.py
|
||||
!bin/test_*.py
|
||||
!bin/todo_table.py
|
||||
!bin/transcript_archive/
|
||||
!bin/transcript_archive/*.py
|
||||
!bin/utc_stamp.py
|
||||
!docs/
|
||||
!docs/*.md
|
||||
!principles/
|
||||
|
||||
@@ -3,18 +3,22 @@
|
||||
Decisions live in `docs/decisions.md`:
|
||||
|
||||
- bin/: an outcome is an entry of a `.outcomes.md` file in loop-claude's archive, a record is a document tools or people keep entries in, and a place is what a comprehension seat names
|
||||
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
|
||||
- bin/: the tools and their tests run on the host's Python, with no container
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
- deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
|
||||
- deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's
|
||||
- larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
|
||||
- loop-claude: a `claude` that cannot start is a failed worker run, retried
|
||||
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
|
||||
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; it interrupts for a reserved choice those don't settle, or an ask that carries no recommendation
|
||||
- loop-claude: every claude it or loop-inbox opens on a terminal has `CLAUDE_CODE_SANDBOXED` set, so Claude Code skips its trust dialog, and neither tool writes `~/.claude.json`
|
||||
- loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes
|
||||
- loop-claude: every claude it starts bypasses permissions inside its sandbox
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
- loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` → "Compact instructions" says what the summary keeps
|
||||
- loop-inbox: a loop-claude lists itself while it runs, and its waiting question, as files per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question
|
||||
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
- machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together
|
||||
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
|
||||
@@ -22,21 +26,24 @@ Decisions live in `docs/decisions.md`:
|
||||
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
|
||||
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
|
||||
- review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
|
||||
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: a pass gets at most three rounds per chunk; instead of a fourth, the run asks the human
|
||||
- review: a comment is prose in any file; a branch changing only Markdown no agent follows runs only the prose pass and, for README or docs an outside reader lands on, the product-owner pass; plan rows a chunk files from a finding, re-scores or moves get no review
|
||||
- review: a fix for a 🔴 reruns the pass that found it, unless that pass is at its cap, and each pass whose row in `larv-review` §3's re-entry table the fix meets; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟡, a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: a pass gets at most two rounds per chunk, and the release review's architecture and principles passes five, with no more and no ask for more; the fixes answering a pass's last round merge once the gate passes
|
||||
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
|
||||
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
|
||||
- review: a project decision may suspend the comprehension check for the plan items it names
|
||||
- review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
|
||||
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker, never for the judge
|
||||
- review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
|
||||
- review: an ask no user answers leaves the PR unmerged
|
||||
- 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 comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, 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 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 premises chunk's whole review is the human's approval
|
||||
- review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
|
||||
- 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
|
||||
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
|
||||
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass or the branch changes only Markdown no agent follows, which reviews on the project's rung; the seats and the security pass always on the project's
|
||||
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
|
||||
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
|
||||
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
|
||||
@@ -45,7 +52,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
|
||||
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
|
||||
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
|
||||
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides one, and larv-review's overrides pass rules on each override before merge
|
||||
- rule-hook: a PreToolUse hook enforces each rule a program can check, a `# rule-override <rule>: <reason>` marker overrides any rule but those `rule-hook --help` marks as taking none, and larv-review's overrides pass rules on each override before merge
|
||||
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
|
||||
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
|
||||
- settings.json: each machine owns its model, and git's clean filter `bin/settings_filter.py` keeps it, and Claude Code's key order, out of every commit
|
||||
@@ -59,7 +66,7 @@ Decisions live in `docs/decisions.md`:
|
||||
## Working rules
|
||||
|
||||
- `routing-calls-raised.md` sits at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`). Each of its lines is a call or a `Reset`, with a stamp. A call is new when it is stamped after the latest `Reset` and after the latest stamp that `todo.md` or `docs/decisions.md` → `routing:` cites. When there are new calls, file one `todo.md` item to settle them, or refresh the item already filed. Its detail quotes those calls with their stamps, and the routed-chunks table of `routing-figures.md` beside it, never the project names its other tables hold. A change to the ladder, its steps or the delegation rule is the human's. The chunk that settles the calls cites the latest stamp it settled in `docs/decisions.md` → `routing:`, whatever the human decided, so they are not filed again. Once a chunk that changes the ladder, its steps or the delegation rule has merged, append `- <UTC time> Reset` to `routing-calls-raised.md`: the figures then count only chunks finished after it, and its calls may be raised again.
|
||||
- When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first: `git diff HEAD -- settings.json`, which shows staged changes too. An empty diff means only the model or the key order changed: `git add settings.json` takes the file off `git status`, with nothing to commit. When the diff holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
|
||||
- When `~/.claude/settings.json` has uncommitted changes, carry them into `~/code/claude-config` on a branch of their own and merge them through a PR: Claude Code writes that file from any session, and `deploy-release` refuses to move `~/.claude` until a release holds them. Read their diff first: `git -C ~/.claude diff HEAD -- settings.json`. An empty diff means only the model or the key order changed, which `deploy-release` takes as no change. When the diff holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`.
|
||||
|
||||
## Scoring run
|
||||
|
||||
@@ -69,4 +76,4 @@ The project values for `skills/comprehension-panel/seat-prompts.md`:
|
||||
- `{kind}`: a Claude Code configuration with an agent loop and review skills
|
||||
- `{domain}`: driving headless Claude Code sessions, agent review workflows
|
||||
- `{domain docs}`: the Claude Code documentation
|
||||
- `{3am question}`: a loop-claude run exits 1 overnight after the judge returned a verdict the loop rejected, or a larv-review run looped a reviewer a fourth time
|
||||
- `{3am question}`: a loop-claude run exits 1 overnight after the judge returned a verdict the loop rejected, or a larv-review run looped a reviewer a third time
|
||||
|
||||
+68
-1
@@ -2,12 +2,79 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `loop-claude` now interrupts you less. A worker takes its own recommendation on a choice no rule reserves for you, and records it, and the judge answers an ask that carries a recommendation by quoting the rule that says so. You are still asked about a goal, a release's planned items and its cut, a change to the routing ladder, and whatever another rule asks your approval for; `CLAUDE.md` → "Working loop", "Ask, don't guess" lists them.
|
||||
- This setup's own plan now ranks items by `Score = 100 * V / (2**S + 32)`, up from 8: F, a chunk's fixed cost, is 32, about one size-5 change, fitted to ten finished chunks' tokens, so small items rank lower against large ones. `docs/decisions.md` holds the fit.
|
||||
- `loop-claude` now keeps the cycle it last measured the routing figures at, and each routing call it raised, in `routing-state.json` at the archive's root, and reads them back from there in place of `routing-figures.md` and `routing-calls-raised.md`. The two markdown files hold what they held before. From them, loop-claude now reads only a `Reset` line in `routing-calls-raised.md`, which still resets the figures. The first loop to close a cycle after the upgrade measures the figures at once. If the figures still make a call raised since the latest reset, it puts that call to you once more.
|
||||
- `loop-claude` and the routing figures no longer read a `Worker:` line written as a sentence, as versions before 0.4.0 archived. A rerun routes a chunk whose archive still ends in one afresh, and the figures leave it out of the routed chunks and charge its dollars to a row named by the sentence.
|
||||
|
||||
## 0.6.0
|
||||
|
||||
- `deploy-release --cut`, run in `~/code/claude-config`, now cuts a release. Once the next release holds no item in `todo.md` and its release review has landed, it renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request: it opens the pull request, waits for its checks and merges it fast-forward only. Then it tags the merged commit, pushes the tag and moves `~/.claude` to it. Where a step fails it stops with git's or the forge's reason, and a rerun continues. Nobody can push to `main` on the remote any more, so the old manual steps under README → Release no longer work. Cut 0.6.0 itself from the clone, `~/code/claude-config/bin/deploy-release --cut`, since `~/.claude` still holds 0.5.0.
|
||||
- The routing figures now count what `loop-claude`'s judge costs. `loop-claude` archives each judge run's cost, from claude's reply, in a `Judge cost:` line beside the verdict or rejection, and `routing-figures.md` adds it to its dollars by project, rung and tool, and under the subagent type `judge`. Before, the judge's cost was left out. Chunks archived before this change, and a judge run that failed, add none.
|
||||
- In a repo with no tag, `chunk-preflight` now counts the newest version under a dated `CHANGELOG.md` heading, such as `## 0.0.1 - 2026-10-03`, as the last cut. A later release in `todo.md` reads as next, the unreleased commits are those after the commit that added that heading, and a `Release review of` commit counts only for a release after it. A heading without a date doesn't count, and a tag always wins. Before, such a repo was sent to review a release it had already cut.
|
||||
- `rule-hook` no longer hangs, or reads without end, on an Edit, MultiEdit or Write whose `file_path` is a FIFO or a device: it reads only a regular file.
|
||||
- A `loop-inbox` ask file now stores when the loop asked as an ISO UTC datetime, such as `2026-11-04T09:30:00Z`, in place of seconds since the epoch. Restart any `loop-inbox` running when you deploy: one started before doesn't list the new asks. A `loop-claude` running then reloads itself at its next cycle, and `loop-inbox` doesn't list a question it asks before that; answer such a question on the loop's terminal.
|
||||
- Each chunk's first worker prompt now holds a reading rule: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context. Where the 20 chunks after it take more review rounds, unfinished verdicts, findings, misread findings, dollars or hours than the 20 before, a later release drops it.
|
||||
- `rule-hook`'s `round-cap` now refuses a round commit whose title names no larv-review pass, such as `Answer architectur round 1:`. Before, a misspelled pass got a count of its own, so its rounds never reached the cap.
|
||||
- A routing call from `loop-claude`'s figures now opens claude in the setup's development clone, `~/code/claude-config`, not in `~/.claude`. Recording the answer there no longer leaves `~/.claude` with changes that stop `deploy-release` from moving it.
|
||||
- Where the default branch's tags cannot be read, `chunk-preflight` now says so, with git's reason, and that it cannot tell which release is next, and `loop-claude` routes the chunk on the project's rung. Before, both read such a branch as one with nothing cut, so `chunk-preflight` could report an empty plan where a release review was due.
|
||||
- A branch that changes `workflow-bench/run-prompt.md` or `compare-prompt.md` now counts as changing config, as a skill does: its reviewers run on the rung its items pick, not on the project's rung.
|
||||
- `deploy-release` now stops with git's own error where git cannot refresh the checkout's index. Before, it went on and could refuse with a wrong report of uncommitted changes.
|
||||
|
||||
## 0.5.0
|
||||
|
||||
- A bare run of `chunk-preflight` now only prints the facts. It no longer adds the worktree `<checkout>-item-<ID>` and the branch `item-<ID>`, or runs `reading-cost`, `larv-review places` and its other checks in that worktree. `chunk-preflight --worktree` does all that, and `loop-claude` now passes it. Before, every run that found an item added the worktree and branch, and you had to remove them after a run made only to read the facts.
|
||||
|
||||
## 0.4.1
|
||||
|
||||
- A release review now fixes the findings of its architecture and principles passes in the release it reviews. Before, it filed each one in `todo.md`, so the release held the drift the review had found. It files only three kinds of finding, each under the release being reviewed: one whose fix needs a human answer, marked `question`; one whose fix adds a feature; and one whose fix the five rounds cannot finish. Until each is done, the release isn't ready to cut.
|
||||
- In a repo with no tag yet, `chunk-preflight` now calls a release finished once `todo.md` files no item under it: its release review is due, and no later release's item is taken. Before, it lost sight of such a release.
|
||||
- In a run `loop-claude` started, `rule-hook` now refuses a `/security-review` or `/claude-security` Skill call that the worker makes in its own context on a rung below the project's. It also refuses one from any subagent whose prompt doesn't open with `You are the security pass for this chunk.`, since that subagent's rung is unchecked. The refusal says to invoke the skill from a subagent on the project's rung, its prompt opening with that sentence. Before, only an Agent call that launched the security pass was held to that rung.
|
||||
- `loop-claude` and `loop-inbox` no longer write `~/.claude.json`. Each claude they open on a terminal, for `/talk`, a release ready to cut or a routing call, now has `CLAUDE_CODE_SANDBOXED=1` set, so Claude Code skips its trust dialog. Before, they marked the checkout and each worktree trusted in that file, and a write Claude Code made at the same moment could be lost. Claude Code doesn't document the variable: where a version drops it, the trust dialog comes back.
|
||||
|
||||
## 0.4.0
|
||||
|
||||
- `~/.claude` now holds only a release, and this repo is developed in a clone, `~/code/claude-config`. A new tool, `deploy-release`, moves `~/.claude` to the newest `v*` tag and prints `CHANGELOG.md`'s section for each version it moved past. It refuses while a tracked file there has an uncommitted change the new tag doesn't hold, such as a hook Claude Code wrote into `settings.json`, or where the move would drop commits no release holds; a model picked with `/model` is no such change. To switch a machine over:
|
||||
1. Stop any `loop-claude` running in `~/.claude`, and finish or move its open chunk.
|
||||
2. Clone this repo to `~/code/claude-config`, and run `git config filter.settings.clean bin/settings_filter.py` there.
|
||||
3. Run `~/code/claude-config/bin/deploy-release`. Where `~/.claude` is on a branch, it refuses until a release holds that branch's commits.
|
||||
4. Run loop-claude for this repo from `~/code/claude-config`. It asks for the project's model, since the project is new to it.
|
||||
|
||||
- larv-review's architecture and principles passes now run only in a new release review: the chunk that runs once a release holds no item and changes are unreleased, before the release is ready to cut. Each reads the whole project, may refactor boldly and takes up to five rounds; their fixes take the stability, security, overrides and prose passes, two rounds each. No other chunk runs either pass, so a chunk that changes code no longer waits on the principles audit. Between releases, the product-owner pass now also reviews changes to routes, request and response shapes, events, webhooks, published file formats, CLI flags and exit codes, which the architecture trigger used to cover. The comprehension check's paired ruling moves to the release review too.
|
||||
- `chunk-preflight` now reports a release review due where it reported a release ready to cut, until a commit titled `Release review of <release>` follows the newest `v*` tag on the default branch. Open the review's branch with that commit.
|
||||
- rule-hook's `round-cap` and `larv-review round-count` allow the architecture and principles passes five rounds.
|
||||
|
||||
- Haiku 5.5 is off the routing ladder, which now runs from Sonnet 5.5 at high to Fable 5.1 at max. A Sonnet 5.5 project's L 1 and L 2 workers now run on Sonnet 5.5 at high, where they ran on Haiku 5.5 at max: such a chunk took more than two hours and 3.1 million output tokens on a README change. A review replay can now lower a pass only to Sonnet 5.5 at high. `subagent-rung`, `review-replay` and `judge-replay` treat Haiku 5.5 as a model off the ladder.
|
||||
- larv-review runs fewer reviews on changes that hold no code:
|
||||
- A fix for a 🟡 no longer reruns the pass that found it. Only a 🔴 fix does, with each pass whose re-entry row the fix meets.
|
||||
- A comment counts as prose in every file, config included, so a comment in a workflow or compose file fires only the prose pass. Markdown an agent follows counts as config: `CLAUDE.md`, `AGENTS.md`, and files under `agents/`, `principles/`, `rules/` or `skills/`.
|
||||
- A branch that changes only other Markdown, such as `README.md`, `docs/` and `todo.md`, runs the prose pass, and the product-owner pass where an outside reader lands on the change. Its reviewers run on the project's rung, whatever its items' E + I. loop-claude's prompt says so, and rule-hook's `reviewer-rung` allows it.
|
||||
- A `todo.md` row or detail that a chunk files from a finding, re-scores or moves between releases is no longer reviewed. The chunk that ships the item reads it.
|
||||
|
||||
- New tool `loop-inbox` lists the interrupts of every loop-claude on the machine, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines. Pick one to answer the question as on the loop's terminal, except that Enter alone goes back; `/talk` opens claude in loop-inbox's terminal. Of a pasted answer, only the first line is sent, and the rest is dropped. The loop takes the first answer, from its terminal or loop-inbox, so it works as before with no loop-inbox running. A loop that ends drops off the list, even one killed outright. A loop whose claude is already open, such as for a release ready to cut or the routing calls, is listed but answered in that claude. A loop asking for its project's model, as on a project's first run, asks on its own terminal only. Below the questions, loop-inbox lists every running loop, with the ID and tagline of each `todo.md` item its chunk takes. Link it onto `PATH` as README → Install shows.
|
||||
- Ctrl-C in a claude that `loop-claude` opens on its terminal, for `/talk`, a release ready to cut or the routing calls, now reaches only that claude. Before, it also stopped `loop-claude`, which closed that claude a quarter second later.
|
||||
- `reading-cost` now lists the files a chunk read in the worktree `chunk-preflight` made, `<checkout>-item-<ID>`. It listed none, since no transcript command names that worktree.
|
||||
- `larv-review ruling-base` now finds the last measured commit when run in a subfolder of a checkout. Before, it found no change to the comprehension history there and fell back to the merge base.
|
||||
- `score-outcomes` now counts each finished chunk's later fixes: the later chunks on the default branch that fixed code it shipped, each a defect that review let through. A later chunk counts where a change of it rewrites or removes lines that `git blame` traces to the earlier chunk: its whole change where it ships a `todo.md` item marked `defect` or `security`, or one of its round commits whose title counts both a 🔴 and a finding a reviewer marked `[misread]`. Each finished item shows the count beside its guessed scores, and a new list, after the misread findings, names the chunks that fixed each one, newest first. `routing-figures.md` shows the mean per rung, over the chunks whose later fixes are known, in a new column of the routed-chunks table. To find them, loop-claude now reads each archived project's checkout, and the figures name each project whose default branch it could not read.
|
||||
- `loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone.
|
||||
- larv-review now gives each review pass at most two rounds per chunk, where it gave three and then asked for more, and no longer asks: the fixes answering a pass's second round merge once the gate passes. rule-hook's new `round-cap` rule refuses a round commit that would take a pass past round 2, such as `Answer stability round 3: …`, and takes no override. It counts the pass's earlier round commits on the branch, so a third commit titled round 2 is refused too. `larv-review round-count` marks a pass at two rounds as at the cap.
|
||||
- rule-hook has a new rule, `repeat-read`, and now runs before each Read call too. It blocks a Read, or a Bash `cat`, `head` or `sed -n '<A>,<B>p'` of one file, when every line it asks for is already in the agent's context, and the block names those lines. The rule takes no override.
|
||||
- A line is in context when an earlier read's result in the agent's own transcript showed it since the last compaction, as the file holds it now. A subagent is judged on its own transcript, not its session's.
|
||||
- A read goes through when it asks for a line no earlier read showed, or one that changed since. A Bash output that Claude Code cut short shows no lines.
|
||||
- A Read also goes through until the agent has read the file with Read or written it with Edit, MultiEdit or Write, and again once the file changed after that. Edit, MultiEdit and Write refuse the file until then, and a Bash read does not count.
|
||||
- Where the context lacks lines the transcript shows, as after Claude Code cleared old tool results, `grep -n '' <file> | sed -n '<A>,<B>p'` reads them.
|
||||
- Install the latest stable Python, today 3.14, as `python3`: the tools and their tests no longer support 3.11 to 3.13. A full test run now takes about 29 s, where it took about 3.3 minutes. It runs once, on that Python, in four pytest-xdist workers, where it used to rerun the whole suite on 3.11.
|
||||
- `routing-figures.md` now reports dollars by project, subagent type, rung and tool, in place of tokens. Cache reads are included; the tokens left them out, though they were about a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across the messages of the worker and its subagents in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them.
|
||||
- larv-review's principles pass now launches one auditor per round, which checks the README's goals, code health and every principles file that applies, so it reads the project once per round. It used to launch one auditor for the goals with code health and one for each principles file, each reading the whole project. Its report is `principles-round-<n>.md`, like every other pass's.
|
||||
- A session running larv-review now enters the chunk's worktree with `EnterWorktree` before the first review pass, so `/security-review` and the full scan read the branch's diff. Run from the checkout root, they used to find it empty.
|
||||
- `loop-claude` now stops with exit 2 when the judge rules one chunk unfinished 6 cycles running, so a worker and a judge that disagree can no longer cycle unattended without end. Rerunning resumes the chunk and gives it 6 more cycles.
|
||||
- larv-review now launches a round's reviewers in up to three waves, each wave's reviewers in one message, in place of one reviewer at a time: first the architect, then the principles auditor with the security and overrides passes, then the stability, product-owner and prose passes. Each wave now lasts as long as its slowest reviewer, where a round used to last as long as all its reviewers one after another.
|
||||
- loop-claude's worker, and every subagent it launches, now run with a 200k auto-compact window, handed as `CLAUDE_CODE_AUTO_COMPACT_WINDOW`: Claude Code compacts their context at about 170k tokens, where it used to let it grow to about 967k. loop-claude's judge no longer reads a compaction summary as words you typed. `CLAUDE.md` has a new section, "Compact instructions", saying what a summary keeps.
|
||||
- On Linux, `run-heavy` now caps the memory of a container its command makes with `docker run` or `docker create`. A container that sets no limit gets a memory limit and a swap limit, both the slot's share: three quarters of the machine's memory, split across the heavy slots. A container that sets one of the two limits keeps it, and gets the other as large. This covers containers a project's own scripts start, which rule-hook can't see. A `docker compose` service, and a docker named by its full path, get no cap. rule-hook's `docker-run-memory` now lets a `docker run` under run-heavy pass.
|
||||
- rule-hook has a new rule, `docker-run-memory`. It blocks a `docker run` or `docker create` that lacks a memory limit or a swap limit, such as `--memory 4g --memory-swap 4g`, sized to what the work needs. `--memory-swap -1`, unlimited swap, counts as none. `CLAUDE.md` asks for the same limits on a container a script or a compose file starts, which rule-hook can't see. rule-hook's `run-heavy` rule also now reads docker's `--tlscacert`, `--tlscert`, `--tlskey` and buildx's `--builder` as options that take a value, and reads `docker container run` as a run: `docker --tlscacert ca.pem build .` was not blocked outside run-heavy before.
|
||||
- Reviewers now mark a 🔴 or 🟡 `[misread]` where it arose because the implementer misread code that had already shipped. A round's commit title now counts the marked findings, as in `Answer stability round 1: 1 🔴, 2 🟡 (1 misread); …`, and rule-hook's `round-title-counts` blocks a round title without that count. `score-outcomes` shows the count on each finished item, and lists it after the medians for each chunk whose round titles carry it, newest first. A chunk whose round titles predate this change reads as unknown.
|
||||
- Sessions running at once no longer starve the machine. A new tool, `run-heavy <command>`, runs a heavy command, such as a full gate, mutation tests, an e2e run or a `docker build`, once it holds one of the machine's heavy slots: one per 4 CPUs, shared by every session. `CLAUDE.md` has every session run its heavy commands under it, and rule-hook blocks a `docker build` or a mutation run outside it. loop-claude now waits to start a worker while less than a quarter of the machine's memory is available.
|
||||
- larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer <pass> round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning.
|
||||
- rule-hook now blocks a larv-review round commit titled past round 3, such as `Answer stability round 4: …`, unless a `round-cap` override quotes the human's yes.
|
||||
- loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did.
|
||||
- `loop-claude --help` now describes routing in two short paragraphs for the person running the loop. The rules it used to repeat are now stated once, in the code that enforces them.
|
||||
- loop-claude now archives the route on each `Worker:` line as a JSON record, such as `{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 12}`, and reads it back field by field. The line used to be a sentence, such as `claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5`, which loop-claude parsed back word for word: rewording the sentence in the code would have made every archived line unreadable, and a rerun would have routed the open chunk afresh. A rerun and the routing figures still read the sentences archived since loop-claude routed on L. A rerun that finds a `Worker:` line it can't read now says so on stderr. The judge's reply now names the levels the worker took in `highest_likelihood_taken_in` and `highest_escape_and_impact_taken_in`, in place of `bundled` and `bundled_escape_and_impact`.
|
||||
|
||||
@@ -7,12 +7,12 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
|
||||
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
|
||||
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
|
||||
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
|
||||
- **When the next release has no items left and work has landed towards it, it is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix lands, into that release; never start a later release's items or plan a new one.
|
||||
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
|
||||
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
|
||||
- **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
|
||||
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and the items that may join it; read further only what they leave out. Otherwise run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs.
|
||||
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
|
||||
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.
|
||||
- **Ask, don't guess.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.
|
||||
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it.
|
||||
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file under `~/.claude/principles/` only when the item changes it, a finding or a record you write names it, or you decline a finding.
|
||||
- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record.
|
||||
@@ -75,7 +75,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- Escalate a task that proves too hard for your rung. Four escalation triggers say so:
|
||||
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
|
||||
2. The same failing test or finding survives two fix attempts.
|
||||
3. A pass reports a 🔴 in round 2 or later.
|
||||
3. A pass reports a 🔴 in round 2.
|
||||
4. A review rules the work below standard: systems-architect's BLOCK, a finding against larv-review's `standards/quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up").
|
||||
|
||||
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
|
||||
@@ -104,12 +104,25 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- **A list or threshold a consumer relies on is sourced.** Deny-lists, defaults, limits: follow a published standard or a widely deployed tool, and cite it in the decision recording the choice; where none exists, ask. Never assemble one from names that seem plausible.
|
||||
- When a page renders client-side and comes back empty/blocked, use the Playwright renderer at `~/code/playwright-for-agents/` — `./pw <url> [options]` (see its README). Don't use claude-in-chrome for this.
|
||||
|
||||
## Compact instructions
|
||||
|
||||
Claude Code reads this section by its heading when it compacts a conversation. Keep in the summary:
|
||||
|
||||
- what remains before the chunk is finished;
|
||||
- the task loop-claude gave, and each `todo.md` item the chunk takes with its L and E + I;
|
||||
- the worktree, branch and PR;
|
||||
- the rung loop-claude named for each review launch, rerun and escalated subagent;
|
||||
- each review pass's rounds so far, each open 🔴 and 🟡, and how the answered ones were answered;
|
||||
- every question the human answered, with the answer;
|
||||
- each escalation trigger that fired;
|
||||
- for a reviewer or comprehension seat, every finding and place it has drafted.
|
||||
|
||||
## Vocabulary
|
||||
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md` or the judge's records.
|
||||
- **gate** — the merge gate: the checks a PR passes before it merges.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it. A release ready to cut opens that session at once, on loop-claude's terminal. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
|
||||
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
|
||||
- **judge's records** — the files the judge reads beside the README's premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
|
||||
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
|
||||
@@ -119,6 +132,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`, with code health ("Shared goal") first among the goals unless the README voids it.
|
||||
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
|
||||
- **release** — a semver version the human cuts.
|
||||
- **release review** — a release's last chunk: the architecture and principles passes over the whole project, before the release is ready to cut; `larv-review` §3 → "Release review".
|
||||
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
|
||||
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
|
||||
- **scoring run** — each seat scores the project from 1 to 10, overall and on each dimension. `larv-review` §3 → "Comprehension check" says which seats score and when one is due.
|
||||
|
||||
@@ -37,17 +37,20 @@ Me, on my own machines, which take tagged releases. Nobody else depends on it.
|
||||
|
||||
Take this checkout only onto a machine that is a sandbox with no direct access to a production environment, such as a dedicated VM: `settings.json` runs Claude Code in auto mode with the dangerous-mode prompt skipped.
|
||||
|
||||
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place:
|
||||
Each machine holds two checkouts. `~/.claude` is the one Claude Code reads, and it holds only a release: `deploy-release` moves it from tag to tag. Develop in a clone under `~/code`, where loop-claude runs this repo's chunks like any project's.
|
||||
|
||||
Claude Code may already have created `~/.claude`, where `git clone` refuses to run, so make the repository in place, then clone it for development:
|
||||
|
||||
```sh
|
||||
mkdir -p ~/.claude && cd ~/.claude
|
||||
git init
|
||||
git remote add origin ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git
|
||||
git fetch --tags origin
|
||||
git checkout -f "$(git tag -l 'v*' --sort=-v:refname | head -n 1)"
|
||||
git clone ssh://git@gitea.larvit.se:21022/lilleman/claude-config.git ~/code/claude-config
|
||||
```
|
||||
|
||||
Then run Update's commands, skipping `git add settings.json`: the new repository tracks no file yet.
|
||||
|
||||
Have Python 3.11 or newer as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
|
||||
Have the latest stable Python, today 3.14, as `python3` on `PATH`, and for Rust projects `rust-analyzer` on `PATH`, which the `rust-analyzer-lsp` plugin needs. Install every plugin `settings.json` enables:
|
||||
|
||||
```sh
|
||||
claude plugin marketplace add anthropics/claude-plugins-official
|
||||
@@ -56,7 +59,7 @@ claude plugin install code-review@claude-plugins-official
|
||||
claude plugin install rust-analyzer-lsp@claude-plugins-official
|
||||
```
|
||||
|
||||
Have git store `settings.json` without `"model"`, so a model you pick with `/model` stays on this machine and never reaches a commit:
|
||||
Have git store `settings.json` without `"model"`, so a model you pick with `/model` stays on this machine and never reaches a commit. Run this in each checkout, `~/.claude` and `~/code/claude-config`:
|
||||
|
||||
```sh
|
||||
git config filter.settings.clean bin/settings_filter.py
|
||||
@@ -64,53 +67,50 @@ git config filter.settings.clean bin/settings_filter.py
|
||||
|
||||
Then pick a model with `/model`.
|
||||
|
||||
After a pick, `git status` may list `settings.json`, and a `git pull` that changes the file refuses to run. `git add settings.json` stages no change and clears both. Once it is staged, such a pull goes through and drops the model: pick it again.
|
||||
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
|
||||
Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt.
|
||||
|
||||
## Update
|
||||
|
||||
Move a machine that takes tagged releases to the latest tag. The move discards every uncommitted change to a file the latest tag tracks, such as a hook Claude Code wrote into `settings.json`. Git counts a model pick as such a change until `git add settings.json`, so stage it first. List the uncommitted changes to files the checkout tracks, and the tag it is on:
|
||||
Move `~/.claude` to the newest release:
|
||||
|
||||
```sh
|
||||
cd ~/.claude
|
||||
git add settings.json
|
||||
git fetch --tags origin
|
||||
git status
|
||||
~/code/claude-config/bin/deploy-release
|
||||
```
|
||||
|
||||
To keep an uncommitted change, merge it per `AGENTS.md` → "Working rules" and cut a release ("Release") before moving: a machine gets only what a tag holds. Then move:
|
||||
|
||||
```sh
|
||||
git checkout -f "$(git tag -l 'v*' --sort=-v:refname | head -n 1)"
|
||||
```
|
||||
|
||||
Then, where the tag changed `settings.json`, pick the model again with `/model`, and do what `CHANGELOG.md` asks of each version since the old tag, such as a new step under Install.
|
||||
It refuses while a file `~/.claude` tracks has an uncommitted change, such as a hook Claude Code wrote into `settings.json`: merge that per `AGENTS.md` → "Working rules", then cut a release. A model picked with `/model` is no such change. It prints `CHANGELOG.md`'s section for each version it moved past: do what each asks, such as a new step under Install. `deploy-release --help` says what else it checks.
|
||||
|
||||
## Release
|
||||
|
||||
Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit `v<version>`, and push both.
|
||||
Once the next release holds no item in `todo.md` and its release review has landed, cut it from `~/code/claude-config`:
|
||||
|
||||
```sh
|
||||
bin/deploy-release --cut
|
||||
```
|
||||
|
||||
It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that through a pull request, since nobody can push to `main`. Then it tags the merged commit `v<version>`, pushes the tag, and moves this machine's `~/.claude` to it. Where a step fails it stops with the reason, and a rerun continues where it stopped. `deploy-release --help` lists the steps. Each other machine takes the release with Update.
|
||||
|
||||
## Tools
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
|
||||
Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`.
|
||||
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how.
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Bash, Edit, MultiEdit, Write and Agent call, and `rule-hook --help` states the rules and the override.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; then each chunk's 🔴 and 🟡 findings with how many a reviewer marked `[misread]`, code health's counter-signal; `score-outcomes --help` states the measures.
|
||||
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by, and code health's two counter-signals per chunk, misread findings and later fixes; `score-outcomes --help` states the report.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
|
||||
Test on the host, with `uv` on `PATH` to fetch mypy and the Python version Install names (`docs/decisions.md` → `bin/`): `python3 -m unittest discover -s bin -p 'test_*.py'`. Test the bench's git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
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 git wrapper with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
|
||||
To mutation-test a changed module, copy `bin/` to a scratch directory (`cp -r bin "$scratch"`): mutmut writes files beside its config. In the copy, name the module and its tests in a `setup.cfg`, as below for `score_outcomes/results.py`. Leave out each test class that starts a tool's launcher through `subprocess`: a mutated module fails to load in a process mutmut did not start.
|
||||
|
||||
@@ -123,9 +123,28 @@ pytest_add_cli_args=-k
|
||||
not ScoreOutcomesTool
|
||||
```
|
||||
|
||||
Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with pytest==9.2.0 'mutmut>=3,<4' results`, and `uvx --with pytest==9.2.0 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. 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 `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `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 `rank_todo.py`, `larv_review` and `rule_hook` 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
|
||||
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
---
|
||||
name: principles-auditor
|
||||
description: "Use this agent for larv-review's principles pass: one yardstick checked against the whole project."
|
||||
description: "Use this agent for larv-review's principles pass: the project's goals and every principles file handed to it, checked against the whole project."
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it.
|
||||
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under its `README.md` → `## Goals` with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, or one principles file, every principle in it.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
|
||||
|
||||
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
|
||||
- A departure a `todo.md` item plans away is named with that item, not raised.
|
||||
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason.
|
||||
- Report under one heading per yardstick.
|
||||
|
||||
@@ -35,4 +35,4 @@ The prompt hands you these. Beyond them, read only what a finding needs checking
|
||||
|
||||
1. **What the diff touched**: every markdown line, comment and printed text, such as help or an error, that the diff adds or changes.
|
||||
2. **What the review cited**: each section the prompt names, with the code it governs.
|
||||
3. **Every prose file the repo owns**, when the prompt says the architecture pass's trigger fired. This sweep catches files that grew a paragraph per chunk, which no single diff shows.
|
||||
3. **Every prose file the repo owns**, when the prompt says the chunk is a release review. This sweep catches files that grew a paragraph per chunk, which no single diff shows.
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from review_rules.comprehension_history import HISTORY
|
||||
from release_plan.todo_table import Item, items
|
||||
from reading_cost.figures import RECORD
|
||||
from records.utc_stamp import utc
|
||||
|
||||
# The plan, and the records tools append to: none of their lines are the chunk's work.
|
||||
NOT_WORK = ("todo.md", HISTORY, RECORD)
|
||||
# Each commit as its hash, commit and author times and parents, its short hash and title, then the files it changed; a merge's files are those it changed against its first parent. git refuses a NUL byte in a commit message, so a title can't split a record.
|
||||
LOG = ("log", "--format=%x00%H %ct %at %P%x1f%h%x1f%s", "--name-only", "--diff-merges=first-parent")
|
||||
# One commit's record in LOG's output, without the NUL that opens it.
|
||||
LOG_RECORD = re.compile(r"([0-9a-f]+) ([0-9]+) ([0-9]+) ([0-9a-f ]*)\x1f([0-9a-f]+)\x1f(.*)", re.DOTALL)
|
||||
# How a chunk reached the default branch; rebase and push leave no merge commit to bound it.
|
||||
Landing = typing.Literal["merge", "rebase", "push"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Commit:
|
||||
"""A commit as LOG prints it; committed and authored are its commit and author times, in seconds since the epoch."""
|
||||
hash: str
|
||||
short: str
|
||||
committed: int
|
||||
authored: int
|
||||
parents: tuple[str, ...]
|
||||
title: str
|
||||
files: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Span:
|
||||
"""A chunk on a default branch, as cut_branch cuts it. before is the commit its change starts from, None for the branch's oldest chunk; tip is its newest commit on the first-parent line. label names it as the reports do, landing says how it reached the branch, and merged is tip's commit time. titles are those of every commit it brought."""
|
||||
before: str | None
|
||||
tip: str
|
||||
label: str
|
||||
landing: Landing
|
||||
merged: str
|
||||
titles: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class BranchChunk(Span):
|
||||
"""A Span with two more fields: shipped holds each todo.md item its change removed, as scored before the change; fixed_by names the later chunks that fixed code it shipped, newest first."""
|
||||
shipped: tuple[Item, ...]
|
||||
fixed_by: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Branch:
|
||||
"""A default branch's commits by hash, its chunks newest first, and each commit's chunk as an index into chunks."""
|
||||
commits: dict[str, Commit]
|
||||
chunks: list[Span]
|
||||
owner: dict[str, int]
|
||||
|
||||
|
||||
def cut_branch(log: str) -> Branch | Failure:
|
||||
"""The branch LOG printed, cut into chunks as chunk_log cuts its first-parent line; a commit belongs to the oldest chunk whose commits reach it."""
|
||||
commits = parsed(log)
|
||||
if isinstance(commits, Failure):
|
||||
return commits
|
||||
if not commits:
|
||||
return Failure("git log printed no commit")
|
||||
# git log prints the commit it starts from first.
|
||||
line = [commits[next(iter(commits))]]
|
||||
while line[-1].parents:
|
||||
line.append(commits[line[-1].parents[0]])
|
||||
runs = chunk_log(line)
|
||||
owner = owners(runs, commits)
|
||||
titles: list[list[str]] = [[] for _ in runs]
|
||||
for commit in commits.values():
|
||||
titles[owner[commit.hash]].append(commit.title)
|
||||
spans = []
|
||||
for index, run in enumerate(runs):
|
||||
spans.append(Span(
|
||||
before=run[-1].parents[0] if run[-1].parents else None,
|
||||
tip=run[0].hash,
|
||||
label=label(run[-1].short, run[0].short),
|
||||
landing=landing(run),
|
||||
merged=utc(run[0].committed),
|
||||
titles=tuple(titles[index]),
|
||||
))
|
||||
return Branch(commits, spans, owner)
|
||||
|
||||
|
||||
def parsed(log: str) -> dict[str, Commit] | Failure:
|
||||
"""Each commit LOG printed, by hash, in the order it printed them."""
|
||||
commits = {}
|
||||
for record in log.split("\x00")[1:]:
|
||||
found = LOG_RECORD.fullmatch(record)
|
||||
if not found:
|
||||
return Failure(f"git log printed a commit it could not read: {record[:200]!r}")
|
||||
full, committed, authored, parents, short, rest = found.groups()
|
||||
title, *files = rest.split("\n")
|
||||
commits[full] = Commit(full, short, int(committed), int(authored), tuple(parents.split()), title, tuple(name for name in files if name))
|
||||
return commits
|
||||
|
||||
|
||||
def chunk_log(line: list[Commit]) -> list[list[Commit]]:
|
||||
"""The first-parent line, newest first, cut into chunks, newest first, each holding its commits newest first. A merge is a chunk of its own; any other commit joins the chunk of the newer commit above it when that is no merge and both share a commit time."""
|
||||
runs: list[list[Commit]] = []
|
||||
for commit in line:
|
||||
if runs and len(commit.parents) < 2 and len(runs[-1][-1].parents) < 2 and runs[-1][-1].committed == commit.committed:
|
||||
runs[-1].append(commit)
|
||||
else:
|
||||
runs.append([commit])
|
||||
return runs
|
||||
|
||||
|
||||
def landing(run: list[Commit]) -> Landing:
|
||||
"""How a run that chunk_log cut reached the branch: by a merge commit, by a rebase that gave a commit a commit time other than its author time, or by commits never replayed."""
|
||||
if len(run[0].parents) > 1:
|
||||
return "merge"
|
||||
return "rebase" if any(commit.committed != commit.authored for commit in run) else "push"
|
||||
|
||||
|
||||
def label(first: str, last: str) -> str:
|
||||
"""How the report names a chunk: its one commit's short hash, or its first and last commits' as a range."""
|
||||
return first if first == last else f"{first}^..{last}"
|
||||
|
||||
|
||||
def owners(runs: list[list[Commit]], commits: dict[str, Commit]) -> dict[str, int]:
|
||||
"""Each commit's chunk, as its index in runs: the oldest chunk whose commits reach it."""
|
||||
owner: dict[str, int] = {}
|
||||
for index in reversed(range(len(runs))):
|
||||
for commit in reversed(runs[index]):
|
||||
unowned = [commit.hash]
|
||||
while unowned:
|
||||
found = unowned.pop()
|
||||
if found not in owner:
|
||||
owner[found] = index
|
||||
unowned += commits[found].parents
|
||||
return owner
|
||||
|
||||
|
||||
def shipped(before: str, after: str) -> list[Item]:
|
||||
"""Each item the todo.md before a change holds and the todo.md after it does not, as scored before; none where either holds no items table it can read."""
|
||||
planned, left = items(before), items(after)
|
||||
if not isinstance(planned, list) or not isinstance(left, list):
|
||||
return []
|
||||
kept = {item.id for item in left}
|
||||
return sorted((item for item in planned if item.id not in kept), key=lambda item: item.id)
|
||||
|
||||
|
||||
def plan_revisions(branch: Branch) -> list[str]:
|
||||
"""The revisions whose todo.md shipped_by needs: for each chunk that brought a commit changing todo.md, other than the branch's oldest chunk, the commit before it and its tip."""
|
||||
changed = sorted({branch.owner[commit.hash] for commit in branch.commits.values() if "todo.md" in commit.files})
|
||||
revisions: dict[str, None] = {}
|
||||
for index in changed:
|
||||
before = branch.chunks[index].before
|
||||
if before is not None:
|
||||
revisions.update(dict.fromkeys((before, branch.chunks[index].tip)))
|
||||
return list(revisions)
|
||||
|
||||
|
||||
def shipped_by(branch: Branch, plans: dict[str, str]) -> list[tuple[Item, ...]]:
|
||||
"""The items each of the branch's chunks shipped, in the order of its chunks. plans holds todo.md's text at each revision plan_revisions names. A chunk with a revision plans lacks changed no plan, so it shipped none."""
|
||||
found: list[tuple[Item, ...]] = []
|
||||
for chunk in branch.chunks:
|
||||
if chunk.before is not None and chunk.before in plans and chunk.tip in plans:
|
||||
found.append(tuple(shipped(plans[chunk.before], plans[chunk.tip])))
|
||||
else:
|
||||
found.append(())
|
||||
return found
|
||||
@@ -0,0 +1,86 @@
|
||||
"""The later chunks that fixed code each chunk on a default branch shipped: its escaped defects.
|
||||
|
||||
A later chunk fixed code an earlier chunk shipped where one of its changes removes or rewrites lines that `git blame` traces to a commit the earlier chunk brought. Two kinds of change count: the chunk's whole change, where it ships a todo.md item marked `defect` or `security`; and a round commit of the chunk whose title counts both a 🔴 and a misread finding. Each later chunk counts at most once against each earlier chunk."""
|
||||
import re
|
||||
import typing
|
||||
|
||||
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
|
||||
from release_plan.todo_table import 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")
|
||||
HUNK = re.compile(r"@@ -([0-9]+)(?:,([0-9]+))? \+[0-9]+(?:,([0-9]+))? @@")
|
||||
BLAME_HEADER = re.compile(r"([0-9a-f]{40}|[0-9a-f]{64}) [0-9]+ [0-9]+")
|
||||
|
||||
|
||||
class FixingChange(typing.NamedTuple):
|
||||
"""A change that fixes a defect: the index of its chunk, the commit before it and its tip."""
|
||||
chunk: int
|
||||
before: str
|
||||
tip: str
|
||||
|
||||
|
||||
class Traced(typing.NamedTuple):
|
||||
"""The commits that last changed the lines a fixing change removes, with the index of the change's chunk."""
|
||||
chunk: int
|
||||
commits: set[str]
|
||||
|
||||
|
||||
def fixing_changes(branch: Branch, shipped: list[tuple[Item, ...]]) -> list[FixingChange]:
|
||||
"""Each change that fixes a defect: the whole change of each chunk that ships a FIXES item, as shipped_by lists them, and each round commit whose title counts both a 🔴 and a misread finding."""
|
||||
changes = []
|
||||
for index, (chunk, items) in enumerate(zip(branch.chunks, shipped)):
|
||||
if chunk.before is not None and any(item.exempt in FIXES for item in items):
|
||||
changes.append(FixingChange(index, chunk.before, chunk.tip))
|
||||
for commit in branch.commits.values():
|
||||
counts = title_counts(commit.title)
|
||||
# A title counts misread 🔴 and 🟡 findings together, so it takes one with both a 🔴 and a misread finding to answer a misread 🔴.
|
||||
if counts and counts.red and counts.misread and commit.parents:
|
||||
changes.append(FixingChange(branch.owner[commit.hash], commit.parents[0], commit.hash))
|
||||
return changes
|
||||
|
||||
|
||||
def with_fixes(branch: Branch, shipped: list[tuple[Item, ...]], traced: list[Traced]) -> list[BranchChunk]:
|
||||
"""The branch's chunks, each with the items it shipped, as shipped_by lists them, and the later chunks that fixed code it shipped, from the commits each fixing change traced to."""
|
||||
fixed: dict[int, set[int]] = {}
|
||||
for change in traced:
|
||||
for commit in change.commits:
|
||||
# Blame at a commit on the branch should name only commits its log holds; any other counts against no chunk. Chunks run newest first, so > keeps the chunks older than the fixing one.
|
||||
if commit in branch.owner and branch.owner[commit] > change.chunk:
|
||||
fixed.setdefault(branch.owner[commit], set()).add(change.chunk)
|
||||
chunks = []
|
||||
for index, (span, items) in enumerate(zip(branch.chunks, shipped)):
|
||||
fixed_by = tuple(branch.chunks[later].label for later in sorted(fixed.get(index, ())))
|
||||
chunks.append(BranchChunk(**vars(span), shipped=items, fixed_by=fixed_by))
|
||||
return chunks
|
||||
|
||||
|
||||
def removed_work(diff: str) -> dict[str, list[tuple[int, int]]]:
|
||||
"""What removed reads from a `git diff -U0`, less the paths in NOT_WORK: the plan and the records."""
|
||||
return {path: spans for path, spans in removed(diff).items() if path not in NOT_WORK}
|
||||
|
||||
|
||||
def removed(diff: str) -> dict[str, list[tuple[int, int]]]:
|
||||
"""The old lines each hunk of a `git diff -U0` removes or rewrites, as its first line and count, by the path the file had before; none for a path git quotes, as it does one holding a byte it cannot print."""
|
||||
spans: dict[str, list[tuple[int, int]]] = {}
|
||||
path, left = None, 0
|
||||
for row in diff.splitlines():
|
||||
if left and row[:1] in ("-", "+", " "):
|
||||
left -= 1
|
||||
elif row.startswith("diff --git "):
|
||||
path, left = None, 0
|
||||
elif row.startswith("--- "):
|
||||
# Git ends a path holding a space with a tab.
|
||||
path = row[len("--- a/"):].removesuffix("\t") if row.startswith("--- a/") else None
|
||||
elif hunk := HUNK.match(row):
|
||||
start, count = int(hunk.group(1)), int(hunk.group(2) or 1)
|
||||
left = count + int(hunk.group(3) or 1)
|
||||
if path and count:
|
||||
spans.setdefault(path, []).append((start, count))
|
||||
return spans
|
||||
|
||||
|
||||
def blamed(porcelain: str) -> set[str]:
|
||||
"""The commit each line of `git blame --porcelain` output comes from."""
|
||||
return {header.group(1) for row in porcelain.splitlines() if (header := BLAME_HEADER.match(row))}
|
||||
@@ -0,0 +1,61 @@
|
||||
from branch_chunks.fixes import blamed, fixing_changes, FixingChange, removed_work, Traced, with_fixes
|
||||
from branch_chunks.cut import BranchChunk, cut_branch, LOG, plan_revisions, shipped_by
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import Run, text_at
|
||||
|
||||
|
||||
def branch_chunks(default: str, run: Run) -> list[BranchChunk] | Failure:
|
||||
"""Each chunk on the default branch's first-parent line, newest first, with the todo.md items it shipped and the later chunks that fixed code it shipped.
|
||||
|
||||
run must run git in the checkout's top: the diff names each path from the top, while blame and a pathspec read a path from the current directory."""
|
||||
# The -- keeps a file named like the branch from making it ambiguous.
|
||||
log = run(*LOG, default, "--")
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
branch = cut_branch(log)
|
||||
if isinstance(branch, Failure):
|
||||
return branch
|
||||
plans = plans_at(plan_revisions(branch), run)
|
||||
if isinstance(plans, Failure):
|
||||
return plans
|
||||
shipped = shipped_by(branch, plans)
|
||||
traced = traces(fixing_changes(branch, shipped), run)
|
||||
return traced if isinstance(traced, Failure) else with_fixes(branch, shipped, traced)
|
||||
|
||||
|
||||
def plans_at(revisions: list[str], run: Run) -> dict[str, str] | Failure:
|
||||
"""todo.md's text at each revision, empty where the revision holds none."""
|
||||
plans = {}
|
||||
for revision in revisions:
|
||||
plan = text_at(revision, "todo.md", run)
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
plans[revision] = plan
|
||||
return plans
|
||||
|
||||
|
||||
def traces(changes: list[FixingChange], run: Run) -> list[Traced] | Failure:
|
||||
"""The commits traced_to traces for each change."""
|
||||
found = []
|
||||
for change in changes:
|
||||
traced = traced_to(change.before, change.tip, run)
|
||||
if isinstance(traced, Failure):
|
||||
return traced
|
||||
found.append(Traced(change.chunk, traced))
|
||||
return found
|
||||
|
||||
|
||||
def traced_to(before: str, tip: str, run: Run) -> set[str] | Failure:
|
||||
"""The commits that last changed each line of a chunk's work that the change from before to tip removes or rewrites."""
|
||||
# The prefixes and options keep the checkout's diff config out of the output. Only hunk headers, paths and commits are read, so a file's text that is not UTF-8 is replaced.
|
||||
diff = run("diff", "-U0", "--inter-hunk-context=0", "-M", "--no-color", "--no-ext-diff", "--no-textconv", "--ignore-submodules", "--src-prefix=a/", "--dst-prefix=b/", before, tip, errors="replace")
|
||||
if isinstance(diff, Failure):
|
||||
return diff
|
||||
traced: set[str] = set()
|
||||
for path, spans in removed_work(diff).items():
|
||||
# --no-ignore-revs-file drops each revs file the config names, since blame fails on one that is missing. An empty --ignore-revs-file= doesn't: blame opens the configured files first.
|
||||
blame = run("blame", "--porcelain", "--no-textconv", "--no-ignore-revs-file", *(f"-L{start},+{count}" for start, count in spans), before, "--", path, errors="replace")
|
||||
if isinstance(blame, Failure):
|
||||
return blame
|
||||
traced |= blamed(blame)
|
||||
return traced
|
||||
@@ -0,0 +1,286 @@
|
||||
import functools
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from branch_chunks.fixes import blamed, fixing_changes, removed, removed_work, Traced, with_fixes
|
||||
from branch_chunks.cut import Branch, chunk_log, Commit, cut_branch, landing, NOT_WORK, shipped, Span
|
||||
from branch_chunks.read import branch_chunks, traced_to
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git
|
||||
from test_env import isolated_env
|
||||
from release_plan.todo_table import Item
|
||||
|
||||
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
FIRST = "| 4 | 0.1.0 | | **Do it.** | 2 | 3 | 10 | 6 | 7 | 1 | 9.0 |"
|
||||
SECOND = "| 5 | 0.1.0 | | **Then this.** | 4 | 6 | 8 | 6 | 7 | 1 | 9.0 |"
|
||||
FIX = "| 6 | 0.1.0 | defect | **Fix it.** | 1 | 1 | 1 | 6 | 7 | 1 | 9.0 |"
|
||||
|
||||
|
||||
def todo(*rows: str, header: str = HEADER) -> str:
|
||||
return "# todo\n\n## Items\n\n" + header + "".join(f"{row}\n" for row in rows)
|
||||
|
||||
|
||||
def item(id_: int, exempt: str = "") -> Item:
|
||||
return Item(id_, (0, 1, 0), exempt, f"**Item {id_}.**", {}, (), ())
|
||||
|
||||
|
||||
def span(label: str) -> Span:
|
||||
return Span(f"{label}-before", f"{label}-tip", label, "merge", "2026-10-13T10:00:00Z", ())
|
||||
|
||||
|
||||
def commit(hash_: str, committed: int, authored: int, *parents: str, title: str = "") -> Commit:
|
||||
return Commit(hash_, hash_, committed, authored, parents, title, ())
|
||||
|
||||
|
||||
def cut(*line: Commit) -> list[tuple[str, str, int, str]]:
|
||||
"""Each chunk chunk_log cuts the first-parent line into: its oldest and newest commit, its commit time and how it landed."""
|
||||
return [(run[-1].hash, run[0].hash, run[0].committed, landing(run)) for run in chunk_log(list(line))]
|
||||
|
||||
|
||||
class Shipped(unittest.TestCase):
|
||||
def test_ships_each_item_the_change_removed_with_the_scores_it_had_before(self):
|
||||
self.assertEqual([found.id for found in shipped(todo(FIRST, SECOND), todo(SECOND))], [4])
|
||||
self.assertEqual(shipped(todo(FIRST, SECOND), todo(SECOND))[0].scores, {"R": 2, "S": 3, "C": 10, "A": 6, "G": 7})
|
||||
|
||||
def test_lists_the_shipped_items_by_id(self):
|
||||
self.assertEqual([found.id for found in shipped(todo(SECOND, FIRST), todo())], [4, 5])
|
||||
|
||||
def test_reads_a_table_from_before_c_joined_it(self):
|
||||
older = "| 4 | 0.1.0 | | **A \\| B.** | 2 | 3 | 6 | 7 | 1 | 9.0 |"
|
||||
self.assertEqual(shipped(todo(older, header=WITHOUT_C), todo(header=WITHOUT_C))[0].scores, {"R": 2, "S": 3, "A": 6, "G": 7})
|
||||
|
||||
def test_ships_nothing_where_either_plan_has_no_table_it_can_read(self):
|
||||
self.assertEqual(shipped(todo(FIRST), "# todo\n\n- [ ] Do it.\n"), [])
|
||||
self.assertEqual(shipped(todo(FIRST, "| x | 0.1.0 | | **Bad.** | 2 | 3 | 5 | 6 | 7 | 1 | 9.0 |"), todo()), [])
|
||||
|
||||
|
||||
class CutBranch(unittest.TestCase):
|
||||
def test_reads_a_title_that_holds_a_control_character(self):
|
||||
found = cut_branch(f"\x00{'a' * 40} 100 100 \x1faaaaaaa\x1fTake \x1e and \x1f\n\nb.py\n")
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual([found.titles for found in found.chunks], [("Take \x1e and \x1f",)])
|
||||
|
||||
def test_fails_on_a_commit_it_cannot_read(self):
|
||||
self.assertIsInstance(cut_branch(f"\x00{'a' * 40} 100\x1faaaaaaa\n"), Failure)
|
||||
|
||||
def test_fails_on_a_log_that_holds_no_commit(self):
|
||||
self.assertIsInstance(cut_branch(""), Failure)
|
||||
|
||||
|
||||
class ChunkLog(unittest.TestCase):
|
||||
def test_a_merge_is_a_chunk_of_its_own_and_joins_no_run_below_it(self):
|
||||
self.assertEqual(cut(commit("m", 100, 100, "a", "b"), commit("c", 100, 100, "a")), [("m", "m", 100, "merge"), ("c", "c", 100, "push")])
|
||||
self.assertEqual(cut(commit("c", 100, 100, "m"), commit("m", 100, 100, "a", "b")), [("c", "c", 100, "push"), ("m", "m", 100, "merge")])
|
||||
|
||||
def test_commits_sharing_a_commit_time_form_one_run_labelled_rebase_when_any_differs(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 150, "c1"), commit("c1", 200, 100, "r")), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_run_of_commits_that_all_kept_their_author_time_is_labelled_push(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 200, "c1"), commit("c1", 200, 200, "r")), [("c1", "c2", 200, "push")])
|
||||
|
||||
def test_a_run_is_rebase_when_only_its_older_commit_was_replayed(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 200, "c1"), commit("c1", 200, 100, "r")), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_run_is_rebase_when_only_its_newer_commit_was_replayed(self):
|
||||
self.assertEqual(cut(commit("c2", 200, 100, "c1"), commit("c1", 200, 200, "r")), [("c1", "c2", 200, "rebase")])
|
||||
|
||||
def test_a_commit_at_another_time_starts_a_new_chunk(self):
|
||||
self.assertEqual(cut(commit("c2", 300, 300, "c1"), commit("c1", 200, 200, "r")), [("c2", "c2", 300, "push"), ("c1", "c1", 200, "push")])
|
||||
|
||||
|
||||
class FixingChanges(unittest.TestCase):
|
||||
def test_takes_the_whole_change_of_each_chunk_that_ships_a_defect_or_a_security_item(self):
|
||||
branch = Branch({}, [span("d"), span("c"), span("b"), span("a")], {})
|
||||
shipped = [(item(9, "security"),), (item(8),), (item(6, "defect"), item(7)), ()]
|
||||
self.assertEqual(fixing_changes(branch, shipped), [(0, "d-before", "d-tip"), (2, "b-before", "b-tip")])
|
||||
|
||||
def test_takes_each_round_commit_whose_title_counts_both_a_red_and_a_misread_finding(self):
|
||||
titles = {
|
||||
"r1": "Answer stability round 1: 1 🔴, 0 🟡 (1 misread); keep y's caller",
|
||||
"r2": "Answer stability round 2: 1 🔴, 0 🟡 (0 misread); fix",
|
||||
"r3": "Answer prose round 1: 0 🔴, 1 🟡 (1 misread); fix",
|
||||
"r4": "Answer principles round 1: 1 🔴, 0 🟡; fix",
|
||||
"r5": "Do the work",
|
||||
}
|
||||
commits = {name: commit(name, 100, 100, f"{name}-parent", title=title) for name, title in titles.items()}
|
||||
branch = Branch(commits, [span("b"), span("a")], {"r1": 1, "r2": 0, "r3": 0, "r4": 0, "r5": 0})
|
||||
self.assertEqual(fixing_changes(branch, [(), ()]), [(1, "r1-parent", "r1")])
|
||||
|
||||
|
||||
class WithFixes(unittest.TestCase):
|
||||
def test_names_each_later_chunk_once_against_each_chunk_whose_commits_its_fixes_traced_to_newest_first(self):
|
||||
branch = Branch({}, [span("d"), span("c"), span("b"), span("a")], {"a1": 3, "a2": 3, "b1": 2, "c1": 1, "d1": 0})
|
||||
found = with_fixes(branch, [()] * 4, [Traced(1, {"a1", "a2"}), Traced(0, {"a1", "b1", "c1"}), Traced(1, {"a2"}), Traced(0, {"a2"})])
|
||||
self.assertEqual([found.fixed_by for found in found], [(), ("d",), ("d",), ("d", "c")])
|
||||
|
||||
def test_counts_no_fix_of_its_own_chunks_commit_a_newer_chunks_or_one_no_chunk_brought(self):
|
||||
branch = Branch({}, [span("b"), span("a")], {"b1": 0, "a1": 1})
|
||||
self.assertEqual([found.fixed_by for found in with_fixes(branch, [(), ()], [Traced(1, {"a1", "b1", "elsewhere"})])], [(), ()])
|
||||
|
||||
def test_keeps_each_chunk_as_cut_with_the_items_it_shipped(self):
|
||||
(found,) = with_fixes(Branch({}, [span("a")], {}), [(item(4),)], [])
|
||||
self.assertEqual((found.before, found.tip, found.label, found.landing, found.merged, found.titles), ("a-before", "a-tip", "a", "merge", "2026-10-13T10:00:00Z", ()))
|
||||
self.assertEqual([shipped.id for shipped in found.shipped], [4])
|
||||
|
||||
|
||||
class Removed(unittest.TestCase):
|
||||
def test_reads_the_old_lines_each_hunk_removes_or_rewrites_by_the_path_they_had(self):
|
||||
diff = "\n".join([
|
||||
"diff --git a/a.py b/a.py",
|
||||
"--- a/a.py",
|
||||
"+++ b/a.py",
|
||||
"@@ -2 +2 @@ def f():",
|
||||
"-x",
|
||||
"+y",
|
||||
"@@ -5,3 +4,0 @@",
|
||||
"@@ -9,0 +8,2 @@",
|
||||
"diff --git a/old.py b/new.py",
|
||||
"--- a/old.py",
|
||||
"+++ b/new.py",
|
||||
"@@ -1,2 +1,2 @@",
|
||||
"diff --git a/gone.py b/gone.py",
|
||||
"--- a/gone.py",
|
||||
"+++ /dev/null",
|
||||
"@@ -1,4 +0,0 @@",
|
||||
"diff --git a/born.py b/born.py",
|
||||
"--- /dev/null",
|
||||
"+++ b/born.py",
|
||||
"@@ -0,0 +1,3 @@",
|
||||
"diff --git \"a/tab\\there.py\" \"b/tab\\there.py\"",
|
||||
"--- \"a/tab\\there.py\"",
|
||||
"+++ \"b/tab\\there.py\"",
|
||||
"@@ -1 +1 @@",
|
||||
"diff --git a/my file.py b/my file.py",
|
||||
"--- a/my file.py\t",
|
||||
"+++ b/my file.py\t",
|
||||
"@@ -7,2 +7 @@",
|
||||
])
|
||||
self.assertEqual(removed(diff), {"a.py": [(2, 1), (5, 3)], "old.py": [(1, 2)], "gone.py": [(1, 4)], "my file.py": [(7, 2)]})
|
||||
|
||||
def test_reads_a_changed_line_that_looks_like_a_header_as_text(self):
|
||||
# The second removed line was `-- a/other` in the file.
|
||||
diff = "--- a/q.sql\n+++ b/q.sql\n@@ -3,2 +3 @@\n-x\n--- a/other\n+z\n@@ -9 +8,0 @@\n-y\n"
|
||||
self.assertEqual(removed(diff), {"q.sql": [(3, 2), (9, 1)]})
|
||||
|
||||
|
||||
class RemovedWork(unittest.TestCase):
|
||||
def test_leaves_out_the_plan_and_the_records(self):
|
||||
diff = "".join(f"--- a/{path}\n+++ b/{path}\n@@ -2 +2 @@\n-x\n+y\n" for path in ("a.py", *NOT_WORK))
|
||||
self.assertEqual(removed_work(diff), {"a.py": [(2, 1)]})
|
||||
|
||||
|
||||
class Blamed(unittest.TestCase):
|
||||
def test_reads_the_commit_of_each_line_from_porcelain_output(self):
|
||||
first, second = "a" * 40, "b" * 40
|
||||
porcelain = f"{first} 2 2 1\nauthor t\nfilename a.py\n\tx\n{second} 5 5 2\nauthor t\n\ty\n{second} 6 6\n\t{first} 1 1 1\n"
|
||||
self.assertEqual(blamed(porcelain), {first, second})
|
||||
|
||||
|
||||
class TracedTo(unittest.TestCase):
|
||||
DIFF = "--- a/a.py\n+++ b/a.py\n@@ -2 +2 @@\n-x\n+y\n--- a/todo.md\n+++ b/todo.md\n@@ -5 +4,0 @@\n-| 6 |\n"
|
||||
|
||||
def test_names_the_commits_blame_names_for_the_work_a_change_removes(self):
|
||||
blames = {"a.py": f"{'a' * 40} 2 2 1\n\tx\n", "todo.md": f"{'b' * 40} 5 5 1\n\t| 6 |\n"}
|
||||
self.assertEqual(traced_to("before", "tip", lambda *args, **options: self.DIFF if args[0] == "diff" else blames[args[-1]]), {"a" * 40})
|
||||
|
||||
def test_fails_where_git_cannot_blame(self):
|
||||
self.assertEqual(traced_to("before", "tip", lambda *args, **options: self.DIFF if args[0] == "diff" else Failure("no blame")), Failure("no blame"))
|
||||
|
||||
|
||||
class BranchChunks(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.checkout = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.checkout)}
|
||||
self.git("init", "-q", "-b", "main")
|
||||
self.commit("Start", {"todo.md": todo(FIRST, SECOND, FIX), "a.py": "1\n"})
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
|
||||
|
||||
def commit(self, title, files):
|
||||
for name, text in files.items():
|
||||
(self.checkout / name).write_bytes(text if isinstance(text, bytes) else text.encode())
|
||||
self.git("add", name)
|
||||
self.git("commit", "-q", "-m", title)
|
||||
|
||||
def merge(self, branch, title, files, at):
|
||||
"""Merges a branch holding one commit, at the given time, and returns the merge commit's short hash."""
|
||||
self.git("switch", "-q", "-c", branch)
|
||||
self.commit(title, files)
|
||||
self.git("switch", "-q", "main")
|
||||
self.env.update({"GIT_COMMITTER_DATE": at, "GIT_AUTHOR_DATE": at})
|
||||
self.git("merge", "-q", "--no-ff", "-m", f"Merge {branch}", branch)
|
||||
for name in ("GIT_COMMITTER_DATE", "GIT_AUTHOR_DATE"):
|
||||
self.env.pop(name)
|
||||
return self.git("rev-parse", "--short", "HEAD").strip()
|
||||
|
||||
def read(self, run=None):
|
||||
"""branch_chunks over main, run by git_repo's git, or else by run."""
|
||||
with unittest.mock.patch.dict(os.environ, self.env, clear=True):
|
||||
return branch_chunks("main", functools.partial(run or git, cwd=str(self.checkout)))
|
||||
|
||||
def fixing_history(self):
|
||||
"""Merges seven chunks onto main, then checks out a branch off it. Returns each of main's chunks by label, with the chunks that fixed it.
|
||||
|
||||
The defect chunk six rewrites the lines around one that an unfixed chunk wrote, renames a file and rewrites a line of it, rewrites a line that is not UTF-8, and moves a gitlink. Chunk seven fixes nothing."""
|
||||
start = self.git("rev-parse", "--short", "HEAD").strip()
|
||||
one = self.merge("one", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-10T10:00:00Z")
|
||||
two = self.merge("two", "Do five", {"b.py": "x\nn\ny\n", "todo.md": todo(FIX)}, "2026-10-11T10:00:00Z")
|
||||
self.git("update-index", "--add", "--cacheinfo", f"160000,{'1' * 40},sub")
|
||||
three = self.merge("three", "Add old.py and sub", {"old.py": "k1\nk2\nk3\nk4\nk5\n"}, "2026-10-12T10:00:00Z")
|
||||
four = self.merge("four", "Rewrite k5", {"old.py": "k1\nk2\nk3\nk4\nr\n"}, "2026-10-13T10:00:00Z")
|
||||
five = self.merge("five", "Add d.txt", {"d.txt": "café\n".encode("latin-1")}, "2026-10-14T10:00:00Z")
|
||||
self.git("rm", "-q", "old.py")
|
||||
self.git("update-index", "--cacheinfo", f"160000,{'2' * 40},sub")
|
||||
six = self.merge("six", "Fix six", {"b.py": "X\nn\nY\n", "new.py": "k1\nk2\nk3\nk4\nR\n", "d.txt": "cafè\n".encode("latin-1"), "todo.md": todo()}, "2026-10-15T10:00:00Z")
|
||||
seven = self.merge("seven", "Add c.py", {"c.py": "1\n"}, "2026-10-16T10:00:00Z")
|
||||
self.git("switch", "-q", "-c", "side")
|
||||
self.commit("Side", {"a.py": "2\n"})
|
||||
return {start: (), one: (six,), two: (), three: (), four: (six,), five: (six,), six: (), seven: ()}
|
||||
|
||||
def test_traces_a_fix_across_files_renames_text_that_is_not_utf_8_and_gitlinks(self):
|
||||
expected = self.fixing_history()
|
||||
found = self.read()
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual({chunk.label: chunk.fixed_by for chunk in found}, expected)
|
||||
|
||||
def test_keeps_the_checkouts_diff_and_blame_config_out_of_the_trace(self):
|
||||
expected = self.fixing_history()
|
||||
for setting in ("diff.noprefix=true", "color.ui=always", "diff.external=false", "diff.interHunkContext=5", "diff.renames=false", "blame.ignoreRevsFile=missing", "diff.doubled.textconv=sed p"):
|
||||
self.git("config", *setting.split("=", 1))
|
||||
(self.checkout / ".git" / "info" / "attributes").write_text("*.py diff=doubled\n")
|
||||
found = self.read()
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual({chunk.label: chunk.fixed_by for chunk in found}, expected)
|
||||
|
||||
def test_fails_where_git_cannot_blame_a_fixing_change(self):
|
||||
self.merge("four", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-13T10:00:00Z")
|
||||
self.merge("six", "Fix six", {"b.py": "x\nY\n", "todo.md": todo(SECOND)}, "2026-10-14T10:00:00Z")
|
||||
self.assertEqual(self.read(lambda *args, **options: Failure("no blame") if args[0] == "blame" else git(*args, **options)), Failure("no blame"))
|
||||
|
||||
def test_reads_each_chunk_with_the_items_it_shipped_and_the_later_chunks_that_fixed_it(self):
|
||||
shipped = self.merge("four", "Do four", {"b.py": "x\ny\n", "todo.md": todo(SECOND, FIX)}, "2026-10-13T10:00:00Z")
|
||||
fixed = self.merge("six", "Fix six", {"b.py": "x\nY\n", "todo.md": todo(SECOND)}, "2026-10-14T10:00:00Z")
|
||||
found = self.read()
|
||||
self.assertNotIsInstance(found, Failure)
|
||||
self.assertEqual([(found.label, found.landing, found.merged, [item.id for item in found.shipped], found.fixed_by) for found in found[:2]], [(fixed, "merge", "2026-10-14T10:00:00Z", [6], ()), (shipped, "merge", "2026-10-13T10:00:00Z", [4], (fixed,))])
|
||||
self.assertEqual(sorted(found[1].titles), ["Do four", "Merge four"])
|
||||
self.assertEqual((found[1].tip, found[2].tip), (self.git("rev-parse", "HEAD^").strip(), self.git("rev-parse", "HEAD^^").strip()))
|
||||
self.assertEqual((found[1].before, found[2].before), (found[2].tip, None))
|
||||
|
||||
def test_fails_where_git_cannot_read_the_branch(self):
|
||||
self.assertEqual(branch_chunks("main", lambda *args: Failure("no log")), Failure("no log"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,177 +0,0 @@
|
||||
"""The next chunk's pick: the item the chunk takes first, weighed against the last release cut, and what the default branch holds for the pick."""
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from git_repo import commits_since, file_at, git, newest_release_tag
|
||||
from failure import Failure
|
||||
from todo_table import Item, items, next_item, release_of, renames
|
||||
from markdown_text import sections
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LastCut:
|
||||
"""What the default branch holds about its last release, which chunk_item weighs the plan against."""
|
||||
# The newest v* tag, None where the branch has none.
|
||||
tag: str | None | Failure
|
||||
# CHANGELOG.md's text, empty where the branch holds none.
|
||||
changelog: str | Failure
|
||||
# How many commits follow the tag, or make up the branch where it has none.
|
||||
commits: int | Failure
|
||||
# todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; empty without a tag.
|
||||
todos_since: list[str] | Failure
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Upcoming:
|
||||
"""The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` → "Working loop" uses both."""
|
||||
# The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the plan's earliest. None where there is none.
|
||||
release: tuple[int, int, int] | None
|
||||
# Whether it is the plan's earliest release. Without a cut, it always is, even where the plan holds no item.
|
||||
is_earliest: bool
|
||||
# Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them.
|
||||
landed: bool | Failure
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Next:
|
||||
"""The plan's earliest release is the next release."""
|
||||
# None where the plan holds no item.
|
||||
release: tuple[int, int, int] | None
|
||||
# The item the next chunk takes first, next_item's pick; None where every item waits or the plan holds none.
|
||||
item: Item | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cut:
|
||||
"""The plan's earliest release is the last cut's version or earlier."""
|
||||
release: tuple[int, int, int]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReadyToCut:
|
||||
"""The next release holds no item, and work has landed towards it."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: tuple[int, int, int] | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unplanned:
|
||||
"""The next release holds no item, and no work has landed towards it."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: tuple[int, int, int] | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unknown:
|
||||
"""todo.md's texts since the cut, or the changes since it, cannot be read."""
|
||||
|
||||
|
||||
# How the plan stands to the last cut, with the item the next chunk takes first where there is one.
|
||||
Pick = Next | Cut | ReadyToCut | Unplanned | Unknown
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DefaultPlan:
|
||||
"""What the default branch, as last fetched, holds for chunk_item."""
|
||||
# todo.md's text, empty where the branch holds none.
|
||||
todo: str | Failure
|
||||
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_release_tag(ref, root)
|
||||
commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root)
|
||||
return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root)))
|
||||
|
||||
|
||||
def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> 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 not isinstance(tag, str):
|
||||
return []
|
||||
changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
texts = []
|
||||
for commit in [tag, *changed.split()]:
|
||||
text = file_at(commit, "todo.md", cwd)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
|
||||
"""The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
|
||||
upcoming = next_release(found, cut)
|
||||
return standing(upcoming, next_item(found)) if isinstance(upcoming, Upcoming) else upcoming
|
||||
|
||||
|
||||
def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
"""The next release after cut, and whether work has landed towards it. found holds the plan's items.
|
||||
|
||||
Cut where the plan files items under the last cut's version or earlier, and Unknown where todo.md's texts since the cut cannot be read.
|
||||
"""
|
||||
earliest = min((item.release for item in found), default=None)
|
||||
cut_version = version_of(cut.tag)
|
||||
if cut_version is None:
|
||||
return Upcoming(earliest, True, landed(cut))
|
||||
if earliest is not None and earliest <= cut_version:
|
||||
return Cut(earliest)
|
||||
named = named_releases(cut.todos_since)
|
||||
if isinstance(named, Failure):
|
||||
return Unknown()
|
||||
after = {release for release in named if release > cut_version}
|
||||
if earliest is not None:
|
||||
after.add(earliest)
|
||||
release = min(after, default=None)
|
||||
return Upcoming(release, earliest is not None and earliest == release, landed(cut))
|
||||
|
||||
|
||||
def version_of(tag: str | None | Failure) -> tuple[int, int, int] | None:
|
||||
"""The version x.y.z named by tag, the newest v* tag; None where it names none."""
|
||||
tagged = re.fullmatch(r"v([0-9]+\.[0-9]+\.[0-9]+)", tag) if isinstance(tag, str) else None
|
||||
return None if tagged is None else release_of(tagged[1])
|
||||
|
||||
|
||||
def landed(cut: LastCut) -> bool | Failure:
|
||||
"""Whether work has landed since cut: one or more changes are unreleased."""
|
||||
changes = unreleased_changes(cut)
|
||||
return changes if isinstance(changes, Failure) else changes > 0
|
||||
|
||||
|
||||
def standing(upcoming: Upcoming, first: Item | None) -> Next | ReadyToCut | Unplanned | Unknown:
|
||||
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next.
|
||||
|
||||
Unknown where the next release holds no item and the unreleased changes cannot be counted.
|
||||
"""
|
||||
if upcoming.is_earliest:
|
||||
return Next(upcoming.release, first)
|
||||
if isinstance(upcoming.landed, Failure):
|
||||
return Unknown()
|
||||
return ReadyToCut(upcoming.release) if upcoming.landed else Unplanned(upcoming.release)
|
||||
|
||||
|
||||
def unreleased_changes(cut: LastCut) -> int | Failure:
|
||||
"""How many changes are unreleased, as `~/.claude/CLAUDE.md` → "Working loop" counts them: the entries under ## Unreleased, or the commits since the tag where CHANGELOG.md has no such section or cannot be read."""
|
||||
entries = unreleased_entries(cut.changelog) if isinstance(cut.changelog, str) else None
|
||||
return cut.commits if entries is None else entries
|
||||
|
||||
|
||||
def unreleased_entries(changelog: str) -> int | None:
|
||||
"""How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section."""
|
||||
found = sections(changelog).get("Unreleased")
|
||||
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
|
||||
|
||||
|
||||
def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]] | Failure:
|
||||
"""Each release the todo.md texts, oldest first, file items under. A release leaves the set when a text marks it renamed, and returns when a later text files items under it again. A text whose items or marks do not parse names none, except the newest: where its marks do not parse, it returns that Failure, since the release they should have excluded would read as finished."""
|
||||
if isinstance(todos, Failure):
|
||||
return todos
|
||||
if todos and isinstance(newest := renames(todos[-1]), Failure):
|
||||
return newest
|
||||
named: set[tuple[int, int, int]] = set()
|
||||
for text in todos:
|
||||
plan, marked = items(text), renames(text)
|
||||
if isinstance(plan, list) and isinstance(marked, set):
|
||||
named = (named - marked) | {item.release for item in plan}
|
||||
return named
|
||||
@@ -2,17 +2,26 @@
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from chunk_pick import chunk_item, Cut, LastCut, ReadyToCut, Unknown, Unplanned
|
||||
from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, NoItem, Plan
|
||||
from todo_table import item_details, items, NoItemsTable, version
|
||||
from release_plan.todo_table import item_details, items, NoItemsTable
|
||||
from release_plan.release import version
|
||||
|
||||
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
||||
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
||||
|
||||
|
||||
def cut_name(cut: LastCut) -> str | None:
|
||||
"""How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut."""
|
||||
if cut.tag is not None:
|
||||
return None if isinstance(cut.tag, Failure) else cut.tag
|
||||
headed = dated_cut(cut.tag, cut.changelog)
|
||||
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
|
||||
|
||||
|
||||
def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
|
||||
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, chunk_pick.chunk_item's pick; else why there is none."""
|
||||
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none."""
|
||||
where = f"{default}'s todo.md"
|
||||
if isinstance(todo, Failure):
|
||||
return NoItem(f"{where} cannot be read: {todo.reason}.")
|
||||
@@ -21,15 +30,21 @@ def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
if isinstance(found, Failure):
|
||||
return NoItem(f"{where} cannot be read: {found.reason}.")
|
||||
if isinstance(cut.tag, Failure):
|
||||
return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.")
|
||||
named = cut_name(cut)
|
||||
last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet"
|
||||
pick = chunk_item(found, cut)
|
||||
if isinstance(pick, Cut):
|
||||
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
|
||||
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.")
|
||||
if isinstance(pick, Unknown):
|
||||
return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
|
||||
if isinstance(pick, ReadyToCut | Unplanned):
|
||||
upcoming = f"release {version(pick.release)}, the next after the last cut, {cut.tag}" if pick.release else f"the next release after the last cut, {cut.tag}"
|
||||
return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
|
||||
if isinstance(pick, ReadyToCut | ReviewDue | Unplanned):
|
||||
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
|
||||
if isinstance(pick, ReviewDue):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of <release>` has landed {'since the cut' if named is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
|
||||
if isinstance(pick, ReadyToCut):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
|
||||
first = pick.item
|
||||
if first is None:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""The lines the preflight prints, stated from what it gathered."""
|
||||
from todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone, version
|
||||
from release_plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
|
||||
from chunk_preflight.choices import cut_name, PULLS_LIST
|
||||
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
|
||||
from chunk_pick import LastCut, unreleased_entries
|
||||
from chunk_preflight.choices import PULLS_LIST
|
||||
from markdown_text import quoted
|
||||
from records.markdown_text import quoted
|
||||
from release_plan.release import version
|
||||
|
||||
|
||||
def render(found: Gathered) -> list[str]:
|
||||
@@ -19,11 +20,13 @@ def render(found: Gathered) -> list[str]:
|
||||
def last_release(default: str, release: LastCut) -> str:
|
||||
if isinstance(release.tag, Failure):
|
||||
return f"Last version cut: cannot be read: {release.tag.reason}"
|
||||
cut = f"Last version cut: {release.tag or 'none'}."
|
||||
named = cut_name(release)
|
||||
cut = f"Last version cut: {named or 'none'}."
|
||||
entries = unreleased_entries(release.changelog) if isinstance(release.changelog, str) else None
|
||||
if entries is not None:
|
||||
return f"{cut} Unreleased: {counted(entries, 'entry', 'entries')} under CHANGELOG.md → ## Unreleased."
|
||||
since = f"since {release.tag}" if release.tag else f"on {default}"
|
||||
headed = dated_cut(release.tag, release.changelog)
|
||||
since = f"since {release.tag}" if release.tag else f"since CHANGELOG.md dated {version(headed)}" if headed else f"on {default}"
|
||||
commits = f"the commits {since} cannot be counted: {release.commits.reason}" if isinstance(release.commits, Failure) else f"{counted(release.commits, 'commit', 'commits')} {since}"
|
||||
changelog = f"CHANGELOG.md cannot be read: {release.changelog.reason}" if isinstance(release.changelog, Failure) else "no ## Unreleased in CHANGELOG.md"
|
||||
return f"{cut} Unreleased: {commits}; {changelog}."
|
||||
|
||||
@@ -4,8 +4,8 @@ import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from todo_table import Item
|
||||
from chunk_pick import LastCut
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.release_standing import LastCut
|
||||
|
||||
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
||||
Forge = typing.Literal["gh", "tea"]
|
||||
|
||||
+47
-36
@@ -1,28 +1,35 @@
|
||||
"""Find the mechanical facts a chunk starts from, and make its worktree, so its worker starts from them.
|
||||
"""Find the mechanical facts a chunk starts from, so its worker starts from them; with --worktree, also make its worktree.
|
||||
|
||||
usage: chunk-preflight
|
||||
usage: chunk-preflight [--worktree]
|
||||
|
||||
Run it inside a project checkout. loop-claude runs it at the checkout root before each chunk's
|
||||
first worker, before it routes the chunk, and quotes what it prints in the worker's prompt. It
|
||||
fetches origin, when the checkout has that remote, and takes origin's default branch, or else the
|
||||
local main or master. It leaves the checkout as it is, and reads todo.md as the default branch
|
||||
holds it, the plan loop-claude routes on. It prints:
|
||||
Run it inside a project checkout. It fetches origin, when the checkout has that remote, and takes
|
||||
origin's default branch, or else the local main or master. Without --worktree, it still fetches,
|
||||
but it doesn't make a worktree or a branch, and doesn't run any tool in one. loop-claude runs it
|
||||
with --worktree at the checkout root before each chunk's first worker, before it routes the chunk,
|
||||
and quotes what it prints in the worker's prompt. It leaves the checkout as it is, and reads
|
||||
todo.md as the default branch holds it, the plan loop-claude routes on. It prints:
|
||||
|
||||
- the newest v* tag on the default branch, and how many entries the default branch's CHANGELOG.md
|
||||
holds under ## Unreleased, or else how many commits followed the tag;
|
||||
- the last version cut: the newest v* tag on the default branch, or on a branch with no tag the
|
||||
newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count.
|
||||
Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how
|
||||
many commits followed the cut: the tag, or the commit that added that heading;
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with
|
||||
its L and E + I. An item waits while it is marked question, or while an item still in todo.md
|
||||
blocks it. Where the newest tag names a version x.y.z, the next release is the earliest after
|
||||
x.y.z that todo.md has named at that tag or since, less a release its ## Renamed section marks
|
||||
renamed. Otherwise it is todo.md's earliest release.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the tag:
|
||||
finished and ready to cut where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the tag), and else to be planned first.
|
||||
blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks
|
||||
renamed. Where nothing is cut, it is the earliest release todo.md has ever named, less those
|
||||
renamed, so a release whose items are all done still reads as next.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the cut:
|
||||
its release review due where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the cut) and no commit titled `Release review of <release>` followed the tag,
|
||||
finished and ready to cut once one did, and else to be planned first. On a branch with no tag,
|
||||
such a commit counts only where its <release> is after the version under the dated heading.
|
||||
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
|
||||
already cut;
|
||||
- the item's worktree: a sibling of the checkout named <checkout>-item-<ID>, on the branch
|
||||
item-<ID>. It continues a worktree already on that branch; else it adds one on the local branch,
|
||||
else on a new branch tracking origin's, else on a new branch off the default branch;
|
||||
- with --worktree, the item's worktree: a sibling of the checkout named <checkout>-item-<ID>, on
|
||||
the branch item-<ID>. It continues a worktree already on that branch; else it adds one on the
|
||||
local branch, else on a new branch tracking origin's, else on a new branch off the default
|
||||
branch. Without --worktree, it prints that none was made;
|
||||
- the open pull requests whose head is the item's branch, each by its number and URL, as gh lists
|
||||
them on a github.com origin, and else as tea does. No title reaches the output;
|
||||
- the items of that release that a chunk taking the item may take too: those that are not
|
||||
@@ -30,17 +37,19 @@ holds it, the plan loop-claude routes on. It prints:
|
||||
item's own R is above 5;
|
||||
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
|
||||
file's lines or a folder's files, and the item's tagline and detail;
|
||||
- what `rank_todo.py --check todo.md`, `larv-review needs-scoring-run <ID>`, `reading-cost` and
|
||||
`larv-review places` print in the worktree, each with its exit code. reading-cost appends to the
|
||||
worktree's docs/reading-cost.md, for the chunk to commit.
|
||||
- where it made or continued the worktree, what `rank_todo.py --check todo.md`,
|
||||
`larv-review needs-scoring-run <ID>`, `reading-cost` and `larv-review places` print in it, each
|
||||
with its exit code. reading-cost appends to the worktree's docs/reading-cost.md, for the chunk to
|
||||
commit.
|
||||
|
||||
A fact it cannot find it says it cannot, and why, and goes on. A fetch, forge CLI or tool still
|
||||
running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT sets, is stopped; a
|
||||
stopped fetch reads origin as last fetched. With no item, it makes no worktree and runs none of
|
||||
those four tools.
|
||||
those four tools, --worktree or not.
|
||||
|
||||
Exit 1, saying why, on any argument, on a CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds
|
||||
above 0, or when git cannot start or finds no checkout or no default branch.
|
||||
Exit 1, saying why, on any argument other than --worktree, -h or --help, on a
|
||||
CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, or when git cannot start or finds no
|
||||
checkout or no default branch.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
@@ -48,8 +57,8 @@ import subprocess
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from git_repo import commit_exists, default_branch, file_at, git, top
|
||||
from chunk_pick import default_plan
|
||||
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
|
||||
from release_plan.release_standing import default_plan
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
|
||||
from chunk_preflight.choices import forge_of, named_paths, planned, pulls_command, worktree_add, worktree_on
|
||||
@@ -61,16 +70,18 @@ TOOLS = (("rank_todo.py", "--check", "todo.md"), ("larv-review", "needs-scoring-
|
||||
# Seconds before a fetch, forge CLI or tool is stopped, so a hung one cannot keep the rest from printing; TIMEOUT_SETTING overrides it.
|
||||
TIMEOUT = 60
|
||||
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
|
||||
# The flag that makes the item's worktree and runs TOOLS in it. Three readers seated as the README's audience picked it 2-1 over --start.
|
||||
WORKTREE = "--worktree"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(timeout=TIMEOUT))
|
||||
return 0
|
||||
if argv:
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight", file=sys.stderr)
|
||||
if argv not in ([], [WORKTREE]):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}]", file=sys.stderr)
|
||||
return 1
|
||||
printed = run(env.get(TIMEOUT_SETTING))
|
||||
printed = run(env.get(TIMEOUT_SETTING), argv == [WORKTREE])
|
||||
if isinstance(printed, Failure):
|
||||
print(printed.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -78,13 +89,13 @@ def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def run(setting: str | None) -> list[str] | Failure:
|
||||
"""The preflight's lines, given what TIMEOUT_SETTING holds; a Failure where that is no number of seconds, or git finds no checkout or no default branch."""
|
||||
def run(setting: str | None, make: bool) -> list[str] | Failure:
|
||||
"""The preflight's lines, given the setting TIMEOUT_SETTING holds and whether to make the item's worktree; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
|
||||
timeout = seconds(setting)
|
||||
if isinstance(timeout, Failure):
|
||||
return timeout
|
||||
root = top()
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout)
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make)
|
||||
|
||||
|
||||
def seconds(setting: str | None) -> float | Failure:
|
||||
@@ -96,7 +107,7 @@ def seconds(setting: str | None) -> float | Failure:
|
||||
return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0")
|
||||
|
||||
|
||||
def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure:
|
||||
def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Failure:
|
||||
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
|
||||
default = default_branch(stale_ok=True, timeout=timeout)
|
||||
if isinstance(default, Failure):
|
||||
@@ -104,12 +115,12 @@ def preflight(root: pathlib.Path, timeout: float) -> list[str] | Failure:
|
||||
ref, note = default
|
||||
held = default_plan(str(root), ref)
|
||||
plan = planned(held.todo, held.cut, ref)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
|
||||
return render(Gathered(ref, note, held.cut, item))
|
||||
|
||||
|
||||
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float) -> ItemFacts:
|
||||
worktree = item_worktree(root, plan.branch, default)
|
||||
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts:
|
||||
worktree = item_worktree(root, plan.branch, default) if make else Failure(f"none made, since it ran without {WORKTREE}.")
|
||||
path = worktree.path if isinstance(worktree, Worktree) else None
|
||||
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else [])
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ from failure import Failure
|
||||
from chunk_preflight.choices import forge_of, named_paths, planned, worktree_add
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from test_env import isolated_env
|
||||
from chunk_pick import LastCut
|
||||
from release_plan.release_standing import LastCut
|
||||
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
|
||||
from chunk_preflight.facts import open_pulls, render
|
||||
|
||||
@@ -119,8 +119,8 @@ class Repo:
|
||||
stub.write_text(f'#!/bin/sh\ncase "$*" in\n{arm}\nesac\nexec {shutil.which("git")} "$@"\n')
|
||||
stub.chmod(0o755)
|
||||
|
||||
def preflight(self, **env):
|
||||
return subprocess.run([sys.executable, str(BIN / "chunk-preflight")], capture_output=True, cwd=self.root, env={**self.env, **env}, text=True, timeout=120)
|
||||
def preflight(self, *args, **env):
|
||||
return subprocess.run([sys.executable, str(BIN / "chunk-preflight"), *args], capture_output=True, cwd=self.root, env={**self.env, **env}, text=True, timeout=120)
|
||||
|
||||
|
||||
class ChunkPreflightTool(unittest.TestCase):
|
||||
@@ -130,7 +130,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
# Claude Code rewrites tracked files, such as settings.json, so a checkout behind origin often holds changes.
|
||||
repo.write(repo.root, "todo.md", TODO + "\nA change of the checkout's own.\n")
|
||||
head = repo.git(repo.root, "rev-parse", "HEAD")
|
||||
done = repo.preflight()
|
||||
done = repo.preflight("--worktree")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertEqual(repo.git(repo.root, "rev-parse", "HEAD"), head)
|
||||
worktree = repo.temp / "proj-item-7"
|
||||
@@ -155,20 +155,22 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
self.assertNotIn("`gone.py`:", done.stdout)
|
||||
|
||||
def test_names_no_item_and_makes_no_worktree_where_the_release_after_the_last_cut_has_emptied(self):
|
||||
for changelog, fact in ((CHANGELOG, "finished and ready to cut"), ("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n", "planned first")):
|
||||
for changelog, reviewed, fact in ((CHANGELOG, False, "release review is due"), (CHANGELOG, True, "finished and ready to cut"), ("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n", False, "planned first")):
|
||||
with self.subTest(fact=fact):
|
||||
repo = Repo(self, changelog=changelog)
|
||||
repo.write(repo.root, "todo.md", LATER)
|
||||
repo.commit(repo.root, "ship 0.2.0")
|
||||
if reviewed:
|
||||
repo.git(repo.root, "commit", "--quiet", "--allow-empty", "-m", "Release review of 0.2.0")
|
||||
repo.git(repo.root, "push", "--quiet", "origin", "main")
|
||||
done = repo.preflight()
|
||||
done = repo.preflight("--worktree")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(fact, done.stdout)
|
||||
self.assertNotIn("item 9", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-9").exists())
|
||||
|
||||
def test_takes_the_next_item_where_the_plan_marks_the_release_after_the_last_cut_renamed_and_calls_it_finished_where_it_does_not(self):
|
||||
for mark, fact, absent in (("\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", "item 3", "finished"), ("", "finished and ready to cut", "item 3")):
|
||||
for mark, fact, absent in (("\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", "item 3", "release review"), ("", "release review is due", "item 3")):
|
||||
with self.subTest(mark=mark):
|
||||
repo = Repo(self)
|
||||
repo.write(repo.root, "todo.md", TODO.replace("| 0.3.0 |", "| 0.4.0 |").replace("| 0.2.0 |", "| 0.3.0 |") + mark)
|
||||
@@ -183,7 +185,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
"""Each case's plans: before the tag, at it, on a side branch merged after it, and after it, each committed in turn where given."""
|
||||
cases = (
|
||||
("a release named only before the cut", TODO, LATER, None, None, "item 9"),
|
||||
("a release named at the cut", None, TODO, None, LATER, "finished and ready to cut"),
|
||||
("a release named at the cut", None, TODO, None, LATER, "release review is due"),
|
||||
("a release named only on a side branch", None, LATER, TODO, None, "item 9"),
|
||||
)
|
||||
for name, before, at, side, after, fact in cases:
|
||||
@@ -212,9 +214,9 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
|
||||
def test_continues_the_items_worktree_and_else_its_pushed_branch(self):
|
||||
repo = Repo(self)
|
||||
repo.preflight()
|
||||
repo.preflight("--worktree")
|
||||
worktree = repo.temp / "proj-item-3"
|
||||
continued = repo.preflight().stdout
|
||||
continued = repo.preflight("--worktree").stdout
|
||||
self.assertIn(str(worktree), continued)
|
||||
self.assertIn("continued", continued)
|
||||
(worktree / "work.txt").write_text("work\n")
|
||||
@@ -223,7 +225,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
repo.git(worktree, "push", "--quiet", "origin", "item-3")
|
||||
repo.git(repo.root, "worktree", "remove", "--force", str(worktree))
|
||||
repo.git(repo.root, "branch", "--quiet", "-D", "item-3")
|
||||
pushed = repo.preflight().stdout
|
||||
pushed = repo.preflight("--worktree").stdout
|
||||
self.assertIn(str(worktree), pushed)
|
||||
self.assertIn("made off origin/item-3", pushed)
|
||||
self.assertTrue((worktree / "work.txt").exists())
|
||||
@@ -231,7 +233,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
def test_makes_no_worktree_where_its_path_holds_something_else_and_runs_no_tool(self):
|
||||
repo = Repo(self)
|
||||
(repo.temp / "proj-item-3").mkdir()
|
||||
done = repo.preflight()
|
||||
done = repo.preflight("--worktree")
|
||||
self.assertIn(f"none made, since {repo.temp / 'proj-item-3'} exists", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
|
||||
@@ -239,7 +241,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
repo = Repo(self)
|
||||
repo.temp.chmod(0o555)
|
||||
self.addCleanup(repo.temp.chmod, 0o755)
|
||||
done = repo.preflight()
|
||||
done = repo.preflight("--worktree")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("Worktree: none made: git worktree add", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
@@ -248,7 +250,7 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
def test_makes_no_worktree_and_runs_no_tool_where_git_cannot_list_the_worktrees(self):
|
||||
repo = Repo(self)
|
||||
repo.stub_git('"worktree list --porcelain") echo "listing broke" >&2; exit 1;;')
|
||||
done = repo.preflight()
|
||||
done = repo.preflight("--worktree")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("listing broke", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
@@ -257,19 +259,37 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
def test_reads_origin_as_last_fetched_where_the_fetch_stalls_and_still_states_the_other_facts(self):
|
||||
repo = Repo(self)
|
||||
repo.stub_git(f'"fetch --quiet origin") exec {shutil.which("sleep")} 10;;')
|
||||
done = repo.preflight(CHUNK_PREFLIGHT_TIMEOUT="1")
|
||||
done = repo.preflight("--worktree", CHUNK_PREFLIGHT_TIMEOUT="1")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("as last fetched", done.stdout)
|
||||
self.assertIn("item 3, L 2, E + I 5", done.stdout)
|
||||
self.assertIn("`reading-cost` exited 0", done.stdout)
|
||||
|
||||
def test_without_worktree_states_the_items_facts_and_makes_no_worktree_and_runs_no_tool(self):
|
||||
repo = Repo(self)
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("item 3, L 2, E + I 5", done.stdout)
|
||||
self.assertIn("Worktree: none made, since it ran without --worktree.", done.stdout)
|
||||
self.assertIn("Open pull requests from item-3: none.", done.stdout)
|
||||
self.assertIn("`src/app.py`: 3 lines", done.stdout)
|
||||
self.assertNotIn("`reading-cost`", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
self.assertNotIn("item-3", repo.git(repo.root, "branch", "--list"))
|
||||
|
||||
def test_exits_1_on_an_argument_other_than_worktree(self):
|
||||
done = Repo(self).preflight("--start")
|
||||
self.assertEqual(done.returncode, 1)
|
||||
self.assertIn("unknown arguments --start", done.stderr)
|
||||
self.assertEqual(done.stdout, "")
|
||||
|
||||
def test_lists_the_open_pull_requests_with_gh_on_a_github_origin(self):
|
||||
repo = Repo(self, origin="github.com/o/r.git")
|
||||
self.assertIn("#12 https://github.com/o/r/pull/12", repo.preflight().stdout)
|
||||
|
||||
def test_without_a_plan_states_the_release_facts_and_makes_no_worktree(self):
|
||||
repo = Repo(self, todo="")
|
||||
done = repo.preflight()
|
||||
done = repo.preflight("--worktree")
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn("v0.1.0", done.stdout)
|
||||
self.assertIn("no items table", done.stdout)
|
||||
@@ -347,6 +367,9 @@ class Render(unittest.TestCase):
|
||||
untagged = rendered(NoItem("x."), LastCut(None, "", 1, []))
|
||||
self.assertIn("cut: none", untagged)
|
||||
self.assertIn("1 commit on origin/main", untagged)
|
||||
headed = rendered(NoItem("x."), LastCut(None, "## 0.0.1 - 2026-10-03\n", 1, []))
|
||||
self.assertIn("cut: 0.0.1 (dated in CHANGELOG.md).", headed)
|
||||
self.assertIn("1 commit since CHANGELOG.md dated 0.0.1", headed)
|
||||
|
||||
def test_states_why_the_changelog_and_the_commits_since_the_last_cut_cannot_be_read(self):
|
||||
said = rendered(NoItem("x."), LastCut("v0.1.0", Failure("changelog unreadable"), Failure("count unreadable"), []))
|
||||
@@ -427,20 +450,37 @@ class Plans(unittest.TestCase):
|
||||
self.assertIn("holds no item", empty)
|
||||
self.assertNotIn("no items table", empty)
|
||||
|
||||
def test_names_a_release_cut_under_a_dated_heading_as_the_last_cut_on_a_branch_with_no_tag(self):
|
||||
said = planned(EMPTY, LastCut(None, "## 0.0.1 - 2026-10-03\n", 0, []), "origin/main").why
|
||||
self.assertIn("the next release after the last cut, 0.0.1 (dated in CHANGELOG.md)", said)
|
||||
|
||||
def test_says_the_tags_cannot_be_read_with_gits_reason_and_names_no_cut(self):
|
||||
said = planned(EMPTY, LastCut(Failure("git exited 128: not a git repository"), "", 4, []), "origin/main").why
|
||||
self.assertIn("origin/main's tags cannot be read: git exited 128: not a git repository.", said)
|
||||
self.assertIn("Find the next release yourself.", said)
|
||||
self.assertNotIn("no release is cut yet", said)
|
||||
|
||||
def test_names_the_start_as_the_last_cut_where_nothing_is_cut(self):
|
||||
said = planned(EMPTY, LastCut(None, "", 4, [TODO]), "origin/main").why
|
||||
self.assertIn("release 0.2.0, the next after the start, since no release is cut yet,", said)
|
||||
self.assertIn("has landed yet.", said)
|
||||
self.assertIn("since the cut.", planned(EMPTY, LastCut(None, "## 0.1.0 - 2026-10-03\n", 4, [TODO]), "origin/main").why)
|
||||
|
||||
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
|
||||
named = "release 0.2.0, the next after the last cut, v0.1.0"
|
||||
unnamed = "the next release after the last cut, v0.1.0"
|
||||
cases = (
|
||||
(LATER, 4, [TODO], "finished and ready to cut", named),
|
||||
(LATER, 0, [TODO], "planned first", named),
|
||||
(EMPTY, 4, [TODO], "finished and ready to cut", named),
|
||||
(EMPTY, 0, [TODO], "planned first", named),
|
||||
(EMPTY, 4, [EMPTY], "finished and ready to cut", unnamed),
|
||||
(LATER, Failure("count unreadable"), [TODO], "cannot be read", unnamed),
|
||||
(LATER, 4, [TODO], False, "release review is due", named),
|
||||
(LATER, 4, [TODO], True, "finished and ready to cut", named),
|
||||
(LATER, 0, [TODO], False, "planned first", named),
|
||||
(EMPTY, 4, [TODO], True, "finished and ready to cut", named),
|
||||
(EMPTY, 0, [TODO], False, "planned first", named),
|
||||
(EMPTY, 4, [EMPTY], True, "finished and ready to cut", unnamed),
|
||||
(LATER, Failure("count unreadable"), [TODO], False, "cannot be read", unnamed),
|
||||
)
|
||||
for todo, commits, todos, fact, release in cases:
|
||||
with self.subTest(todo=todo, commits=commits, todos=todos):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, todos), "origin/main").why
|
||||
for todo, commits, todos, reviewed, fact, release in cases:
|
||||
with self.subTest(todo=todo, commits=commits, todos=todos, reviewed=reviewed):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, todos, reviewed), "origin/main").why
|
||||
self.assertIn(fact, why)
|
||||
self.assertIn(release, why)
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
|
||||
import json
|
||||
import typing
|
||||
|
||||
|
||||
def parse_entry(raw: str | bytes) -> dict | None:
|
||||
@@ -36,8 +37,9 @@ def written_by_human(entry: dict) -> bool:
|
||||
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
|
||||
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
|
||||
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
|
||||
# {"type": "user", "isCompactSummary": true, "message": {"content": "This session is being continued from a previous conversation that ran out of context. ..."}}
|
||||
def tagged_as_injected(entry: dict) -> bool:
|
||||
return bool(entry.get("isMeta")) or entry.get("promptSource") in ("sdk", "system")
|
||||
return bool(entry.get("isMeta")) or bool(entry.get("isCompactSummary")) or entry.get("promptSource") in ("sdk", "system")
|
||||
|
||||
|
||||
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
|
||||
@@ -86,11 +88,35 @@ def part_text(part: object) -> str | None:
|
||||
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
|
||||
|
||||
|
||||
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
|
||||
# {"type": "tool_use", "id": "toolu_01…", "name": "Bash", "input": {"command": "echo hi"}}
|
||||
def tool_call(part: object) -> tuple[object, object] | None:
|
||||
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
|
||||
|
||||
|
||||
def tool_use_id(part: object) -> str | None:
|
||||
return part["id"] if isinstance(part, dict) and part.get("type") == "tool_use" and isinstance(part.get("id"), str) else None
|
||||
|
||||
|
||||
class ToolResult(typing.NamedTuple):
|
||||
tool_use_id: str
|
||||
text: str
|
||||
failed: bool
|
||||
|
||||
|
||||
# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed
|
||||
def tool_result(part: object) -> ToolResult | None:
|
||||
if not isinstance(part, dict) or part.get("type") != "tool_result":
|
||||
return None
|
||||
return ToolResult(str(part.get("tool_use_id")), result_text(part.get("content")), bool(part.get("is_error")))
|
||||
|
||||
|
||||
def result_text(content: object) -> str:
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
# Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them.
|
||||
return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""
|
||||
|
||||
|
||||
# stream-json's last line: {"type": "result", "subtype": "success", ...}
|
||||
def ends_stream(event: dict) -> bool:
|
||||
return event.get("type") == "result"
|
||||
|
||||
@@ -37,6 +37,11 @@ def session_files(transcript: str) -> list[str]:
|
||||
return sorted(glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*"))
|
||||
|
||||
|
||||
# <session id>/subagents/agent-<agent id>.jsonl, beside <session id>.jsonl
|
||||
def subagent_transcript(session_transcript: str, agent_id: str) -> str:
|
||||
return os.path.join(session_transcript.removesuffix(".jsonl"), "subagents", f"agent-{agent_id}.jsonl")
|
||||
|
||||
|
||||
def delete_session(session: Session) -> Failure | None:
|
||||
path = transcript_file(session)
|
||||
if path is None:
|
||||
|
||||
@@ -6,7 +6,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from claude_code import entries, reply, transcript, trust
|
||||
from claude_code import entries, reply, transcript
|
||||
from failure import Failure
|
||||
|
||||
|
||||
@@ -54,6 +54,15 @@ class FirstTimestampedLine(unittest.TestCase):
|
||||
self.assertEqual(transcript.first_timestamped_line(b""), b"")
|
||||
|
||||
|
||||
class CurrentThread(unittest.TestCase):
|
||||
def test_a_parent_cycle_ends_the_thread(self):
|
||||
looped = [{"uuid": "a", "parentUuid": "b"}, {"uuid": "b", "parentUuid": "a"}]
|
||||
self.assertEqual([entry["uuid"] for entry in transcript.current_thread(looped)], ["a", "b"])
|
||||
|
||||
def test_entries_without_a_uuid_make_no_thread(self):
|
||||
self.assertEqual(transcript.current_thread([{"type": "summary"}]), [])
|
||||
|
||||
|
||||
class HumanTurns(unittest.TestCase):
|
||||
def test_counts_typed_turns_and_not_tool_results(self):
|
||||
self.assertEqual(transcript.human_turns([
|
||||
@@ -66,6 +75,7 @@ class HumanTurns(unittest.TestCase):
|
||||
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
|
||||
{**human("peer message"), "isMeta": True},
|
||||
{**human("the loop's own prompt"), "promptSource": "sdk"},
|
||||
{**human("This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation."), "isCompactSummary": True},
|
||||
human([{"type": "text", "text": "[Request interrupted by user]"}]),
|
||||
human([]),
|
||||
queued("typed while claude worked", "human"),
|
||||
@@ -122,14 +132,5 @@ class ClaudeReply(unittest.TestCase):
|
||||
self.assertEqual(reply.claude_reply(self.claude(FileNotFoundError(2, "No such file or directory")), [], "/r", "p", "claude"), Failure("could not start claude: No such file or directory"))
|
||||
|
||||
|
||||
class MarkTrusted(unittest.TestCase):
|
||||
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
|
||||
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
|
||||
handed = json.dumps(config)
|
||||
self.assertEqual(trust.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
|
||||
self.assertEqual(json.dumps(config), handed)
|
||||
self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -21,6 +21,21 @@ def read_transcript(path: str) -> list[dict] | Failure:
|
||||
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
||||
|
||||
|
||||
def current_thread(entries: list[dict]) -> list[dict]:
|
||||
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid.
|
||||
|
||||
That leaves out a branch the session rewound, and the results of parallel tool calls that Claude Code chains on a side branch."""
|
||||
chained = [entry for entry in entries if isinstance(entry.get("uuid"), str)]
|
||||
by_uuid = {entry["uuid"]: entry for entry in chained}
|
||||
found: list[dict] = []
|
||||
entry = chained[-1] if chained else None
|
||||
# A compaction writes {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...}, so the thread starts there; the length check stops a parent cycle.
|
||||
while entry is not None and len(found) < len(chained):
|
||||
found.append(entry)
|
||||
entry = by_uuid.get(entry.get("parentUuid"))
|
||||
return found[::-1]
|
||||
|
||||
|
||||
# The lines before it, such as the session's title, are the same for every chunk of a project.
|
||||
def first_timestamped_line(raw: bytes) -> bytes:
|
||||
lines = raw.splitlines()
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from file_writes import replace_json
|
||||
|
||||
|
||||
# A failure only warns: claude still opens, and the human answers Claude Code's trust dialog.
|
||||
def trust(config: pathlib.Path, roots: list[str]) -> None:
|
||||
try:
|
||||
with open(config, encoding="utf-8") as handle:
|
||||
data = json.load(handle)
|
||||
except (OSError, ValueError) as failure:
|
||||
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
|
||||
return
|
||||
marked = mark_trusted(data, roots)
|
||||
if isinstance(marked, Failure):
|
||||
print(f"could not read {config}: {marked.reason}", file=sys.stderr)
|
||||
return
|
||||
updated, untrusted = marked
|
||||
if not untrusted:
|
||||
return
|
||||
if unwritten := replace_json(config, updated, indent=2):
|
||||
print(f"could not write {config}: {unwritten.reason}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
|
||||
|
||||
|
||||
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
|
||||
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
|
||||
if not isinstance(config, dict) or not isinstance(projects := config.get("projects", {}), dict):
|
||||
return Failure('not an object whose "projects" is an object')
|
||||
if (wrong := next((path for path, settings in projects.items() if not isinstance(settings, dict)), None)) is not None:
|
||||
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
marked = {path: {**projects.get(path, {}), "hasTrustDialogAccepted": True} for path in untrusted}
|
||||
return {**config, "projects": {**projects, **marked}}, untrusted
|
||||
@@ -18,9 +18,11 @@ PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""",
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Launch:
|
||||
"""A tool a simple command runs: the launchers it runs through, such as nice and run-heavy, and the words it is given."""
|
||||
"""A tool a simple command runs: the launchers it runs through, such as nice and run-heavy; the word that names the tool, as written; the words before that word; and the tool's arguments."""
|
||||
launchers: frozenset[str]
|
||||
tool: str
|
||||
word: str
|
||||
before: list[str]
|
||||
arguments: list[str]
|
||||
|
||||
|
||||
@@ -107,4 +109,4 @@ def launched(words: list[str], tools: typing.Collection[str]) -> Launch | None:
|
||||
at = next((i for i, name in enumerate(reachable) if name in tools), None)
|
||||
if at is None:
|
||||
return None
|
||||
return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at + 1:])
|
||||
return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at], words[:at], words[at + 1:])
|
||||
@@ -1,6 +1,6 @@
|
||||
import unittest
|
||||
|
||||
from docker_command import capped
|
||||
from command_lines.docker_command import capped
|
||||
|
||||
|
||||
class Capped(unittest.TestCase):
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from deploy_release import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
@@ -0,0 +1,186 @@
|
||||
"""`deploy-release --cut`: cut the next release once it is ready, through a pull request, then tag it and move ~/.claude to it.
|
||||
|
||||
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from release_plan.release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned
|
||||
from git_cli.git_repo import default_ref, git
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from deploy_release import forge
|
||||
from chunk_preflight.choices import forge_of
|
||||
from release_plan.todo_table import items
|
||||
from release_plan.release import newest_tag, Release, version
|
||||
|
||||
|
||||
def cut(clone: str, checkout: str) -> str | Failure:
|
||||
"""What the cut did, as the tool prints it; a Failure with git's, the forge's or the tool's reason where a step stopped."""
|
||||
if isinstance(same := same_origin(clone, checkout), Failure):
|
||||
return same
|
||||
if isinstance(fetched := git("fetch", "--quiet", "--tags", "origin", cwd=clone), Failure):
|
||||
return fetched
|
||||
if isinstance(dropped := drop_unpushed_cut_tags(clone), Failure):
|
||||
return dropped
|
||||
ref = default_ref(cwd=clone)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
release = ready_release(clone, ref)
|
||||
if isinstance(release, Failure):
|
||||
return release
|
||||
named = version(release)
|
||||
title, tag = f"Cut release {named}", f"v{named}"
|
||||
merged = commit_titled(title, ref, clone)
|
||||
if merged is None:
|
||||
landed = land(clone, ref, named, title)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
if isinstance(fetched := git("fetch", "--quiet", "origin", cwd=clone), Failure):
|
||||
return fetched
|
||||
merged = commit_titled(title, ref, clone)
|
||||
if merged is None:
|
||||
return Failure(f"the pull request merged, but {ref} holds no commit titled {title!r}")
|
||||
if isinstance(merged, Failure):
|
||||
return merged
|
||||
if isinstance(made := git("tag", "--annotate", "--message", title, tag, merged, cwd=clone), Failure):
|
||||
return made
|
||||
if isinstance(pushed := git("push", "--quiet", "origin", f"refs/tags/{tag}", cwd=clone), Failure):
|
||||
# Until a rerun, chunk-preflight would read a tag only the clone holds as cut.
|
||||
git("tag", "--delete", tag, cwd=clone)
|
||||
return pushed
|
||||
moved = deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return Failure(f"cut and pushed {tag}, but moving {checkout} stopped: {moved.reason}. Fix that, then run a bare deploy-release.")
|
||||
return f"Cut {tag}.\n\n{moved}"
|
||||
|
||||
|
||||
def drop_unpushed_cut_tags(clone: str) -> Failure | None:
|
||||
"""Delete each v* tag the clone holds but origin doesn't, where it tags a commit titled `Cut release <its version>`: one a run made and never pushed, such as a run that died between the two. The clone reads cut releases from its own tags, so such a tag would read as a cut nobody published."""
|
||||
local = git("tag", "--list", "v*", "--format=%(refname:short) %(*subject)", cwd=clone)
|
||||
remote = git("ls-remote", "--tags", "--refs", "origin", "refs/tags/v*", cwd=clone)
|
||||
if isinstance(local, Failure):
|
||||
return local
|
||||
if isinstance(remote, Failure):
|
||||
return remote
|
||||
pushed = {line.split("refs/tags/", 1)[-1] for line in remote.splitlines()}
|
||||
for line in local.splitlines():
|
||||
tag, _, subject = line.partition(" ")
|
||||
if tag not in pushed and subject == f"Cut release {tag.removeprefix('v')}":
|
||||
if isinstance(deleted := git("tag", "--delete", tag, cwd=clone), Failure):
|
||||
return deleted
|
||||
return None
|
||||
|
||||
|
||||
def same_origin(clone: str, checkout: str) -> Failure | None:
|
||||
"""A Failure unless clone is a clone of the origin checkout takes its releases from, so --cut never cuts another project."""
|
||||
urls = [git("ls-remote", "--get-url", "origin", cwd=where) for where in (clone, checkout)]
|
||||
failed = next((url for url in urls if isinstance(url, Failure)), None)
|
||||
if failed is not None:
|
||||
return failed
|
||||
if urls[0] != urls[1]:
|
||||
return Failure(f"run --cut in a clone of {checkout}'s origin, {str(urls[1]).strip()}; this directory's origin is {str(urls[0]).strip()}")
|
||||
return None
|
||||
|
||||
|
||||
def ready_release(clone: str, ref: str) -> Release | Failure:
|
||||
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
|
||||
plan = default_plan(clone, ref)
|
||||
found = items(plan.todo) if isinstance(plan.todo, str) else plan.todo
|
||||
if isinstance(found, Failure):
|
||||
return Failure(f"todo.md on {ref} cannot be read: {found.reason}")
|
||||
match chunk_item(found, plan.cut):
|
||||
case ReadyToCut(release=release) if release is not None:
|
||||
return release
|
||||
case ReadyToCut():
|
||||
return Failure("todo.md names no release after the last one cut")
|
||||
case Next(release=release) if release is not None:
|
||||
return Failure(f"release {version(release)} still holds items in todo.md")
|
||||
case ReviewDue(release=release):
|
||||
return Failure(f"the release review of {version(release) if release else 'the next release'} hasn't landed")
|
||||
case Unplanned():
|
||||
return Failure("every change is released already: nothing has landed since the last release cut")
|
||||
case Cut(release=release):
|
||||
return Failure(f"todo.md files items under {version(release)}, which is cut already")
|
||||
case _:
|
||||
return Failure("cannot tell which release is next")
|
||||
|
||||
|
||||
def commit_titled(title: str, ref: str, clone: str) -> str | None | Failure:
|
||||
"""The commit titled title on ref, after the newest tag; None where there is none."""
|
||||
tag = newest_tag(clone, merged_into=ref)
|
||||
if isinstance(tag, Failure):
|
||||
return tag
|
||||
log = git("log", "--format=%H %s", f"{tag}..{ref}" if tag else ref, cwd=clone)
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
return next((line.split(" ", 1)[0] for line in log.splitlines() if line.split(" ", 1)[1:] == [title]), None)
|
||||
|
||||
|
||||
def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
|
||||
"""Push the branch release-<named> with the cut commit and open its pull request, where an earlier run hasn't; then wait for its checks and merge it."""
|
||||
url = git("config", "--get", "remote.origin.url", cwd=clone)
|
||||
if isinstance(url, Failure):
|
||||
return url
|
||||
on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/")
|
||||
head = branch_head(branch, clone)
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
behind = head is not None and behind_main(branch, head, ref, clone)
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
if head is None or behind:
|
||||
# Where main moved on, such as to fix a failed check, the branch could no longer merge fast-forward, so it is rebuilt on main.
|
||||
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title, head), Failure):
|
||||
return pushed
|
||||
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
number = forge.open_pull(on, branch, head, run)
|
||||
if number is None:
|
||||
if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure):
|
||||
return created
|
||||
number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
|
||||
if isinstance(number, Failure):
|
||||
return number
|
||||
print(f"deploy-release: waiting for the checks of pull request {number}", file=sys.stderr)
|
||||
if isinstance(passed := forge.checks_passed(on, number, head, run), Failure):
|
||||
return passed
|
||||
return forge.merge(on, number, head, run)
|
||||
|
||||
|
||||
def branch_head(branch: str, clone: str) -> str | None | Failure:
|
||||
"""The commit origin's branch points at; None where origin has no such branch."""
|
||||
listed = git("ls-remote", "--heads", "origin", f"refs/heads/{branch}", cwd=clone)
|
||||
return listed if isinstance(listed, Failure) else next(iter(listed.split()), None)
|
||||
|
||||
|
||||
def behind_main(branch: str, head: str, ref: str, clone: str) -> bool | Failure:
|
||||
"""Whether origin's branch, at head, lacks a commit ref holds."""
|
||||
if isinstance(fetched := git("fetch", "--quiet", "origin", f"refs/heads/{branch}", cwd=clone), Failure):
|
||||
return fetched
|
||||
return isinstance(git("merge-base", "--is-ancestor", ref, head, cwd=clone), Failure)
|
||||
|
||||
|
||||
def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, replacing: str | None) -> Failure | None:
|
||||
"""Commit ref's CHANGELOG.md with ## Unreleased renamed to named, in a worktree of its own so the clone's checkout stays as it is, and push it as branch: a new one, or in place of replacing, the commit origin's branch points at."""
|
||||
worktree = pathlib.Path(tempfile.mkdtemp(prefix="deploy-release-")) / "cut"
|
||||
try:
|
||||
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
|
||||
return added
|
||||
changelog = worktree / "CHANGELOG.md"
|
||||
renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE)
|
||||
if not count:
|
||||
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
|
||||
changelog.write_text(renamed)
|
||||
if isinstance(committed := git("commit", "--quiet", "-am", title, cwd=str(worktree)), Failure):
|
||||
return committed
|
||||
lease = [f"--force-with-lease=refs/heads/{branch}:{replacing}"] if replacing else []
|
||||
pushed = git("push", "--quiet", *lease, "origin", f"HEAD:refs/heads/{branch}", cwd=str(worktree))
|
||||
return pushed if isinstance(pushed, Failure) else None
|
||||
finally:
|
||||
git("worktree", "remove", "--force", str(worktree), cwd=clone)
|
||||
shutil.rmtree(worktree.parent, ignore_errors=True)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Move a checkout to this repo's newest release, as a bare `deploy-release` does."""
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git
|
||||
from release_plan.release import newest_tag, parsed, tagged
|
||||
from records.markdown_text import sections
|
||||
|
||||
|
||||
def deploy(checkout: str) -> str | Failure:
|
||||
"""What the move of checkout to the newest release did, as the tool prints it; a Failure where it refused or git failed."""
|
||||
fetched = git("fetch", "--quiet", "--tags", "origin", cwd=checkout)
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
tag = newest_tag(checkout)
|
||||
if isinstance(tag, Failure):
|
||||
return tag
|
||||
if tag is None:
|
||||
return Failure("origin has no v* tag to move to")
|
||||
# Re-reads each file through the clean filter, so a model pick alone leaves settings.json unchanged.
|
||||
if isinstance(refreshed := git("update-index", "-q", "--refresh", cwd=checkout), Failure):
|
||||
return refreshed
|
||||
changed = git("diff", "--name-only", "HEAD", cwd=checkout)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
unreleased = git("diff", "--name-only", tag, "--", *changed.split(), cwd=checkout) if changed.split() else ""
|
||||
if isinstance(unreleased, Failure):
|
||||
return unreleased
|
||||
if unreleased.split():
|
||||
return Failure(f"{checkout} has uncommitted changes that {tag} doesn't hold, to {', '.join(unreleased.split())}: merge them through the development clone and cut a release first")
|
||||
old = git("describe", "--tags", "--abbrev=0", "--match", "v*", "HEAD", cwd=checkout)
|
||||
old_tag = None if isinstance(old, Failure) else old.strip()
|
||||
at_tag = git("describe", "--tags", "--exact-match", "--match", "v*", "HEAD", cwd=checkout)
|
||||
if not isinstance(at_tag, Failure) and at_tag.strip() == tag:
|
||||
return f"Already on {tag}, the newest release."
|
||||
if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure):
|
||||
return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first")
|
||||
settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure)
|
||||
# The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy.
|
||||
if changed.split():
|
||||
restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout)
|
||||
if isinstance(restored, Failure):
|
||||
return restored
|
||||
moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout)
|
||||
if isinstance(moved, Failure):
|
||||
return moved
|
||||
changelog = git("show", f"{tag}:CHANGELOG.md", cwd=checkout)
|
||||
lines = [f"Moved from {old_tag or 'an untagged commit'} to {tag}."]
|
||||
if settings_changed:
|
||||
lines.append("settings.json changed: pick the model again with /model.")
|
||||
if not isinstance(changelog, Failure):
|
||||
lines += newer_sections(changelog, old_tag)
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def newer_sections(changelog: str, old_tag: str | None) -> list[str]:
|
||||
"""Each `## <version>` section of changelog newer than old_tag, newest first, as it reads."""
|
||||
since = tagged(old_tag)
|
||||
found = []
|
||||
for heading, bodies in sections(changelog).items():
|
||||
named = parsed(heading)
|
||||
if named is None:
|
||||
continue
|
||||
if since is None or named > since:
|
||||
found.append(f"## {heading}\n\n" + "\n".join(bodies))
|
||||
return found
|
||||
@@ -0,0 +1,101 @@
|
||||
"""The pull request steps of a cut. They run gh where origin is on GitHub and tea elsewhere, as chunk_preflight tells the two apart.
|
||||
|
||||
Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from chunk_preflight.choices import Forge
|
||||
|
||||
# How long the cut waits between two reads of the head commit's status on Gitea.
|
||||
POLL_SECONDS = 10
|
||||
|
||||
# Runs a command in the clone: what it printed, or a Failure with its reason.
|
||||
Run = typing.Callable[[list[str]], str | Failure]
|
||||
|
||||
|
||||
def runner(cwd: str) -> Run:
|
||||
def run(command: list[str]) -> str | Failure:
|
||||
try:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
|
||||
except OSError as failure:
|
||||
return Failure(f"{command[0]} could not start: {failure}")
|
||||
if done.returncode:
|
||||
return Failure(f"{' '.join(command[:3])}: {(done.stderr or done.stdout).strip()}")
|
||||
return done.stdout
|
||||
return run
|
||||
|
||||
|
||||
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
|
||||
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer with Gitea's `message` key is a Failure."""
|
||||
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
|
||||
if isinstance(answered, Failure) or not answered.strip():
|
||||
return answered
|
||||
try:
|
||||
parsed = json.loads(answered)
|
||||
except ValueError:
|
||||
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
|
||||
if isinstance(parsed, dict) and "message" in parsed:
|
||||
return Failure(f"tea api {endpoint}: {parsed['message']}")
|
||||
return parsed
|
||||
|
||||
|
||||
def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
|
||||
"""The number of the open pull request from origin's own branch whose head is head; None where there is none."""
|
||||
if forge == "gh":
|
||||
listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"])
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
rows = [line.split("\t") for line in listed.splitlines()]
|
||||
return next((row[0] for row in rows if row[1:] == [head, "false"]), None)
|
||||
# Gitea lists at most 50 a page; a release's pull request is among the newest.
|
||||
pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50")
|
||||
if isinstance(pulls, Failure):
|
||||
return pulls
|
||||
try:
|
||||
return next((str(pull["number"]) for pull in pulls if pull["head"]["ref"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"]), None)
|
||||
except (KeyError, TypeError):
|
||||
return Failure(f"tea api listed pull requests in a shape the cut doesn't read: {str(pulls)[:200]}")
|
||||
|
||||
|
||||
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
|
||||
body = ["--body" if forge == "gh" else "--description", "Rename ## Unreleased in CHANGELOG.md to the version."]
|
||||
command = ["gh", "pr"] if forge == "gh" else ["tea", "pulls"]
|
||||
created = run([*command, "create", "--head", branch, "--base", base, "--title", title, *body])
|
||||
return created if isinstance(created, Failure) else None
|
||||
|
||||
|
||||
def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
|
||||
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails."""
|
||||
if forge == "gh":
|
||||
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
|
||||
if isinstance(watched, Failure) and "no checks reported" not in watched.reason:
|
||||
return watched
|
||||
return None
|
||||
while True:
|
||||
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
|
||||
if isinstance(status, Failure):
|
||||
return status
|
||||
try:
|
||||
count, state = status["total_count"], status["state"]
|
||||
except (KeyError, TypeError):
|
||||
return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}")
|
||||
# Gitea reads a commit with no status as pending, with total_count 0.
|
||||
if count == 0 or state == "success":
|
||||
return None
|
||||
if state != "pending":
|
||||
return Failure(f"a check on pull request {number} ended in {state}")
|
||||
sleep(POLL_SECONDS)
|
||||
|
||||
|
||||
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
|
||||
"""Merge pull request number, fast-forward only on Gitea and by rebase on GitHub. The forge refuses where the pull request's head is no longer head."""
|
||||
if forge == "gh":
|
||||
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
|
||||
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
|
||||
else:
|
||||
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
|
||||
return merged if isinstance(merged, Failure) else None
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Move the checkout Claude Code reads its configuration from to this repo's newest release; with --cut, first cut the next release.
|
||||
|
||||
usage: deploy-release [--cut] [<checkout>]
|
||||
|
||||
<checkout> defaults to ~/.claude. The tool fetches origin's tags and checks out the newest v* tag,
|
||||
detached, so the checkout holds only what a release holds. Development happens in another clone,
|
||||
such as ~/code/claude-config. It prints the version it moved from and to, then CHANGELOG.md's
|
||||
section for each version since, so you can do what each asks, such as a new step under Install.
|
||||
Where the move changed settings.json, it asks you to pick the model again with /model, since git's
|
||||
clean filter keeps the model out of every commit.
|
||||
|
||||
It refuses, exit 1, and leaves the checkout as it was where a file the checkout tracks has an
|
||||
uncommitted change the newest tag doesn't hold: such as a hook Claude Code wrote into settings.json.
|
||||
Merge the change through the development clone and cut a release first. A model picked with /model
|
||||
is no such change. It also refuses where the newest tag doesn't hold the checkout's commit, since
|
||||
the move would drop work no release holds. Untracked files, such as Claude Code's sessions and
|
||||
memory, stay as they are.
|
||||
|
||||
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
|
||||
refuses, changing nothing, unless that release holds no item in todo.md, its release review has
|
||||
landed and changes are unreleased. The release names the version; the tool doesn't choose one.
|
||||
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
|
||||
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
|
||||
checkout stays as it is. Where main has moved past the branch, it rebuilds the branch on main.
|
||||
2. It opens a pull request for the branch, with gh on a GitHub origin and tea elsewhere, waits for
|
||||
its checks where there are any, and merges it fast-forward only. GitHub has no such merge, so
|
||||
there it rebase-merges the branch, which is already on top of main.
|
||||
3. It tags the merged commit v<version>, annotated `Cut release <version>`, pushes only the tag,
|
||||
then moves <checkout> to it as above.
|
||||
Where a step fails it stops, exit 1, with git's or the forge's reason, and leaves the pull request
|
||||
and the branch as they are. A rerun continues: it takes the branch's open pull request and a cut
|
||||
commit already merged, and drops a cut tag an earlier run made but never pushed. Once the tag is pushed, the release is cut: where only the
|
||||
move stopped, fix what it names and run a bare deploy-release.
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from deploy_release.cut import cut
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
cutting = argv[:1] == ["--cut"]
|
||||
rest = argv[1:] if cutting else argv
|
||||
if len(rest) > 1 or rest[:1] and rest[0].startswith("-"):
|
||||
print("deploy-release: usage: deploy-release [--cut] [<checkout>]", file=sys.stderr)
|
||||
return 1
|
||||
checkout = rest[0] if rest else str(pathlib.Path.home() / ".claude")
|
||||
moved = cut(os.getcwd(), checkout) if cutting else deploy(checkout)
|
||||
if isinstance(moved, Failure):
|
||||
print(f"deploy-release: {moved.reason}", file=sys.stderr)
|
||||
return 1
|
||||
print(moved)
|
||||
return 0
|
||||
@@ -0,0 +1,461 @@
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from deploy_release.forge import checks_passed, POLL_SECONDS
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "deploy-release"
|
||||
|
||||
|
||||
class DeployRelease(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
||||
self.origin = self.temp / "origin.git"
|
||||
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
|
||||
self.source = self.temp / "source"
|
||||
self.git(self.temp, "clone", "-q", str(self.origin), str(self.source))
|
||||
self.release("0.1.0", "- First.\n", '{"theme": "dark"}\n')
|
||||
self.target = self.temp / "dot-claude"
|
||||
self.git(self.temp, "clone", "-q", str(self.origin), str(self.target))
|
||||
self.git(self.target, "checkout", "-q", "--detach", "v0.1.0")
|
||||
|
||||
def git(self, cwd: pathlib.Path, *args: str) -> str:
|
||||
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env(), text=True).stdout
|
||||
|
||||
def release(self, version: str, entry: str, settings: str) -> None:
|
||||
"""Commit a CHANGELOG.md whose newest section is version's, holding entry, and settings.json, then tag it and push both."""
|
||||
changelog = self.source / "CHANGELOG.md"
|
||||
earlier = changelog.read_text().removeprefix("# Changelog\n\n") if changelog.exists() else ""
|
||||
changelog.write_text(f"# Changelog\n\n## {version}\n\n{entry}\n{earlier}")
|
||||
(self.source / "settings.json").write_text(settings)
|
||||
self.git(self.source, "add", "-A")
|
||||
self.git(self.source, "commit", "-q", "-m", f"Cut release {version}")
|
||||
self.git(self.source, "tag", f"v{version}")
|
||||
self.git(self.source, "push", "-q", "origin", "main", "--tags")
|
||||
|
||||
def deploy(self) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), str(self.target)], capture_output=True, env=isolated_env(), text=True)
|
||||
|
||||
def head(self) -> str:
|
||||
return self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip()
|
||||
|
||||
def test_moves_the_checkout_to_the_newest_tag_and_prints_each_newer_versions_changelog(self):
|
||||
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
|
||||
self.release("0.3.0", "- Third: run `make thing` once.\n", '{"theme": "dark"}\n')
|
||||
(self.source / "CHANGELOG.md").write_text("# Changelog\n\n## Unreleased\n\n- Later.\n\n" + (self.source / "CHANGELOG.md").read_text().removeprefix("# Changelog\n\n"))
|
||||
self.git(self.source, "commit", "-q", "-am", "Later work")
|
||||
self.git(self.source, "push", "-q", "origin", "main")
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertEqual(self.head(), "v0.3.0")
|
||||
self.assertIn("Moved from v0.1.0 to v0.3.0.", ran.stdout)
|
||||
self.assertIn("## 0.3.0\n\n- Third: run `make thing` once.", ran.stdout)
|
||||
self.assertIn("## 0.2.0\n\n- Second.", ran.stdout)
|
||||
self.assertNotIn("First.", ran.stdout)
|
||||
self.assertNotIn("Later.", ran.stdout)
|
||||
self.assertNotIn("/model", ran.stdout)
|
||||
|
||||
def test_stops_with_gits_error_where_the_index_cannot_be_refreshed(self):
|
||||
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
|
||||
(self.target / ".git" / "index").write_bytes(b"DIRC")
|
||||
ran = self.deploy()
|
||||
self.assertNotEqual(ran.returncode, 0)
|
||||
self.assertIn("index", ran.stderr)
|
||||
self.assertNotIn("uncommitted", ran.stderr)
|
||||
self.assertEqual(self.git(self.target, "rev-parse", "HEAD"), self.git(self.source, "rev-parse", "v0.1.0^{commit}"))
|
||||
|
||||
def test_says_so_where_the_checkout_is_on_the_newest_tag_already(self):
|
||||
ran = self.deploy()
|
||||
self.assertEqual((ran.returncode, ran.stdout), (0, "Already on v0.1.0, the newest release.\n"))
|
||||
|
||||
def test_refuses_an_uncommitted_change_to_a_tracked_file_and_leaves_the_checkout_as_it_was(self):
|
||||
self.release("0.2.0", "- Second.\n", '{"theme": "dark"}\n')
|
||||
(self.target / "CHANGELOG.md").write_text("Edited here.\n")
|
||||
(self.target / "projects").mkdir()
|
||||
(self.target / "projects" / "session.jsonl").write_text("{}\n")
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("CHANGELOG.md", ran.stderr)
|
||||
self.assertNotIn("projects", ran.stderr, "an untracked file is Claude Code's own state, not a change")
|
||||
self.assertEqual(self.head(), "v0.1.0")
|
||||
|
||||
def test_takes_an_uncommitted_change_the_new_release_holds_as_no_change(self):
|
||||
(self.target / "settings.json").write_text('{"theme": "light"}\n')
|
||||
self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n')
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertEqual(self.head(), "v0.2.0")
|
||||
|
||||
def test_refuses_to_move_a_checkout_back_from_commits_no_release_holds(self):
|
||||
self.git(self.target, "switch", "-q", "main")
|
||||
(self.source / "new.md").write_text("Unreleased.\n")
|
||||
self.git(self.source, "add", "-A")
|
||||
self.git(self.source, "commit", "-q", "-m", "Unreleased work")
|
||||
self.git(self.source, "push", "-q", "origin", "main")
|
||||
self.git(self.target, "pull", "-q", "--ff-only")
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("v0.1.0 doesn't hold", ran.stderr)
|
||||
self.assertEqual(self.git(self.target, "branch", "--show-current").strip(), "main")
|
||||
|
||||
def test_takes_a_model_picked_with_the_clean_filter_set_as_no_change(self):
|
||||
self.release("0.2.0", "- Second.\n", '{\n "theme": "dark"\n}\n')
|
||||
self.git(self.target, "fetch", "-q", "--tags", "origin")
|
||||
self.git(self.target, "checkout", "-q", "--detach", "v0.2.0")
|
||||
(self.target / ".gitattributes").write_text("/settings.json filter=settings\n")
|
||||
self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {TOOL.parent / 'settings_filter.py'}")
|
||||
(self.target / "settings.json").write_text('{"model": "claude-opus-5-5", "theme": "dark"}\n')
|
||||
self.release("0.3.0", "- Third.\n", '{\n "theme": "dark"\n}\n')
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertEqual(self.head(), "v0.3.0")
|
||||
self.assertIn('"model"', (self.target / "settings.json").read_text(), "a release that leaves settings.json as it was keeps the pick")
|
||||
|
||||
def test_asks_for_the_model_again_where_the_release_changes_settings_json(self):
|
||||
self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n')
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
|
||||
|
||||
|
||||
TODO = """# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = 100 * V / (2**S + 8)`
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 3`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
"""
|
||||
ROW = "| {id} | {release} | | | **Do thing {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# A fake forge, run as tea or as gh. It keeps origin's pull requests in <temp>/forge.json. Its merge moves origin's main only by fast-forward.
|
||||
FAKE_FORGE = """#!PYTHON
|
||||
import json, pathlib, subprocess, sys
|
||||
forge, args = pathlib.Path(sys.argv[0]).name, sys.argv[1:]
|
||||
state_file = pathlib.Path(__file__).resolve().parent.parent / "forge.json"
|
||||
state = json.loads(state_file.read_text())
|
||||
state["calls"].append([forge, *args])
|
||||
def save():
|
||||
state_file.write_text(json.dumps(state))
|
||||
def git(*words):
|
||||
return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True)
|
||||
def pull(number):
|
||||
return next(found for found in state["pulls"] if str(found["number"]) == number)
|
||||
# A fork's head as given; origin's own pull request follows its branch, as a forge does.
|
||||
def sha(found):
|
||||
return found.get("sha") or git("rev-parse", "refs/heads/" + found["head"]).stdout.strip()
|
||||
def merge(number, guard):
|
||||
head = sha(pull(number))
|
||||
if state.get("refuse_merge"):
|
||||
save()
|
||||
sys.exit("Not possible to fast-forward")
|
||||
if head != guard:
|
||||
save()
|
||||
sys.exit("head commit changed")
|
||||
if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode:
|
||||
save()
|
||||
sys.exit("Not possible to fast-forward")
|
||||
git("update-ref", "refs/heads/main", head)
|
||||
pull(number)["state"] = "merged"
|
||||
opened = [found for found in state["pulls"] if found["state"] == "open"]
|
||||
if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]:
|
||||
repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"}
|
||||
print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "sha": sha(found), "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened]))
|
||||
elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]:
|
||||
for found in opened:
|
||||
if found["head"] == args[3]:
|
||||
print(f"{found['number']}\t{sha(found)}\t{str(found['fork']).lower()}")
|
||||
elif args[:2] in (["pulls", "create"], ["pr", "create"]):
|
||||
head = args[args.index("--head") + 1]
|
||||
if any(found["head"] == head and not found["fork"] for found in opened):
|
||||
save()
|
||||
sys.exit("pull request already exists for these targets")
|
||||
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "fork": False, "state": "open"})
|
||||
elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"):
|
||||
checks = state["checks"]
|
||||
print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1}))
|
||||
elif forge == "gh" and args[:2] == ["pr", "checks"]:
|
||||
if state["checks"] == "none":
|
||||
save()
|
||||
sys.exit("no checks reported on the 'release' branch")
|
||||
if state["checks"] == "failure":
|
||||
save()
|
||||
sys.exit("lint\tfail")
|
||||
elif forge == "tea" and args[:5] == ["api", "--method", "POST", "--field", "Do=fast-forward-only"] and args[5] == "--field" and args[7].endswith("/merge"):
|
||||
try:
|
||||
merge(args[7].split("/")[-2], args[6].removeprefix("head_commit_id="))
|
||||
except SystemExit as refused:
|
||||
# Gitea answers an error with a message, and tea api exits 0 all the same.
|
||||
print(json.dumps({"message": str(refused)}))
|
||||
elif args[:2] == ["pr", "merge"] and args[3:5] == ["--rebase", "--match-head-commit"]:
|
||||
merge(args[2], args[5])
|
||||
else:
|
||||
save()
|
||||
sys.exit("unexpected call")
|
||||
save()
|
||||
""".replace("PYTHON", sys.executable)
|
||||
|
||||
|
||||
class Cut(unittest.TestCase):
|
||||
"""A development clone whose next release, 0.2.0, holds no item, has its release review landed and one change unreleased; and a ~/.claude on v0.1.0."""
|
||||
|
||||
def setUp(self):
|
||||
self.temp = pathlib.Path(os.path.realpath(tempfile.mkdtemp()))
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(self.temp)])
|
||||
self.origin = self.temp / "origin.git"
|
||||
fake = self.temp / "fake-bin"
|
||||
fake.mkdir()
|
||||
for name in ("tea", "gh"):
|
||||
(fake / name).write_text(FAKE_FORGE)
|
||||
(fake / name).chmod(0o755)
|
||||
(self.temp / "gitconfig").write_text("[user]\n\tname = t\n\temail = t@t\n")
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": str(self.temp / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1", "PATH": f"{fake}:{os.environ['PATH']}"}
|
||||
self.forge_state({"origin": str(self.origin), "pulls": [], "checks": "none", "calls": []})
|
||||
self.git(self.temp, "init", "-q", "--bare", "-b", "main", str(self.origin))
|
||||
self.clone = self.temp / "claude-config"
|
||||
self.git(self.temp, "clone", "-q", str(self.origin), str(self.clone))
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Start")
|
||||
self.git(self.clone, "tag", "-a", "v0.1.0", "-m", "Cut release 0.1.0")
|
||||
self.commit({"CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- Second.\n\n## 0.1.0\n\n- First.\n", "todo.md": TODO + ROW.format(id=2, release="0.3.0")}, "Ship item 1")
|
||||
self.git(self.clone, "commit", "-q", "--allow-empty", "-m", "Release review of 0.2.0")
|
||||
self.git(self.clone, "push", "-q", "origin", "main", "--tags")
|
||||
self.target = self.temp / "dot-claude"
|
||||
self.git(self.temp, "clone", "-q", str(self.origin), str(self.target))
|
||||
self.git(self.target, "checkout", "-q", "--detach", "v0.1.0")
|
||||
|
||||
def git(self, cwd: pathlib.Path, *args: str) -> str:
|
||||
return subprocess.run(["git", *args], capture_output=True, check=True, cwd=cwd, env=self.env, text=True).stdout
|
||||
|
||||
def commit(self, files: dict[str, str], title: str) -> None:
|
||||
for name, text in files.items():
|
||||
(self.clone / name).write_text(text)
|
||||
self.git(self.clone, "add", "-A")
|
||||
self.git(self.clone, "commit", "-q", "-m", title)
|
||||
|
||||
def forge_state(self, state: dict | None = None) -> dict:
|
||||
if state is not None:
|
||||
(self.temp / "forge.json").write_text(json.dumps(state))
|
||||
return json.loads((self.temp / "forge.json").read_text())
|
||||
|
||||
def set_checks(self, checks: str) -> None:
|
||||
self.forge_state({**self.forge_state(), "checks": checks})
|
||||
|
||||
def cut(self) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), "--cut", str(self.target)], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
||||
|
||||
def origin_git(self, *args: str) -> str:
|
||||
return self.git(self.temp, "--git-dir", str(self.origin), *args)
|
||||
|
||||
def assert_cut(self, ran: subprocess.CompletedProcess[str]) -> None:
|
||||
"""origin's main ends in the cut commit, tagged v0.2.0, and ~/.claude is on that tag."""
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0")
|
||||
changelog = self.origin_git("show", "main:CHANGELOG.md")
|
||||
self.assertIn("## 0.2.0\n\n- Second.", changelog)
|
||||
self.assertNotIn("Unreleased", changelog)
|
||||
self.assertEqual(self.origin_git("rev-parse", "v0.2.0^{commit}"), self.origin_git("rev-parse", "main"))
|
||||
self.assertEqual(self.origin_git("cat-file", "-t", "v0.2.0").strip(), "tag", "the tag is annotated")
|
||||
self.assertEqual(self.origin_git("tag", "-l", "--format=%(contents:subject)", "v0.2.0").strip(), "Cut release 0.2.0")
|
||||
self.assertEqual(self.git(self.target, "describe", "--tags", "--exact-match", "HEAD").strip(), "v0.2.0")
|
||||
|
||||
def test_cuts_the_next_release_through_a_tea_pull_request_merged_fast_forward_then_tags_and_deploys_it(self):
|
||||
head = self.git(self.clone, "rev-parse", "HEAD")
|
||||
ran = self.cut()
|
||||
self.assert_cut(ran)
|
||||
self.assertIn("v0.2.0", ran.stdout)
|
||||
calls = self.forge_state()["calls"]
|
||||
self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
|
||||
self.assertIn("Do=fast-forward-only", [word for call in calls if call[-1].endswith("/pulls/1/merge") for word in call])
|
||||
self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was")
|
||||
self.assertEqual(self.git(self.clone, "status", "--porcelain"), "")
|
||||
|
||||
def test_cuts_through_gh_on_a_github_origin(self):
|
||||
self.use_github()
|
||||
ran = self.cut()
|
||||
self.assert_cut(ran)
|
||||
calls = self.forge_state()["calls"]
|
||||
self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
|
||||
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], [call[:5] for call in calls])
|
||||
|
||||
def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self):
|
||||
self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again")
|
||||
self.git(self.clone, "push", "-q", "origin", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("0.2.0", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["pulls"], [])
|
||||
self.assertEqual(self.origin_git("branch", "--list", "release-*"), "")
|
||||
|
||||
def test_refuses_changing_nothing_until_the_release_review_has_landed(self):
|
||||
self.git(self.clone, "reset", "-q", "--hard", "HEAD~1")
|
||||
self.git(self.clone, "push", "-q", "--force", "origin", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("release review", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["pulls"], [])
|
||||
|
||||
def test_stops_on_a_failing_check_leaving_the_pull_request_and_a_rerun_continues_it(self):
|
||||
self.set_checks("failure")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("failure", ran.stderr)
|
||||
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"])
|
||||
self.assertNotEqual(self.origin_git("branch", "--list", "release-0.2.0"), "")
|
||||
self.assertEqual(self.origin_git("tag", "-l", "v0.2.0"), "")
|
||||
self.set_checks("success")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request")
|
||||
|
||||
def test_stops_with_the_forges_reason_where_it_refuses_the_merge(self):
|
||||
self.forge_state({**self.forge_state(), "refuse_merge": True})
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("Not possible to fast-forward", ran.stderr)
|
||||
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open"])
|
||||
|
||||
def test_a_rerun_rebuilds_the_cut_commit_on_main_where_main_moved_past_the_branch(self):
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
self.commit({"other.md": "Later.\n"}, "Fix the check")
|
||||
self.git(self.clone, "push", "-q", "origin", "main")
|
||||
self.set_checks("success")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main~1").strip(), "Fix the check")
|
||||
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun takes the open pull request")
|
||||
|
||||
def test_deletes_the_tag_it_made_where_its_push_fails_so_a_rerun_tags_again(self):
|
||||
hook = self.origin / "hooks" / "pre-receive"
|
||||
hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then echo 'tags are refused' >&2; exit 1; fi\n")
|
||||
hook.chmod(0o755)
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("tags are refused", ran.stderr)
|
||||
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0"), "")
|
||||
hook.unlink()
|
||||
self.assert_cut(self.cut())
|
||||
|
||||
def test_refuses_changing_nothing_where_the_clone_is_not_a_clone_of_the_checkouts_origin(self):
|
||||
self.git(self.target, "remote", "set-url", "origin", str(self.temp / "other.git"))
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("origin", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["pulls"], [])
|
||||
|
||||
def test_says_which_pull_request_it_waits_for(self):
|
||||
ran = self.cut()
|
||||
self.assertIn("pull request 1", ran.stderr)
|
||||
|
||||
def test_stops_where_the_tag_exists_on_another_commit_and_a_rerun_tags_the_merged_commit(self):
|
||||
self.git(self.clone, "switch", "-q", "-c", "side")
|
||||
self.commit({"side.md": "Side.\n"}, "Side")
|
||||
self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Wrong")
|
||||
self.git(self.clone, "push", "-q", "origin", "side", "v0.2.0")
|
||||
self.git(self.clone, "switch", "-q", "main")
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("v0.2.0", ran.stderr)
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Cut release 0.2.0")
|
||||
self.git(self.clone, "tag", "-d", "v0.2.0")
|
||||
self.origin_git("tag", "-d", "v0.2.0")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request")
|
||||
|
||||
def use_github(self) -> None:
|
||||
"""Point the clone's origin at a GitHub URL that git reads as the local origin, so the cut runs gh."""
|
||||
self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git")
|
||||
self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git")
|
||||
|
||||
def assert_fork_pull_ignored(self) -> None:
|
||||
"""After a failed first run, a fork opens a pull request from its own release-0.2.0, listed first; the rerun merges only origin's."""
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0")
|
||||
self.commit({"settings.json": "{}\n"}, "Cut release 0.2.0")
|
||||
self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0")
|
||||
self.git(self.clone, "switch", "-q", "main")
|
||||
state = self.forge_state()
|
||||
fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"}
|
||||
self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"})
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"])
|
||||
self.assertNotIn("settings.json", self.origin_git("ls-tree", "--name-only", "main"))
|
||||
|
||||
def test_merges_only_origins_own_pull_request_on_tea_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
|
||||
self.assert_fork_pull_ignored()
|
||||
|
||||
def test_merges_only_origins_own_pull_request_on_gh_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
|
||||
self.use_github()
|
||||
self.assert_fork_pull_ignored()
|
||||
|
||||
def test_a_rerun_drops_a_cut_tag_an_earlier_run_made_but_never_pushed(self):
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
self.set_checks("success")
|
||||
hook = self.origin / "hooks" / "pre-receive"
|
||||
hook.write_text("#!/bin/sh\nif grep -q refs/tags/; then exit 1; fi\n")
|
||||
hook.chmod(0o755)
|
||||
self.cut()
|
||||
# A run that died between tagging and pushing left this tag behind.
|
||||
self.git(self.clone, "fetch", "-q", "origin")
|
||||
self.git(self.clone, "tag", "-a", "v0.2.0", "-m", "Cut release 0.2.0", "origin/main")
|
||||
hook.unlink()
|
||||
self.assert_cut(self.cut())
|
||||
|
||||
def test_keeps_a_pushed_cut_tag_and_an_unpushed_tag_on_any_other_commit(self):
|
||||
self.git(self.clone, "switch", "-q", "-c", "side")
|
||||
self.commit({"side.md": "Side.\n"}, "Side")
|
||||
self.git(self.clone, "tag", "-a", "v9.9.9", "-m", "Mine")
|
||||
self.git(self.clone, "switch", "-q", "main")
|
||||
self.assert_cut(self.cut())
|
||||
self.assertEqual(self.cut().returncode, 1, "0.2.0 is cut, so a second run refuses")
|
||||
self.assertEqual(self.git(self.clone, "tag", "-l", "v0.2.0", "v9.9.9").split(), ["v0.2.0", "v9.9.9"])
|
||||
|
||||
def test_takes_no_option_but_cut(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "--cut", "--force"], capture_output=True, cwd=self.clone, env=self.env, text=True)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("usage", ran.stderr)
|
||||
self.assertEqual(self.forge_state()["calls"], [])
|
||||
|
||||
def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self):
|
||||
self.set_checks("failure")
|
||||
self.cut()
|
||||
state = self.forge_state()
|
||||
state["pulls"][0]["sha"] = "0" * 40
|
||||
self.forge_state({**state, "checks": "success"})
|
||||
ran = self.cut()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("already exists", ran.stderr)
|
||||
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
|
||||
|
||||
|
||||
class ChecksPassed(unittest.TestCase):
|
||||
def test_waits_on_tea_while_a_check_is_pending(self):
|
||||
statuses = iter(['{"state": "pending", "total_count": 1}', '{"state": "success", "total_count": 1}'])
|
||||
slept = []
|
||||
self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: next(statuses), slept.append))
|
||||
self.assertEqual(slept, [POLL_SECONDS])
|
||||
|
||||
def test_takes_a_commit_with_no_status_on_tea_as_passed(self):
|
||||
self.assertIsNone(checks_passed("tea", "1", "abc", lambda command: '{"state": "pending", "total_count": 0}', self.fail))
|
||||
|
||||
def test_fails_on_tea_where_a_check_failed(self):
|
||||
self.assertIsInstance(checks_passed("tea", "1", "abc", lambda command: '{"state": "failure", "total_count": 1}', self.fail), Failure)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,24 +1,26 @@
|
||||
import dataclasses
|
||||
|
||||
from shell_command import resolved, Simple
|
||||
from command_lines.shell_command import resolved, Simple
|
||||
|
||||
# git's global options that take a value as the next word.
|
||||
GIT_VALUED = {"-C", "-c", "--exec-path", "--git-dir", "--namespace", "--work-tree"}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Commit:
|
||||
class CommitCall:
|
||||
"""A `git commit` a shell command runs: the directory it runs in, its messages, whether it reads its message from a file, and whether it amends."""
|
||||
directory: str
|
||||
messages: list[str]
|
||||
from_file: bool
|
||||
amends: bool
|
||||
|
||||
|
||||
def commits(simples: list[Simple], home: str) -> list[Commit]:
|
||||
def commits(simples: list[Simple], home: str) -> list[CommitCall]:
|
||||
found = []
|
||||
for simple in simples:
|
||||
invoked = git_subcommand(simple.words, simple.directory, home)
|
||||
if invoked and invoked[0] == "commit":
|
||||
found.append(Commit(invoked[2], *commit_message(invoked[1])))
|
||||
found.append(CommitCall(invoked[2], *commit_message(invoked[1])))
|
||||
return found
|
||||
|
||||
|
||||
@@ -36,14 +38,16 @@ def git_subcommand(words: list[str], directory: str, home: str) -> tuple[str, li
|
||||
return None
|
||||
|
||||
|
||||
def commit_message(args: list[str]) -> tuple[list[str], bool]:
|
||||
"""git commit's messages, and whether it reads one from a file."""
|
||||
def commit_message(args: list[str]) -> tuple[list[str], bool, bool]:
|
||||
"""git commit's messages, whether it reads one from a file, and whether it amends."""
|
||||
messages = []
|
||||
from_file = False
|
||||
amends = False
|
||||
words = iter(args)
|
||||
for word in words:
|
||||
if word == "--":
|
||||
break
|
||||
amends = amends or word == "--amend"
|
||||
name, equals, value = word.partition("=")
|
||||
if name in ("--message", "--file"):
|
||||
given = value if equals else next(words, "")
|
||||
@@ -55,4 +59,4 @@ def commit_message(args: list[str]) -> tuple[list[str], bool]:
|
||||
continue
|
||||
messages += [given] if name == "--message" else []
|
||||
from_file = from_file or name == "--file"
|
||||
return messages, from_file
|
||||
return messages, from_file, amends
|
||||
@@ -1,9 +1,11 @@
|
||||
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files.
|
||||
|
||||
Every tool in bin/ starts git through `git` here."""
|
||||
import functools
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
@@ -21,10 +23,11 @@ GUARD_SETTINGS = [
|
||||
]
|
||||
|
||||
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> str | Failure:
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure:
|
||||
"""What git printed, run in cwd, else in the current directory.
|
||||
|
||||
A Failure where git cannot start, exits non-zero, prints text that is not UTF-8, or still runs after timeout seconds, which stops it.
|
||||
errors "replace" reads each byte that is not UTF-8 as U+FFFD instead of failing. It is for output, such as a diff, whose file text the caller skips.
|
||||
guarded turns off the fsmonitor, the signature check, each transport GUARD_SETTINGS names and a partial clone's fetch of its missing objects. It is for a checkout whose config may name a program.
|
||||
"""
|
||||
command = " ".join(args)
|
||||
@@ -32,7 +35,7 @@ def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarde
|
||||
# GIT_NO_LAZY_FETCH needs git 2.44.
|
||||
env = {**os.environ, "GIT_NO_LAZY_FETCH": "1"} if guarded else None
|
||||
try:
|
||||
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", env=env, timeout=timeout)
|
||||
ran = subprocess.run(["git", *guards, *args], capture_output=True, cwd=cwd, encoding="utf-8", errors=errors, env=env, timeout=timeout)
|
||||
except UnicodeDecodeError as failure:
|
||||
return Failure(f"git {command} printed text that is not UTF-8: {failure}")
|
||||
except (OSError, ValueError) as failure:
|
||||
@@ -42,6 +45,16 @@ def git(*args: str, cwd: str | None = None, timeout: float | None = None, guarde
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {command}: {ran.stderr.strip()}")
|
||||
|
||||
|
||||
class Git(typing.Protocol):
|
||||
"""Runs git as `git` does."""
|
||||
|
||||
def __call__(self, *args: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False, errors: str = "strict") -> str | Failure: ...
|
||||
|
||||
|
||||
# Runs git with the given arguments, in the checkout and with the options its caller bound, as functools.partial(git, cwd=...) does.
|
||||
Run = typing.Callable[..., str | Failure]
|
||||
|
||||
|
||||
def top() -> str | Failure:
|
||||
found = git("rev-parse", "--show-toplevel")
|
||||
return found if isinstance(found, Failure) else found.strip()
|
||||
@@ -60,23 +73,35 @@ def default_branch(stale_ok: bool, timeout: float | None = None) -> tuple[str, s
|
||||
return ref if isinstance(ref, Failure) else (ref, note)
|
||||
|
||||
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. Asking origin, where the checkout records no default branch for it, fails after timeout seconds."""
|
||||
remotes = git("remote", cwd=cwd)
|
||||
def default_ref(cwd: str | None = None, timeout: float | None = None, guarded: bool = False, run: Git = git) -> str | Failure:
|
||||
"""The default branch's ref as last fetched, read in cwd, else in the current directory: `origin/<branch>` with that remote, else the local main or master. run runs git.
|
||||
|
||||
Where the checkout records no default branch for origin, it asks origin, which fails after timeout seconds. Guarded, it runs git as `git` does with guarded, and fails there instead of asking origin."""
|
||||
remotes = run("remote", cwd=cwd, guarded=guarded)
|
||||
if isinstance(remotes, Failure):
|
||||
return remotes
|
||||
if "origin" in remotes.split():
|
||||
recorded = git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd)
|
||||
return recorded.strip() if not isinstance(recorded, Failure) else origin_head(cwd, timeout)
|
||||
recorded = run("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=cwd, guarded=guarded)
|
||||
if not isinstance(recorded, Failure):
|
||||
return recorded.strip()
|
||||
return Failure("origin records no default branch") if guarded else origin_head(cwd, timeout, run)
|
||||
for branch in ("main", "master"):
|
||||
if not isinstance(git("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd), Failure):
|
||||
if not isinstance(run("rev-parse", "--quiet", "--verify", f"refs/heads/{branch}", cwd=cwd, guarded=guarded), Failure):
|
||||
return branch
|
||||
return Failure("no origin remote, and no main or master branch to take as the default branch")
|
||||
|
||||
|
||||
def origin_head(cwd: str | None, timeout: float | None) -> str | Failure:
|
||||
def branch_titles(default: str, cwd: str | None = None, timeout: float | None = None, guarded: bool = False) -> list[str] | Failure:
|
||||
"""The titles of the branch's own commits since default, newest first, read in cwd, else in the current directory.
|
||||
|
||||
--first-parent leaves out the commits a merge brought in, such as those of a default branch newer than the one the checkout last fetched."""
|
||||
titles = git("log", "--first-parent", "--format=%s", f"{default}..HEAD", cwd=cwd, timeout=timeout, guarded=guarded)
|
||||
return titles if isinstance(titles, Failure) else titles.splitlines()
|
||||
|
||||
|
||||
def origin_head(cwd: str | None, timeout: float | None, run: Git) -> str | Failure:
|
||||
"""The default branch origin names, for a clone made by `git init` and `git remote add`, which records none."""
|
||||
listed = git("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
|
||||
listed = run("ls-remote", "--symref", "origin", "HEAD", cwd=cwd, timeout=timeout)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
if named := re.match(r"ref: refs/heads/(\S+)\tHEAD", listed):
|
||||
@@ -84,13 +109,6 @@ def origin_head(cwd: str | None, timeout: float | None) -> str | Failure:
|
||||
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
|
||||
|
||||
|
||||
def newest_release_tag(branch: str, cwd: str | None = None) -> str | None | Failure:
|
||||
"""The newest `v*` tag merged into branch, read in cwd, else in the current directory; None when it has none."""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0.
|
||||
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", branch, "--sort=-v:refname", cwd=cwd)
|
||||
return tags if isinstance(tags, Failure) else next(iter(tags.split()), None)
|
||||
|
||||
|
||||
def commits_since(tag: str | None, branch: str, cwd: str | None = None) -> 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)
|
||||
@@ -105,10 +123,15 @@ def file_at(revision: str, path: str, cwd: str | None = None) -> str | Failure:
|
||||
"""A file's text at a revision, read in cwd, else in the current directory; empty where the revision is not a commit, such as a root commit's parent, or holds no such file."""
|
||||
if not commit_exists(revision, cwd):
|
||||
return ""
|
||||
listed = git("ls-tree", "--name-only", revision, "--", path, cwd=cwd)
|
||||
return text_at(revision, path, functools.partial(git, cwd=cwd))
|
||||
|
||||
|
||||
def text_at(revision: str, path: str, run: Run) -> str | Failure:
|
||||
"""A file's text at a commit, as run reads it; empty where the commit holds no such file. ls-tree reads path from the directory run runs in, and show from the checkout's top."""
|
||||
listed = run("ls-tree", "--name-only", revision, "--", path)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
return git("show", f"{revision}:{path}", cwd=cwd) if listed.strip() else ""
|
||||
return run("show", f"{revision}:{path}") if listed.strip() else ""
|
||||
|
||||
|
||||
def full_history() -> Failure | None:
|
||||
@@ -5,10 +5,10 @@ import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
import git_repo
|
||||
from git_cli import git_repo
|
||||
|
||||
|
||||
class Git(unittest.TestCase):
|
||||
@@ -26,6 +26,9 @@ class Git(unittest.TestCase):
|
||||
self.assertIn("latin", done.reason)
|
||||
self.assertIn("UTF-8", done.reason)
|
||||
|
||||
def test_reads_each_byte_that_is_not_utf_8_as_a_replacement_character_where_asked(self):
|
||||
self.assertEqual(git_repo.git("-c", "alias.latin=!printf 'caf\\351'", "latin", errors="replace"), "caf�")
|
||||
|
||||
def test_says_which_command_could_not_start_in_a_directory_that_is_gone(self):
|
||||
done = git_repo.git("log", cwd="/code/gone")
|
||||
self.assertIsInstance(done, Failure)
|
||||
@@ -87,6 +90,11 @@ class StalledOrigin(unittest.TestCase):
|
||||
self.assertIsInstance(ref, Failure)
|
||||
self.assertIn("stopped after 0.5 s", ref.reason)
|
||||
|
||||
def test_reading_the_default_branch_guarded_asks_no_one_and_fails(self):
|
||||
ref = git_repo.default_ref(self.root, 0.5, guarded=True)
|
||||
self.assertIsInstance(ref, Failure)
|
||||
self.assertIn("origin records no default branch", ref.reason)
|
||||
|
||||
def test_fetching_the_default_branch_fails_after_the_timeout(self):
|
||||
with contextlib.chdir(self.root):
|
||||
found = git_repo.default_branch(stale_ok=True, timeout=0.5)
|
||||
@@ -94,5 +102,35 @@ class StalledOrigin(unittest.TestCase):
|
||||
self.assertIn("stopped after 0.5 s", found.reason)
|
||||
|
||||
|
||||
class TextAt(unittest.TestCase):
|
||||
def test_reads_the_file_the_revision_lists(self):
|
||||
answers = {"ls-tree": "todo.md\n", "show": "# todo\n"}
|
||||
self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: answers[args[0]]), "# todo\n")
|
||||
|
||||
def test_reads_empty_where_the_revision_lists_no_such_file(self):
|
||||
self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: "" if args[0] == "ls-tree" else Failure("no such file")), "")
|
||||
|
||||
def test_fails_where_git_cannot_list_the_revision(self):
|
||||
self.assertEqual(git_repo.text_at("r", "todo.md", lambda *args: Failure("bad revision")), Failure("bad revision"))
|
||||
|
||||
|
||||
class FileAt(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = temp.name
|
||||
self.run_git("init", "--quiet")
|
||||
pathlib.Path(self.root, "todo.md").write_text("# todo\n")
|
||||
self.run_git("add", "todo.md")
|
||||
self.run_git("-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgSign=false", "commit", "--quiet", "-m", "Start")
|
||||
|
||||
def run_git(self, *args):
|
||||
subprocess.run(["git", *args], capture_output=True, check=True, cwd=self.root)
|
||||
|
||||
def test_reads_the_file_in_the_checkout_cwd_names_while_running_in_another_directory(self):
|
||||
with tempfile.TemporaryDirectory() as elsewhere, contextlib.chdir(elsewhere):
|
||||
self.assertEqual(git_repo.file_at("HEAD", "todo.md", self.root), "# todo\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+13
-14
@@ -30,7 +30,7 @@ from transcript_archive.location import archive_root, transcript_of
|
||||
from transcript_archive.read import archived_outcomes
|
||||
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
|
||||
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
|
||||
from project_key import checkout_of
|
||||
from transcript_archive.project_key import checkout_of
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
@@ -40,7 +40,6 @@ from model_routing.ladder import lowest_worker_rung, project_rung, Rung
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.verdicts import Verdict
|
||||
|
||||
TOOL = "judge-replay"
|
||||
@@ -51,21 +50,21 @@ REFERENCE_EFFORT = "xhigh"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
anchor = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
cases = archived_cases(anchor.model, archive_root(home, env), home)
|
||||
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
if isinstance(project, int):
|
||||
return project
|
||||
cases = archived_cases(project.model, archive_root(home, env), home)
|
||||
if isinstance(cases, Failure):
|
||||
return failed(TOOL, cases.reason)
|
||||
if not cases:
|
||||
return failed(TOOL, f"no archived verdicts of projects on {anchor.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
return failed(TOOL, f"no archived verdicts of projects on {project.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
cases = sample(cases, PER_KIND)
|
||||
reference = Rung(anchor.model, REFERENCE_EFFORT)
|
||||
reference = Rung(project.model, REFERENCE_EFFORT)
|
||||
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
|
||||
replay = replayed(cases, reference, down_from(anchor, lowest_worker_rung(anchor)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
replay = replayed(cases, reference, down_from(project, lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(anchor.model, reference, cases, replay))
|
||||
print(report(project.model, reference, cases, replay))
|
||||
return 0
|
||||
|
||||
|
||||
@@ -93,10 +92,10 @@ def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[C
|
||||
|
||||
def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> Kind | Limited:
|
||||
premises, records, entries = read_premises(case.root), read_records(case.root, claude_dir), read_transcript(str(case.transcript))
|
||||
if isinstance(premises, Stop):
|
||||
return verdict_kind(Failure(premises.reason))
|
||||
if isinstance(records, Stop):
|
||||
return verdict_kind(Failure(records.reason))
|
||||
if isinstance(premises, Failure):
|
||||
return verdict_kind(premises)
|
||||
if isinstance(records, Failure):
|
||||
return verdict_kind(records)
|
||||
if isinstance(entries, Failure):
|
||||
return verdict_kind(entries)
|
||||
# 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count.
|
||||
|
||||
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
@@ -122,7 +122,7 @@ class Main(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def verdict(interrupt, evidence):
|
||||
output = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
|
||||
output = {"items_taken_in": [], "answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
|
||||
return {"type": "result", "structured_output": output}
|
||||
|
||||
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
@@ -175,9 +175,9 @@ class Main(unittest.TestCase):
|
||||
self.assertIn("usage limit: You've hit your limit", err)
|
||||
for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["claude-haiku-5-5"], unused)
|
||||
code, _, err = self.run_main(["claude-fable-5-1"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived verdicts of projects on claude-haiku-5-5", err)
|
||||
self.assertIn("no archived verdicts of projects on claude-fable-5-1", err)
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text("[")
|
||||
self.assertEqual(self.run_main(["claude-opus-5-5"], unused)[0], 1)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import counted_vote, entries, Entry, overall_cells, scoring_runs
|
||||
from review_rules.comprehension_history import by_time, counted_vote, entries, Entry, last_cells
|
||||
from larv_review.seats import FIRST_SEATS
|
||||
|
||||
# Matches score-outcomes, which waits for 10 finished chunks before it shows a median.
|
||||
@@ -10,7 +10,7 @@ MIN_PAIRS = 10
|
||||
def ruling_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each paired ruling that holds both of the first seats' overall votes, whether they counted alike."""
|
||||
first, second = FIRST_SEATS
|
||||
cells = [overall_cells(entry) for entry in found if entry.paired]
|
||||
cells = [last_cells(entry.vote_rows) for entry in found if entry.paired]
|
||||
return [counted_vote(each[first]) == counted_vote(each[second]) for each in cells if first in each and second in each]
|
||||
|
||||
|
||||
@@ -18,9 +18,9 @@ def run_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each commit scored at least twice, whether the first two seats' overall scores moved the same way, up, down or not at all, from its first run to its second. Both runs read one tree, so the pair is the ruling those seats would make from absolute scores on code that did not change."""
|
||||
first, second = FIRST_SEATS
|
||||
runs: dict[str, list[dict[str, decimal.Decimal]]] = {}
|
||||
for entry in scoring_runs(found):
|
||||
cells = overall_cells(entry)
|
||||
if first in cells and second in cells:
|
||||
for entry in by_time(found):
|
||||
cells = last_cells(entry.score_rows)
|
||||
if entry.scored and first in cells and second in cells:
|
||||
runs.setdefault(entry.commit, []).append({first: decimal.Decimal(cells[first]), second: decimal.Decimal(cells[second])})
|
||||
pairs = [(each[0], each[1]) for each in runs.values() if len(each) >= 2]
|
||||
return [direction(before[first], after[first]) == direction(before[second], after[second]) for before, after in pairs]
|
||||
|
||||
@@ -1,30 +1,34 @@
|
||||
from failure import Failure
|
||||
from git_repo import file_at, full_history, git
|
||||
from comprehension_history import HISTORY, HistoryChange
|
||||
from git_cli.git_repo import file_at, full_history, git, top
|
||||
from review_rules.comprehension_history import HISTORY, HistoryChange
|
||||
|
||||
|
||||
def history_changes(default: str) -> list[HistoryChange] | Failure:
|
||||
"""Each merged change on the default branch that touched the history, newest first."""
|
||||
if partial := full_history():
|
||||
return partial
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY)
|
||||
# HISTORY names the file from the checkout's top, and git reads a path from the directory it runs in.
|
||||
root = top()
|
||||
if isinstance(root, Failure):
|
||||
return root
|
||||
commits = git("log", "--first-parent", "--format=%H", default, "--", HISTORY, cwd=root)
|
||||
if isinstance(commits, Failure):
|
||||
return commits
|
||||
changes = []
|
||||
for commit in commits.split():
|
||||
change = history_change(commit)
|
||||
change = history_change(commit, root)
|
||||
if isinstance(change, Failure):
|
||||
return change
|
||||
changes.append(change)
|
||||
return changes
|
||||
|
||||
|
||||
def history_change(commit: str) -> HistoryChange | Failure:
|
||||
"""The history before and after commit. A merge commit counts as one change, against its first parent."""
|
||||
before = file_at(f"{commit}^1", HISTORY)
|
||||
def history_change(commit: str, root: str) -> HistoryChange | Failure:
|
||||
"""The history before and after commit, read in the checkout at root. A merge commit counts as one change, against its first parent."""
|
||||
before = file_at(f"{commit}^1", HISTORY, root)
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
after = file_at(commit, HISTORY)
|
||||
after = file_at(commit, HISTORY, root)
|
||||
if isinstance(after, Failure):
|
||||
return after
|
||||
return HistoryChange(commit, before, after)
|
||||
|
||||
@@ -2,15 +2,15 @@ import pathlib
|
||||
import time
|
||||
|
||||
from larv_review.agreement import agreement_report
|
||||
from comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from git_repo import commit_exists, top
|
||||
from review_rules.comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from git_cli.git_repo import commit_exists, top
|
||||
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 means, under_floor
|
||||
from larv_review.plan import plan_reasons
|
||||
import rank_todo
|
||||
from file_writes import replace_file
|
||||
from release_plan import ranking
|
||||
from records.file_writes import replace_file
|
||||
|
||||
|
||||
def record_ruling(votes_file: pathlib.Path) -> Failure | None:
|
||||
@@ -61,7 +61,7 @@ def rerank() -> Failure | None:
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
todo = pathlib.Path(checkout, "todo.md")
|
||||
ranked = rank_todo.rank_file(todo)
|
||||
ranked = ranking.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:
|
||||
|
||||
+18
-16
@@ -22,10 +22,12 @@ measured commit is the default branch's newest merged change that adds a paired
|
||||
run to the history; a merge commit counts as one change against its first parent. With none, it is
|
||||
the merge base of HEAD and the default branch.
|
||||
|
||||
round-count prints each pass's round count among the commits not yet on the default branch whose
|
||||
titles open `Answer <pass> round <n>:`, ignoring case. The count is the highest <n>, or the number of
|
||||
such commits when that is more. At or past the cap of {cap} rounds, it says to ask the human before
|
||||
another round. It also lists each name in such a title that is not a pass.
|
||||
round-count prints each pass's round count among the branch's commits since the default branch
|
||||
whose titles open `Answer <pass> round <n>:`, ignoring case. It follows first parents, as
|
||||
rule-hook's round-cap does. The count is the highest <n>, or the number of such commits when that
|
||||
is more. At or past the cap of {cap} rounds, {release_cap} for architecture and principles, which run
|
||||
only in the release review, it says the pass takes no more rounds. It also lists
|
||||
each name in such a title that is not a pass.
|
||||
|
||||
needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when it ships none, and
|
||||
prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships
|
||||
@@ -101,24 +103,24 @@ import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from round_titles import CAP, round_counts
|
||||
from git_repo import default_branch, git, top
|
||||
from git_cli.git_repo import branch_titles, default_branch, git, top
|
||||
from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts
|
||||
from failure import Failure
|
||||
from comprehension_history import FLOOR
|
||||
from review_rules.comprehension_history import FLOOR
|
||||
from larv_review.history_changes import history_changes
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.agreement import MIN_PAIRS
|
||||
from review_passes import PASSES
|
||||
from review_rules.review_passes import PASSES
|
||||
from larv_review.plan import plan_reasons
|
||||
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
|
||||
from review_folder import REPORTS, review_folder
|
||||
from review_rules.review_folder import REPORTS, review_folder
|
||||
|
||||
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"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(cap=CAP, floor=FLOOR, pairs=MIN_PAIRS))
|
||||
print(__doc__.strip().format(cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS))
|
||||
return 0
|
||||
command, *given = argv or [""]
|
||||
if command == "review-folder" and not given:
|
||||
@@ -194,18 +196,18 @@ def show_ruling_base(default: str) -> Failure | None:
|
||||
|
||||
|
||||
def round_count(default: str) -> Failure | None:
|
||||
titles = git("log", "--format=%s", f"{default}..HEAD")
|
||||
titles = branch_titles(default)
|
||||
if isinstance(titles, Failure):
|
||||
return titles
|
||||
for name, count in round_counts(titles.splitlines()).items():
|
||||
print(f"{name}: {count}{cap_note(count) if name in PASSES else ', not a pass: check the commit title'}")
|
||||
for name, count in round_counts(titles).items():
|
||||
print(f"{name}: {count}{cap_note(count, cap(name)) if name in PASSES else ', not a pass: check the commit title'}")
|
||||
return None
|
||||
|
||||
|
||||
def cap_note(count: int) -> str:
|
||||
if count < CAP:
|
||||
def cap_note(count: int, most: int) -> str:
|
||||
if count < most:
|
||||
return ""
|
||||
return f", {'at' if count == CAP else 'past'} the cap: ask the human before another round"
|
||||
return f", {'at' if count == most else 'past'} the cap: no more rounds"
|
||||
|
||||
|
||||
def needs_scoring_run(default: str, ids: list[int]) -> Failure | None:
|
||||
|
||||
+22
-19
@@ -1,17 +1,18 @@
|
||||
import pathlib
|
||||
|
||||
from chunk_pick import Cut, default_plan, LastCut, next_release, Unknown
|
||||
from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown
|
||||
from failure import Failure
|
||||
from todo_table import Item, items, NoItemsTable, renames, version
|
||||
from git_repo import top
|
||||
from release_plan.todo_table import Item, items, NoItemsTable, renames
|
||||
from release_plan.release import Release, version
|
||||
from git_cli.git_repo import top
|
||||
|
||||
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: tuple[int, int, int] | None, renamed: set[tuple[int, int, int]]) -> list[str] | Failure:
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release]) -> 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.
|
||||
|
||||
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed 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.
|
||||
"""
|
||||
plan = {item.id: item for item in before + after}
|
||||
if unknown := sorted(set(ships) - set(plan)):
|
||||
@@ -19,32 +20,34 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan
|
||||
shipped = [plan[id_] for id_ in ships]
|
||||
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
|
||||
for release in emptied(before, after, shipped, renamed):
|
||||
if work_landed(release, shipped, landed):
|
||||
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")
|
||||
return reasons
|
||||
|
||||
|
||||
# larv-review --help points here rather than restating the rule, so the rule is written once.
|
||||
def work_landed(release: tuple[int, int, int], shipped: list[Item], landed: tuple[int, int, int] | None) -> bool:
|
||||
"""Whether work has landed towards release, for the scoring-run trigger. It has when the chunk ships one of the release's items. It has too when release equals landed: the default branch's next release, once work has landed towards it."""
|
||||
return any(item.release == release for item in shipped) or release == landed
|
||||
def work_landed(release: Release, shipped: list[Item], landed_release: Release | None) -> bool:
|
||||
"""Whether work has landed towards release, for the scoring-run trigger. It has when the chunk ships one of the release's items. It has too when release equals landed_release: the default branch's next release, once work has landed towards it."""
|
||||
return any(item.release == release for item in shipped) or release == landed_release
|
||||
|
||||
|
||||
def landed_towards(found: list[Item], cut: LastCut) -> tuple[int, int, int] | None | Failure:
|
||||
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `chunk_pick.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
|
||||
def landed_towards(found: list[Item], cut: LastCut) -> Release | None | Failure:
|
||||
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `release_standing.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
|
||||
if isinstance(cut.tag, Failure):
|
||||
return Failure(f"could not tell the next release: the default branch's tags cannot be read: {cut.tag.reason}")
|
||||
upcoming = next_release(found, cut)
|
||||
if isinstance(upcoming, Unknown):
|
||||
return Failure("could not tell the next release: the default branch's todo.md history cannot be read")
|
||||
# Cut's release is the last cut's version or earlier, so no work lands towards it.
|
||||
if isinstance(upcoming, Cut):
|
||||
return None
|
||||
if isinstance(upcoming.landed, Failure):
|
||||
return Failure(f"could not tell whether work landed towards the next release: {upcoming.landed.reason}")
|
||||
return upcoming.release if upcoming.landed else None
|
||||
if isinstance(upcoming.unreleased, Failure):
|
||||
return Failure(f"could not tell whether work landed towards the next release: {upcoming.unreleased.reason}")
|
||||
return upcoming.release if upcoming.unreleased else None
|
||||
|
||||
|
||||
def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed: set[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
|
||||
def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed: set[Release]) -> list[Release]:
|
||||
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer, unless the chunk's plan marks it renamed."""
|
||||
named = {item.release for item in before + shipped}
|
||||
kept = [item for item in after if item.id not in {ship.id for ship in shipped}]
|
||||
@@ -78,7 +81,7 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
renamed = renames(after)
|
||||
if isinstance(renamed, Failure):
|
||||
return Failure(f"the checkout's todo.md: {renamed.reason}")
|
||||
landed = landed_towards(planned, held.cut)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
return scoring_run_due(planned, chunk, ids, landed, renamed)
|
||||
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)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from comprehension_history import DIMENSIONS, PLACE, place_dimensions, Seat
|
||||
from review_rules.comprehension_history import DIMENSIONS, PLACE, place_dimensions, Seat
|
||||
from failure import Failure
|
||||
from larv_review.seats import FIRST_SEATS, SPLIT_SEATS, vote_line
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from comprehension_history import entries, HistoryChange
|
||||
from review_rules.comprehension_history import entries, HistoryChange
|
||||
|
||||
|
||||
def measured_commit(changes: list[HistoryChange]) -> str | None:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import DIMENSIONS, FLOOR
|
||||
from review_rules.comprehension_history import DIMENSIONS, FLOOR
|
||||
|
||||
|
||||
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
|
||||
|
||||
@@ -2,7 +2,7 @@ import dataclasses
|
||||
import decimal
|
||||
import re
|
||||
|
||||
from comprehension_history import ARCHITECT, DIMENSIONS, JUNIOR, MID, Seat, SENIOR
|
||||
from review_rules.comprehension_history import ARCHITECT, DIMENSIONS, JUNIOR, MID, Seat, SENIOR
|
||||
from failure import Failure
|
||||
|
||||
SCORES = re.compile(", ".join(rf"{name} ([0-9]+(?:\.[0-9]+)?)" for name in DIMENSIONS))
|
||||
|
||||
@@ -11,14 +11,14 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
|
||||
from comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
|
||||
import comprehension_history
|
||||
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
|
||||
from review_rules import comprehension_history
|
||||
from larv_review.ruling import counted, ruling, split, surplus, votes
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from todo_table import Item, items, NoItemsTable
|
||||
from release_plan.todo_table import Item, items, NoItemsTable
|
||||
from larv_review.plan import landed_towards, plan_reasons, scoring_run_due
|
||||
from chunk_pick import LastCut
|
||||
from release_plan.release_standing import LastCut
|
||||
from larv_review.scoring import means, under_floor
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.seats import score_line, scores, seats_file
|
||||
@@ -162,6 +162,30 @@ class History(unittest.TestCase):
|
||||
fell = ruled.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 6 | 7 | 7 | 7 |\n| Mean | 7 | 6 | 7 | 7 | 7 |\n\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n"
|
||||
self.assertEqual(latest_places(appended(appended("", scored), fell)), hard_since.replace("2026-10-10T12:00:00Z", "2026-10-09T12:00:00Z") + "\nJunior A, hardest first:\n\n- `bin/j.py:5` `s`: wide\n")
|
||||
|
||||
def test_takes_a_seats_vote_from_the_votes_table_when_it_comes_first(self):
|
||||
self.assert_votes_table_read(lambda votes, scores: votes + scores)
|
||||
|
||||
def test_takes_a_seats_vote_from_the_votes_table_when_it_comes_second(self):
|
||||
self.assert_votes_table_read(lambda votes, scores: scores + votes)
|
||||
|
||||
def assert_votes_table_read(self, tables):
|
||||
votes = "| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | same | same | same |\n"
|
||||
scores = "| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | 7 | 7 | 7 | 7 | 7 |\n| Mean | 7 | 7 | 7 | 7 | 7 |\n"
|
||||
places = "Mid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: kept\n- Shape: `bin/f.py:2` `o`: dropped\n"
|
||||
kept = "## 2026-10-07T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: kept\n"
|
||||
self.assertEqual(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + tables(votes, scores) + places)), kept)
|
||||
|
||||
def test_keeps_every_bullet_of_a_listing_that_opens_with_a_dimension_voted_worse(self):
|
||||
votes = "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | worse | same | same |\n"
|
||||
places = "\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: deep\n- Shape: `bin/f.py:2` `o`: wide\n"
|
||||
expected = "## 2026-10-07T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nMid A, decided by:\n\n- Locality: `bin/e.py:1` `n`: deep\n- Shape: `bin/f.py:2` `o`: wide\n"
|
||||
self.assertEqual(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + votes + places)), expected)
|
||||
|
||||
def test_drops_the_bullets_of_a_seat_with_no_row_in_the_votes_table(self):
|
||||
votes = "\n| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |\n|---|---|---|---|---|---|\n| Mid A | same | worse | same | same | same |\n"
|
||||
places = "\nJunior A, decided by:\n\n- Locality: `bin/e.py:1` `n`: deep\n"
|
||||
self.assertIsNone(latest_places(appended("", paired("2026-10-07T12:00:00Z", "worse") + votes + places)))
|
||||
|
||||
def test_names_the_places_of_every_run_on_the_newest_scored_commit(self):
|
||||
run = "## {time}, {pr} at {commit}\n\nJunior A, hardest first:\n\n- `bin/b.py:{line}` `h`: long\n"
|
||||
first, rerun, other = (run.format(time=time, pr=pr, commit=commit, line=line) for time, pr, commit, line in (("2026-10-08T12:00:00Z", "PR #1", "aaaaaaa", 1), ("2026-10-08T13:00:00Z", "PR #1 rerun", "aaaaaaa", 2), ("2026-10-09T12:00:00Z", "PR #2", "bbbbbbb", 3)))
|
||||
@@ -337,6 +361,7 @@ class LandedTowards(unittest.TestCase):
|
||||
plan = [item(1, (0, 2, 0))]
|
||||
self.assertIsInstance(landed_towards(plan, LastCut("v0.1.0", Failure("unreadable"), Failure("count unreadable"), [])), Failure)
|
||||
self.assertIsInstance(landed_towards([], LastCut("v0.1.0", "", 3, Failure("log unreadable"))), Failure)
|
||||
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 LarvReviewTool(unittest.TestCase):
|
||||
@@ -364,15 +389,15 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.git("add", name)
|
||||
self.git("commit", "-q", "--allow-empty", "-m", title)
|
||||
|
||||
def run_tool(self, *args):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
|
||||
def run_tool(self, *args, cwd=None):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.checkout, env=self.env, text=True)
|
||||
|
||||
def seats_file(self, text, name="seats.md"):
|
||||
path = self.checkout.parent / name
|
||||
path.write_text(textwrap.dedent(text))
|
||||
return str(path)
|
||||
|
||||
def test_takes_the_merge_base_until_a_merged_change_records_an_entry(self):
|
||||
def test_takes_the_merge_base_until_a_merged_change_records_an_entry_and_finds_it_from_a_subfolder(self):
|
||||
start = self.git("rev-parse", "HEAD").strip()
|
||||
self.commit("work")
|
||||
ran = self.run_tool("ruling-base")
|
||||
@@ -381,21 +406,32 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.commit("Merge a scoring run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
measured = self.git("rev-parse", "HEAD").strip()
|
||||
self.commit("Fix a typo", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING + "\nA note.\n"})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.git("switch", "-q", "chunk")
|
||||
self.assertEqual(self.run_tool("ruling-base").stdout.splitlines()[0], measured)
|
||||
(self.checkout / "docs").mkdir(exist_ok=True)
|
||||
self.assertEqual(self.run_tool("ruling-base", cwd=self.checkout / "docs").stdout.splitlines()[0], measured)
|
||||
|
||||
def test_counts_rounds_on_this_branch_alone(self):
|
||||
self.commit("Answer stability round 1: a")
|
||||
self.commit("Answer stability round 2: b")
|
||||
self.commit("Answer prose round 1: c")
|
||||
self.commit("Answer stability round 3: d")
|
||||
ran = self.run_tool("round-count")
|
||||
self.assertIn("stability: 3, at the cap: ask the human before another round\n", ran.stdout)
|
||||
self.commit("Answer stability round 4: e")
|
||||
self.assertIn("stability: 4, past the cap: ask the human before another round\n", self.run_tool("round-count").stdout)
|
||||
self.assertIn("stability: 2, at the cap: no more rounds\n", ran.stdout)
|
||||
self.commit("Answer stability round 3: d")
|
||||
self.assertIn("stability: 3, past the cap: no more rounds\n", self.run_tool("round-count").stdout)
|
||||
self.assertIn("prose: 1\n", ran.stdout)
|
||||
self.assertIn("architecture: 0\n", ran.stdout)
|
||||
|
||||
def test_leaves_out_the_round_commits_of_a_branch_merged_in_as_the_hook_does(self):
|
||||
self.git("switch", "-q", "-c", "sibling")
|
||||
self.commit("Answer stability round 1: a")
|
||||
self.commit("Answer stability round 2: b")
|
||||
self.git("switch", "-q", "chunk")
|
||||
self.git("merge", "-q", "--no-ff", "-m", "Merge sibling", "sibling")
|
||||
self.assertIn("stability: 0\n", self.run_tool("round-count").stdout)
|
||||
|
||||
def test_says_whether_a_scoring_run_is_due_and_refuses_an_unknown_item(self):
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "1").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
@@ -583,7 +619,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
def test_states_its_rules_and_finds_origins_default_branch_where_the_clone_recorded_none(self):
|
||||
helped = self.run_tool("--help")
|
||||
self.assertEqual(helped.returncode, 0, helped.stderr)
|
||||
self.assertIn("cap of 3 rounds", helped.stdout)
|
||||
self.assertIn("cap of 2 rounds", helped.stdout)
|
||||
self.git("remote", "set-head", "origin", "--delete")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_inbox import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], pathlib.Path.home()))
|
||||
@@ -0,0 +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.
|
||||
"""
|
||||
|
||||
@@ -1,65 +1,108 @@
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
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 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_claude.stop import needs_human, needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens."""
|
||||
class WorkerSession:
|
||||
"""The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox."""
|
||||
root: str
|
||||
id: uuid.UUID
|
||||
rung: Rung
|
||||
transcript_path: str
|
||||
# Added to the environment of the worker's claude, and of the claude /talk opens.
|
||||
env: dict[str, str]
|
||||
|
||||
def claude_command(self) -> ClaudeCommand:
|
||||
return ClaudeCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
|
||||
with listed(questions, ask, effects):
|
||||
answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal()
|
||||
if isinstance(answer, OpenOnTerminal | OpenInInbox):
|
||||
return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, questions, effects)) or Talked()
|
||||
return answer
|
||||
|
||||
|
||||
def first_answer(ask: Ask, questions: pathlib.Path, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop:
|
||||
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type nothing, or the input ends."""
|
||||
try:
|
||||
answer = effects.input(ASK_ANSWER).strip()
|
||||
# Annotated since mypy infers input_or's T as object from the lambda.
|
||||
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(questions, ask))
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
|
||||
return needs_human(ANSWER_QUESTION, "the input ended")
|
||||
if not answer:
|
||||
match answer:
|
||||
case ClaudeOpening(pid):
|
||||
return OpenInInbox(pid)
|
||||
case Typed(text):
|
||||
say(f"Answered in loop-inbox: {text}", effects)
|
||||
case str(text):
|
||||
pass
|
||||
case _:
|
||||
typing.assert_never(answer)
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return needs_human(ANSWER_QUESTION, "nothing was typed")
|
||||
return Talk() if answer == TALK else answer
|
||||
return OpenOnTerminal() if text == TALK else text
|
||||
|
||||
|
||||
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
|
||||
entries = read_transcript(path)
|
||||
def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> Stop | None:
|
||||
"""Lists ask in loop-inbox as having claude open where, then returns once that claude has ended: the one it opens on the terminal, or the one loop-inbox opened."""
|
||||
match where:
|
||||
case OpenOnTerminal():
|
||||
shown(questions, dataclasses.replace(ask, state=where), effects)
|
||||
if unstarted := hand_over(session.claude_command(), effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
case OpenInInbox(pid):
|
||||
make_way(questions, ask, pid, effects)
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not claude_ended(questions, ask) and effects.alive(pid):
|
||||
effects.sleep(POLL_SECONDS)
|
||||
case _:
|
||||
typing.assert_never(where)
|
||||
return None
|
||||
|
||||
|
||||
def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None]) -> Stop | None:
|
||||
"""Runs held_open, which returns once the claude the human answers in has ended, then checks that the human typed something there."""
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
before = human_turns(entries)
|
||||
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
entries = read_transcript(path)
|
||||
if stop := held_open():
|
||||
return stop
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects))
|
||||
try:
|
||||
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
@@ -8,8 +8,8 @@ from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from todo_table import LEVELS
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished, Verdict
|
||||
from release_plan.todo_table import LEVELS
|
||||
from model_routing.route import on_its_scale
|
||||
from claude_code.transcript import plain, verbatim
|
||||
from loop_claude.cycle.retry import retried
|
||||
@@ -20,20 +20,22 @@ from claude_code.entries import structured_output
|
||||
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
|
||||
JUDGE_PROMPT_CHARS = 400000
|
||||
INTERRUPT_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
||||
"- the worker asks the human anything, seeks approval, or says a decision is the human's, and neither "
|
||||
"README.md nor the records settle the matter\n"
|
||||
"""Decide whether the human must now be interrupted. ~/.claude/CLAUDE.md → "Working loop", "Ask, don't guess" says """
|
||||
"which choices are reserved for the human. interrupt=true when any of these appear:\n"
|
||||
"- the worker asks the human about a reserved choice, or makes one itself, and neither README.md nor the "
|
||||
"records settle it; a choice the worker names a rule as asking the human's approval for counts as reserved, "
|
||||
"since some such rules, such as larv-review's, lie outside the records\n"
|
||||
"- it asks the human anything else without recommending an answer, and neither README.md "
|
||||
"nor the records settle the matter\n"
|
||||
"- it asks again a question a [loop] line already answered\n"
|
||||
"- it carried on under an assumption that decides the deliverable, that the human could "
|
||||
"reasonably reject and that neither README.md nor the records settle; a caveat about "
|
||||
"transient state it then handled is not one\n"
|
||||
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
|
||||
"outside the repo, or a release ready to cut, which only the human may publish\n"
|
||||
"- it flags that the goals, the plan in todo.md or the task itself is unclear, missing or in need of change\n"
|
||||
"- it chose between alternatives that neither README.md nor the records discriminate "
|
||||
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n\n"
|
||||
"interrupt=false otherwise. Bookkeeping the worker settled silently - what to document, wording, "
|
||||
"where a note goes - is not on its own a reason to interrupt. A run that ends asking loop-claude for a higher "
|
||||
"- it flags that the goals need changing\n"
|
||||
"- it flags that the plan in todo.md or the task itself is unclear or missing, and recommends no way on\n\n"
|
||||
"interrupt=false otherwise. A choice in the repo that no rule reserves for the human is the worker's to make, "
|
||||
"so its taking its own recommendation on one is no reason to interrupt. Where it asks about such a choice and "
|
||||
"recommends an answer, quote the sentence of that rule telling it to take the option it would recommend, even "
|
||||
"where a [loop] line quoted that sentence for another question. A run that ends asking loop-claude for a higher "
|
||||
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is.\n\n"
|
||||
"The human may have replied inside the transcript, on a [human] line: judge only what "
|
||||
"is still open, never a question they already answered there.\n\n"
|
||||
@@ -67,21 +69,23 @@ class Reply:
|
||||
highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
|
||||
highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Lists the chunk's items in loop-inbox: running_loops.py.
|
||||
items_taken_in: list[int] = dataclasses.field(metadata={"description": "The IDs of the todo.md items the worker states this chunk takes, the item the chunk was routed on included, never an item it only filed in todo.md for later; empty when it states none."})
|
||||
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: loop_claude/escalation_mark.py.
|
||||
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. " + escalation_mark.QUOTE_AFTER_STEP + " Never a later mention of the trigger, and never the request itself."})
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
|
||||
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
|
||||
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
|
||||
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (chunk_pick.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
|
||||
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
|
||||
|
||||
|
||||
REPLY_TYPES = typing.get_type_hints(Reply)
|
||||
JSON_TYPES = {bool: "boolean", int: "integer", str: "string"}
|
||||
JSON_TYPES: dict[object, dict[str, typing.Any]] = {bool: {"type": "boolean"}, int: {"type": "integer"}, str: {"type": "string"}, list[int]: {"type": "array", "items": {"type": "integer"}}}
|
||||
HIGHEST_L = LEVELS["L"]
|
||||
JUDGE_SCHEMA = {
|
||||
"properties": {field.name: {**field.metadata, "type": JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
||||
"properties": {field.name: {**field.metadata, **JSON_TYPES[REPLY_TYPES[field.name]]} for field in dataclasses.fields(Reply)},
|
||||
"required": list(REPLY_TYPES),
|
||||
"type": "object",
|
||||
}
|
||||
@@ -89,17 +93,18 @@ JUDGE_SCHEMA = {
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Rejected(Failure):
|
||||
"""A judge reply loop-claude rejected: reason says why, reply holds the reply as json."""
|
||||
"""A judge reply loop-claude rejected: reason says why, reply holds the reply as json, and cost is what the run cost in dollars, 0 where its reply records none."""
|
||||
reply: str
|
||||
cost: float = 0.0
|
||||
|
||||
|
||||
class Grounds(typing.NamedTuple):
|
||||
"""What run_judge checks the judge's quotes against, word for word, since stitched fragments can say what their source does not."""
|
||||
# The transcript as the judge saw it. The evidence must quote it, its fragments in order: a misquote is Rejected, which judge retries.
|
||||
"""The texts quotes_checked checks the judge's quotes against. A quote must appear in its text as written, since a quote reworded or stitched together can say what its source does not; only the evidence may join passages with an ellipsis, each passage in order."""
|
||||
# The transcript as the judge saw it.
|
||||
shown: str
|
||||
# escalation_mark.since_step's lines. An escalation must quote both these and shown: a misquote drops the escalation, as escalation_mark.checked says.
|
||||
# The worker's own lines after the escalation mark, as escalation_mark.since_step renders them.
|
||||
since_step: str
|
||||
# README.md's premises and the records. A quoted answer must quote them: a misquote puts the question to the human.
|
||||
# README.md's premises and the records.
|
||||
quotable: str
|
||||
|
||||
|
||||
@@ -107,23 +112,42 @@ def verdict_from(output: object) -> Verdict | Failure:
|
||||
if not isinstance(output, dict):
|
||||
return Failure("the judge returned no reply")
|
||||
for name, kind in REPLY_TYPES.items():
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
if type(output.get(name)) is not kind:
|
||||
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
||||
# An L taken in off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
||||
likelihood = output["highest_likelihood_taken_in"] if 0 <= output["highest_likelihood_taken_in"] <= HIGHEST_L else 0
|
||||
if not fits(output.get(name), kind):
|
||||
return Failure(f"the judge's reply has no {name} of type {type_name(JSON_TYPES[kind])}")
|
||||
taken_in = taken_in_from(output)
|
||||
if output["interrupt"]:
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, release_ready=output["release_ready"])
|
||||
return Interrupt(output["evidence"], output["question"], escalation=output["escalation"], taken_in=taken_in, release_ready=output["release_ready"])
|
||||
if output["answer"].strip():
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge quoted an answer without a question")
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood)
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"], escalation=output["escalation"], taken_in=taken_in)
|
||||
if output["finished"]:
|
||||
return Finished(output["evidence"])
|
||||
escape_and_impact = output["highest_escape_and_impact_taken_in"] if on_its_scale(output["highest_escape_and_impact_taken_in"]) else 0
|
||||
return Unfinished(output["evidence"], escalation=output["escalation"], highest_likelihood_taken_in=likelihood, highest_escape_and_impact_taken_in=escape_and_impact)
|
||||
return Unfinished(output["evidence"], escalation=output["escalation"], taken_in=taken_in)
|
||||
|
||||
|
||||
def type_name(schema: dict[str, typing.Any]) -> str:
|
||||
return f"array of {schema['items']['type']}s" if schema["type"] == "array" else schema["type"]
|
||||
|
||||
|
||||
def fits(value: object, kind: object) -> bool:
|
||||
"""Whether value, read from the judge's JSON, is of kind. type(), not isinstance(): JSON true is no integer."""
|
||||
if typing.get_origin(kind) is list:
|
||||
return type(value) is list and all(fits(each, typing.get_args(kind)[0]) for each in value)
|
||||
return type(value) is kind
|
||||
|
||||
|
||||
def taken_in_from(output: dict) -> TakenIn:
|
||||
"""The reply's readings of the items taken in. An ID below 1 is left out, and an L or E + I off its scale counts as 0. Neither fails the reply: three failures would stop an unattended loop, and holding the rung is safe."""
|
||||
likelihood = output["highest_likelihood_taken_in"]
|
||||
escape_and_impact = output["highest_escape_and_impact_taken_in"]
|
||||
return TakenIn(
|
||||
tuple(item for item in output["items_taken_in"] if item > 0),
|
||||
likelihood if 0 <= likelihood <= HIGHEST_L else 0,
|
||||
escape_and_impact if on_its_scale(escape_and_impact) else 0,
|
||||
)
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
||||
@@ -154,17 +178,36 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
|
||||
return reply
|
||||
verdict = verdict_from(structured_output(reply))
|
||||
replied = json.dumps(reply, ensure_ascii=False)
|
||||
cost = cost_of(reply)
|
||||
if isinstance(verdict, Failure):
|
||||
return Rejected(verdict.reason, replied)
|
||||
return Rejected(verdict.reason, replied, cost)
|
||||
checked = quotes_checked(verdict, grounds)
|
||||
if isinstance(checked, Failure):
|
||||
return Rejected(checked.reason, replied, cost)
|
||||
return dataclasses.replace(checked, judge_cost=cost)
|
||||
|
||||
|
||||
def cost_of(reply: dict) -> float:
|
||||
"""What the run behind claude's json reply cost in dollars; 0 where the reply records none."""
|
||||
cost = reply.get("total_cost_usd")
|
||||
return float(cost) if isinstance(cost, int | float) and not isinstance(cost, bool) and cost > 0 else 0.0
|
||||
|
||||
|
||||
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure:
|
||||
"""The verdict with each of its quotes checked against the text it must appear in, as written:
|
||||
|
||||
| Quote | Must be in | Where it isn't |
|
||||
|---|---|---|
|
||||
| the evidence | grounds.shown, the evidence's fragments in order | a Failure: run_judge rejects the reply, and judge retries it |
|
||||
| a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried |
|
||||
| the escalation | grounds.shown and grounds.since_step | the escalation is dropped, so the worker's rung holds, as escalation_mark.checked says |
|
||||
|
||||
Only a misquoted evidence fails. A Failure for either of the other two would exit an unattended loop, so each changes the verdict instead.
|
||||
"""
|
||||
if not grounded(verdict.evidence, grounds.shown):
|
||||
return Rejected(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""), replied)
|
||||
return quotes_checked(verdict, grounds)
|
||||
|
||||
|
||||
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
|
||||
"""The verdict with its quoted answer and its escalation checked. A quoted answer that neither README.md's premises nor the records hold goes to the human as an interrupt, which keeps the escalation the answer carried. Neither misquote is a Failure, which would otherwise exit an unattended loop."""
|
||||
return Failure(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""))
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
|
||||
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, highest_likelihood_taken_in=verdict.highest_likelihood_taken_in)
|
||||
verdict = Interrupt(verdict.evidence, verdict.question, escalation=verdict.escalation, taken_in=verdict.taken_in)
|
||||
return escalation_mark.checked(verdict, since=grounds.since_step, shown=grounds.shown)
|
||||
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ from model_routing.ladder import climbed, LADDER, position, Rung
|
||||
from model_routing.route import ESCALATION_MARKER, Route
|
||||
from loop_claude.routing import escalation_rungs
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
|
||||
from markdown_text import listed, quoted
|
||||
from review_passes import REVIEWERS
|
||||
from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS
|
||||
from records.markdown_text import listed, quoted
|
||||
from claude_code.transcript import Typed
|
||||
|
||||
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
|
||||
@@ -13,12 +13,16 @@ QUOTE_SOURCES = listed(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_
|
||||
# Where the worker may write an answer the human typed, so it counts as recorded.
|
||||
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
|
||||
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
|
||||
# How review_launches names the reviews: "each reviewer" covers every pass with an agent that no replay lowered.
|
||||
# How review_launches names the reviews: "each reviewer" covers every pass with an agent.
|
||||
EACH_REVIEWER = "each reviewer"
|
||||
EACH_SEAT = "each comprehension seat"
|
||||
THE_SECURITY_PASS = "the security pass's subagent"
|
||||
|
||||
|
||||
# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings.
|
||||
READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context."
|
||||
|
||||
|
||||
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
|
||||
|
||||
|
||||
@@ -26,7 +30,7 @@ def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: s
|
||||
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
|
||||
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
|
||||
opening = f"{routed}\n\n" if routed else ""
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
|
||||
|
||||
|
||||
def routed_by(route: Route, project: Rung | None) -> str:
|
||||
@@ -53,26 +57,37 @@ def preflight_failed(reason: str) -> str:
|
||||
|
||||
|
||||
def review_launches(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentences naming where to launch reviews, in this order; none off the ladder:
|
||||
- one for each rung, other than the worker's, that a reviewer, a seat or the security pass runs on;
|
||||
- the rung of each pass a replay lowered;
|
||||
- where the security pass runs on another rung than the worker's, that a full scan runs only from its subagent;
|
||||
- where the worker runs below the project's rung, where to launch a subagent that files or scores todo.md items;
|
||||
- the reviewers' rung each higher E + I picks.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they open: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: `Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
|
||||
"""
|
||||
"""The sentences naming where to launch reviews, in this order, each from the function that says when it applies; none off the ladder."""
|
||||
if project is None:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
lowered = [f"Launch each {REVIEWERS[kind]} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for kind, rung in choice.lowered.items()]
|
||||
scan = ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
|
||||
planning = [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
|
||||
return [*shared_launches(choice, route, project), *lowered, *scan, *planning, *taken_in_launches(choice)]
|
||||
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice, project)]
|
||||
|
||||
|
||||
def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
|
||||
"""Where the security pass runs on another rung than the worker's, the sentence that a full scan runs only from the security pass's subagent, which shared_launches names just before: `Run a full scan only from such a subagent, since the scan's agents run on the model that starts them.`"""
|
||||
return ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
|
||||
|
||||
|
||||
def planning_launch(route: Route, project: Rung) -> list[str]:
|
||||
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `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 claude-opus-5-5 <L>` prints.`"""
|
||||
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):
|
||||
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()}."]
|
||||
|
||||
|
||||
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
|
||||
"""A sentence for each rung, other than the worker's, that the reviewers no replay lowered, the seats or the security pass run on."""
|
||||
"""A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.`
|
||||
"""
|
||||
together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security}
|
||||
launched: dict[Rung, list[str]] = {}
|
||||
for reviews, rung in together.items():
|
||||
@@ -125,19 +140,13 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
|
||||
|
||||
def reruns(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. None off the ladder.
|
||||
"""The sentence naming the rung one above a reviewer's and the one above a seat's, on which each reruns when it asks, leaving out either that is already on the top rung. None off the ladder.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.` and `Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
lowered = [f"Rerun each {REVIEWERS[kind]} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for kind, rung in choice.lowered.items()]
|
||||
return [*shared_reruns(choice), *lowered]
|
||||
|
||||
|
||||
def shared_reruns(choice: ReviewChoice) -> list[str]:
|
||||
"""The sentence naming the rung one above choice.reviewers and the one above choice.seat, leaving out either that is already on the top rung."""
|
||||
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
|
||||
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
|
||||
if not rerun:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.stop import Stop
|
||||
@@ -24,7 +23,7 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
|
||||
failures = 0
|
||||
now = effects.now()
|
||||
wait = limit_wait(result, now)
|
||||
print(f"the {who} hit a usage limit ({result.said}); retrying at {effects.local_time(now + wait)}", file=sys.stderr, flush=True)
|
||||
say(f"the {who} hit a usage limit ({result.said}); retrying at {effects.local_time(now + wait)}", effects)
|
||||
effects.sleep(wait)
|
||||
continue
|
||||
if not isinstance(result, Failure):
|
||||
@@ -34,7 +33,7 @@ def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effec
|
||||
failures += 1
|
||||
if failures == FAILURES_RUNNING:
|
||||
return Stop(1, f"the {who} failed three times running: {result.reason}")
|
||||
print(f"retrying the {who} in a minute: {result.reason}", file=sys.stderr)
|
||||
say(f"retrying the {who} in a minute: {result.reason}", effects)
|
||||
effects.sleep(RETRY_DELAY)
|
||||
|
||||
|
||||
|
||||
@@ -2,44 +2,49 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.routing import after_ruling, judge_rung
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, to_the_human, transition, TypedAnswer, WorkerRan, Working
|
||||
from transcript_archive.write import archive
|
||||
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
from claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
|
||||
from loop_claude.cycle.judge import judge, Rejected
|
||||
from loop_claude.routing import judge_rung, next_route, step_up, StepUp
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.escalation_mark import StepUp
|
||||
from loop_claude.stop import Stop
|
||||
from model_routing import worker_rungs
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cycle:
|
||||
"""What a cycle runs on. run_cycle replaces the route on a ruling's step-up; nothing changes the other fields.
|
||||
|
||||
Each step reads the few fields it needs by name, so the fields stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows more than seven where a reader finds them by name.
|
||||
"""
|
||||
effects: Effects
|
||||
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
|
||||
facts: str
|
||||
judge_model: str
|
||||
paths: Paths
|
||||
premises: str
|
||||
project_archive: pathlib.Path
|
||||
records: str
|
||||
root: str
|
||||
session: Session
|
||||
task: str
|
||||
route: Route
|
||||
# The project's rung; None for a model off the ladder.
|
||||
project: Rung | None
|
||||
project_archive: pathlib.Path
|
||||
# Where the loop keeps its questions for loop-inbox: running_loops.Listed.folder.
|
||||
questions: pathlib.Path
|
||||
records: str
|
||||
root: str
|
||||
route: Route
|
||||
session: Session
|
||||
# Lists in loop-inbox the items the chunk takes, given the IDs an unfinished ruling found taken in.
|
||||
show_taken_in: typing.Callable[[tuple[int, ...]], None]
|
||||
task: str
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
|
||||
@@ -58,9 +63,11 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
|
||||
event = step(cycle, state)
|
||||
if isinstance(event, Stop):
|
||||
return stopped(cycle, event, event.reason)
|
||||
# Only a ruling's step-up changes the route within a cycle. No transition reads the current route, so Cycle holds it, not the states.
|
||||
if isinstance(event, Ruled) and event.step_up:
|
||||
cycle = dataclasses.replace(cycle, route=event.step_up.after)
|
||||
# Only a ruling's step-up changes the route within a cycle, here, once rule has archived the ruling on the route before it. No transition reads the current route, so Cycle holds it, not the states.
|
||||
if isinstance(event, Ruled) and event.stepped_to:
|
||||
cycle = dataclasses.replace(cycle, route=event.stepped_to)
|
||||
if isinstance(event, Ruled) and not isinstance(event.verdict, Finished):
|
||||
cycle.show_taken_in(event.verdict.taken_in.items)
|
||||
state = transition(state, event)
|
||||
except KeyboardInterrupt:
|
||||
return stopped(cycle, Stop(130, ""), "Ctrl-C")
|
||||
@@ -68,17 +75,18 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
|
||||
|
||||
|
||||
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
|
||||
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds."""
|
||||
if not (isinstance(verdict, Interrupt | QuotedAnswer) and cycle.project):
|
||||
return None
|
||||
after = after_ruling(cycle.project, cycle.route, verdict)
|
||||
return StepUp(cycle.route, after) if after != cycle.route else None
|
||||
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds. A finished or unfinished verdict steps the route only as the loop starts the next cycle."""
|
||||
return step_up(cycle.route, next_route(cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None
|
||||
|
||||
|
||||
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
|
||||
path = transcript_file(cycle.session)
|
||||
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(cycle.route.worker_line(), why), cycle.effects.now()) if path else None
|
||||
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
|
||||
return archived_stop(cycle.project_archive, cycle.session, cycle.task, cycle.route, stop, why, cycle.effects)
|
||||
|
||||
|
||||
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
|
||||
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
|
||||
|
||||
|
||||
@@ -89,99 +97,102 @@ def judge_of(cycle: Cycle) -> Rung:
|
||||
|
||||
def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
match state:
|
||||
case Working(answered, _, step_up):
|
||||
return work(cycle, answered, step_up)
|
||||
case Judging(transcript_path, _):
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, _):
|
||||
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
|
||||
case Working(answered, _, stepped):
|
||||
return work(cycle, answered, stepped)
|
||||
case Judging(transcript_path, quoted_answers):
|
||||
return rule(cycle, transcript_path, quoted_answers)
|
||||
case Interrupting(transcript_path, ruling, _, _):
|
||||
return ask(cycle, transcript_path, ruling)
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
typing.assert_never(state)
|
||||
|
||||
|
||||
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> WorkerRan | Stop:
|
||||
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> WorkerRan | Stop:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
|
||||
if stop := keep_answer(cycle, answered, step_up):
|
||||
return stop
|
||||
say(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True)
|
||||
# worker_start runs inside the lambda: a failed attempt may have opened the session.
|
||||
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, step_up), worker_environment(cycle), cycle.effects), cycle.effects):
|
||||
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, stepped), worker_environment(cycle), cycle.effects), cycle.effects):
|
||||
return stop
|
||||
path = transcript_file(cycle.session)
|
||||
return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}")
|
||||
|
||||
|
||||
def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to."""
|
||||
return worker_rungs.environment(cycle.project, cycle.route)
|
||||
"""The rungs the worker's claude is handed, which rule-hook holds its review launches to, and the auto-compact window of its context."""
|
||||
return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)}
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]:
|
||||
def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
|
||||
return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle))
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
|
||||
if isinstance(answered, TypedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
|
||||
if session_open(cycle.session):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
|
||||
|
||||
|
||||
def keep_answer(cycle: Cycle, answered: QuotedAnswer, step_up: StepUp | None) -> Stop | None:
|
||||
path = transcript_file(cycle.session)
|
||||
if not path:
|
||||
return None
|
||||
# As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then.
|
||||
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), ran_on(cycle, step_up).worker_line())
|
||||
if failure := archive_stepped(cycle, path, quoted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
return None
|
||||
|
||||
|
||||
def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
|
||||
def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop:
|
||||
"""The judge's ruling. An interrupt or a quoted answer is archived as it is ruled, on the route the worker ran on until then, and then any step-up it makes, so the figures charge each stretch of work to its own rung."""
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
|
||||
return verdict if isinstance(verdict, Stop) else Ruled(verdict, ruling_step_up(cycle, verdict))
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
if not isinstance(verdict, Interrupt | QuotedAnswer):
|
||||
return Ruled(verdict)
|
||||
stepped = ruling_step_up(cycle, verdict)
|
||||
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers), stepped):
|
||||
return Stop(1, failure.reason)
|
||||
return Ruled(verdict, stepped.after if stepped else None)
|
||||
|
||||
|
||||
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.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))), cycle.effects.now()):
|
||||
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)):
|
||||
return Stop(1, unkept.reason)
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, ran_on(cycle, step_up).worker_line())
|
||||
if failure := archive_stepped(cycle, transcript_path, interrupted, step_up):
|
||||
return Stop(1, failure.reason)
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
|
||||
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript."""
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
|
||||
if isinstance(answer, Stop):
|
||||
return answer
|
||||
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.questions, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
case Talked():
|
||||
return HumanTalked()
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route:
|
||||
"""The route the worker ran on until the ruling: the one before its step-up, if it made one."""
|
||||
return step_up.before if step_up else cycle.route
|
||||
return HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
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."""
|
||||
for kept in (outcome, outcomes.stepped_up(step_up.after.worker_line())) if step_up else (outcome,):
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
|
||||
return failure
|
||||
return None
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now(), lambda text: say(text, cycle.effects)):
|
||||
return failure
|
||||
return archived_step(cycle.project_archive, transcript_path, cycle.task, step_up, cycle.effects)
|
||||
|
||||
|
||||
def archived_step(project_archive: pathlib.Path, transcript_path: str, task: str, step_up: StepUp | None, effects: Effects) -> Failure | None:
|
||||
"""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))
|
||||
|
||||
|
||||
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
@@ -191,8 +202,8 @@ 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))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()):
|
||||
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)):
|
||||
return Stop(1, failure.reason)
|
||||
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
|
||||
return Stop(1, failure.reason)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.escalation_mark import StepUp
|
||||
from model_routing.route import Route
|
||||
|
||||
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records.
|
||||
QUOTED_ANSWERS_PER_CYCLE = 3
|
||||
@@ -9,7 +9,7 @@ QUOTED_ANSWERS_PER_CYCLE = 3
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TypedAnswer:
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal or in loop-inbox."""
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
@@ -19,8 +19,8 @@ class Working:
|
||||
"""The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one."""
|
||||
answered: QuotedAnswer | TypedAnswer | None = None
|
||||
quoted_answers: int = 0
|
||||
# The step-up made by the ruling that brought the answer, so the worker is told of it; None for none.
|
||||
step_up: StepUp | None = None
|
||||
# Whether the ruling that brought the answer stepped the worker up a rung, so the worker is told of it.
|
||||
stepped: bool = False
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -32,19 +32,12 @@ class Judging:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupting:
|
||||
"""The human answers; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
"""The human answers, by typing or in the worker's claude session; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
transcript_path: str
|
||||
ruling: Interrupt | QuotedAnswer
|
||||
quoted_answers: int = 0
|
||||
# The step-up the ruling made. It holds through the answer the human types, and drops on /talk.
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal."""
|
||||
transcript_path: str
|
||||
quoted_answers: int = 0
|
||||
# Whether the ruling stepped the worker up a rung. It holds through the answer the human types, and drops on /talk.
|
||||
stepped: bool = False
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -58,7 +51,7 @@ class Ended:
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
Active = Working | Judging | Interrupting | Talking | Closing
|
||||
Active = Working | Judging | Interrupting | Closing
|
||||
State = Active | Ended
|
||||
|
||||
|
||||
@@ -70,8 +63,8 @@ class WorkerRan:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ruled:
|
||||
verdict: Verdict
|
||||
# None unless an interrupt's or a quoted answer's escalation stepped the route; always None for a finished or unfinished verdict.
|
||||
step_up: StepUp | None = None
|
||||
# The route an interrupt's or a quoted answer's escalation stepped the worker up to, which the cycle runs on from here; None where the route holds, and always for a finished or unfinished verdict.
|
||||
stepped_to: Route | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -79,14 +72,9 @@ class HumanTyped:
|
||||
typed: TypedAnswer
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk, or the interrupt is for a release ready to cut."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
"""The human typed in the worker's claude session, which /talk opens, or a release ready to cut opens at once."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -94,27 +82,28 @@ class Archived:
|
||||
pass
|
||||
|
||||
|
||||
Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | Archived
|
||||
Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived
|
||||
|
||||
|
||||
def to_the_human(ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> bool:
|
||||
"""Whether a ruling goes to the human: an interrupt always, a quoted answer once the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
|
||||
return isinstance(ruling, Interrupt) or quoted_answers >= QUOTED_ANSWERS_PER_CYCLE
|
||||
|
||||
|
||||
def transition(state: State, event: Event) -> State:
|
||||
match state, event:
|
||||
case Working(_, quoted_answers), WorkerRan(transcript_path):
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, step_up) if quoted_answers < QUOTED_ANSWERS_PER_CYCLE:
|
||||
return Working(answered, quoted_answers + 1, step_up)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(QuotedAnswer() as ruling, step_up) if quoted_answers >= QUOTED_ANSWERS_PER_CYCLE:
|
||||
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() as ruling, step_up):
|
||||
return Interrupting(transcript_path, ruling, quoted_answers, step_up)
|
||||
case Judging(transcript_path, quoted_answers), Ruled(Interrupt() | QuotedAnswer() as ruling, stepped_to) if to_the_human(ruling, quoted_answers):
|
||||
return Interrupting(transcript_path, ruling, quoted_answers, stepped_to is not None)
|
||||
case Judging(_, quoted_answers), Ruled(QuotedAnswer() as answered, stepped_to):
|
||||
return Working(answered, quoted_answers + 1, stepped_to is not None)
|
||||
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
|
||||
return Closing(transcript_path, verdict)
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
|
||||
return Talking(transcript_path, quoted_answers)
|
||||
case Interrupting(_, _, quoted_answers, stepped), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, stepped)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, quoted_answers), HumanTalked():
|
||||
case Interrupting(transcript_path, _, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import sys
|
||||
|
||||
from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from claude_code.transcript import part_line
|
||||
@@ -12,6 +10,9 @@ from claude_code.session import Session
|
||||
PRINTED_TOOL_INPUT = 160
|
||||
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
|
||||
MEMORY_POLL = 60
|
||||
# The auto-compact window, in tokens, handed to the worker's claude in the environment variable AUTO_COMPACT_WINDOW names. Claude Code compacts before the window fills, at about 170k: docs/decisions.md → `loop-claude: the worker's claude compacts its context before it fills a 200k window`.
|
||||
AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
|
||||
COMPACT_WINDOW = 200_000
|
||||
|
||||
|
||||
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
|
||||
@@ -30,7 +31,7 @@ def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects
|
||||
resets.append(resets_at)
|
||||
for part in assistant_parts(event):
|
||||
if line := part_line(part, PRINTED_TOOL_INPUT):
|
||||
print(line, flush=True)
|
||||
say(line, effects, stdout=True)
|
||||
return worker_outcome(proc.wait(), result, resets)
|
||||
|
||||
|
||||
@@ -39,7 +40,7 @@ def wait_for_memory(effects: Effects) -> None:
|
||||
said = False
|
||||
while (memory := effects.memory()) is not None and not memory.has_room():
|
||||
if not said:
|
||||
print(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", file=sys.stderr, flush=True)
|
||||
say(f"waiting to start the worker until at least {ROOM_SHARE:.0%} of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is available now", effects)
|
||||
said = True
|
||||
effects.sleep(MEMORY_POLL)
|
||||
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
"""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."""
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from failure import Failure
|
||||
import git_repo
|
||||
from git_cli import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# Seconds between a loop's looks for an answer from loop-inbox while it reads its terminal, and for the end of the claude loop-inbox opened.
|
||||
POLL_SECONDS = 0.5
|
||||
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
|
||||
PYTHON_TIMEOUT = 600
|
||||
|
||||
|
||||
class Git(typing.Protocol):
|
||||
"""Runs git in cwd, as git_repo.git does."""
|
||||
class InputOr(typing.Protocol):
|
||||
"""Prints a prompt, then returns the line typed at the terminal, or the first answer that other returns, called every POLL_SECONDS. Raises EOFError where the input ends."""
|
||||
|
||||
def __call__(self, *args: str, cwd: str) -> str | Failure: ...
|
||||
def __call__[T](self, prompt: str, other: typing.Callable[[], T | None]) -> str | T: ...
|
||||
|
||||
|
||||
class Streaming(typing.Protocol):
|
||||
@@ -30,18 +35,24 @@ class Streaming(typing.Protocol):
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Effects:
|
||||
# Whether the process with this pid still runs.
|
||||
alive: typing.Callable[[int], bool]
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: Git
|
||||
git: git_repo.Git
|
||||
input: typing.Callable[[str], str]
|
||||
input_or: InputOr
|
||||
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
|
||||
local_time: typing.Callable[[float], str]
|
||||
# The machine's memory; None where it cannot be read.
|
||||
memory: typing.Callable[[], Memory | None]
|
||||
new_id: typing.Callable[[], str]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
pid: typing.Callable[[], int]
|
||||
# Runs a Python script in a directory, as run_python does.
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
@@ -62,22 +73,46 @@ class StreamingClaude:
|
||||
|
||||
def system_effects() -> Effects:
|
||||
return Effects(
|
||||
alive=alive,
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
input=input,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)),
|
||||
input_or=input_or,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
|
||||
memory=read_memory,
|
||||
new_id=lambda: str(uuid.uuid4()),
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
pid=os.getpid,
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
|
||||
|
||||
def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
|
||||
"""Runs claude on the terminal in cwd, with env added to its environment, and returns its exit code. While claude runs, Ctrl-C belongs to it: this process shares its terminal, and ignores the key."""
|
||||
# A Python handler, unlike SIG_IGN, is reset to the default as claude starts, so Ctrl-C still reaches claude.
|
||||
previous = signal.signal(signal.SIGINT, lambda number, frame: None)
|
||||
try:
|
||||
return subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, previous)
|
||||
|
||||
|
||||
def alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr."""
|
||||
command = [sys.executable, *args]
|
||||
@@ -87,3 +122,25 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"could not start: {failure}")
|
||||
except subprocess.TimeoutExpired:
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T:
|
||||
# On stderr, where input prints its prompt on a terminal.
|
||||
print(prompt, end="", file=sys.stderr, flush=True)
|
||||
while True:
|
||||
if select.select([sys.stdin], [], [], POLL_SECONDS)[0]:
|
||||
# On a terminal, one read returns at most one line, so nothing typed after it is buffered here, out of discard_typed's reach.
|
||||
line = os.read(sys.stdin.fileno(), 65536)
|
||||
if not line:
|
||||
raise EOFError
|
||||
return line.decode("utf-8", "replace").removesuffix("\n")
|
||||
if (got := other()) is not None:
|
||||
print(file=sys.stderr, flush=True) # Ends the prompt's line.
|
||||
return got
|
||||
|
||||
|
||||
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
|
||||
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
|
||||
body = text.lstrip("\n")
|
||||
blanks = text[: len(text) - len(body)]
|
||||
print(f"{blanks}{effects.local_time(effects.now())} {body}", file=sys.stdout if stdout else sys.stderr, flush=True)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
A worker whose run ends asking loop-claude for a higher rung cites the trigger that fired, and the judge quotes the passage where it fired as the verdict's escalation. The mark, Route.escalated_at, is how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The session's transcript only grows, so the mark holds across cycles, and the archive's Worker: lines keep it for a rerun.
|
||||
|
||||
- Stamp. stamped() writes on the judge's verdict how many entries the judge read.
|
||||
- Step. routing.after_unfinished() and routing.after_ruling() step the worker up on an escalation and move the mark to moved_to(verdict). A ruling's StepUp travels through the cycle's states, so the archive and the worker's next prompt name it.
|
||||
- Step. routing.next_route() steps the worker up on an escalation and moves the mark to moved_to(verdict).
|
||||
- Show. transcript() puts STEP_LINE after the mark, telling the judge that the triggers before that line are spent. QUOTE_AFTER_STEP, in the judge's schema, tells the judge to quote only the worker's words after that line.
|
||||
- Check. checked() keeps an escalation only where it quotes both the transcript the judge was shown and the worker's own lines after the mark, which since_step() renders, so a passage that bought one step cannot buy another.
|
||||
"""
|
||||
@@ -13,7 +13,6 @@ import typing
|
||||
from loop_claude.verdicts import Escalating, Verdict
|
||||
from claude_code.entries import human_text, loop_text
|
||||
from claude_code.transcript import render, Typed, verbatim
|
||||
from model_routing.route import Route
|
||||
|
||||
# Only the judge reads the step line, so it is not a [loop] line.
|
||||
STEP_TAG = "[step]"
|
||||
@@ -22,13 +21,6 @@ STEP_LINE = f"{STEP_TAG} loop-claude stepped the worker up a rung here, so the e
|
||||
QUOTE_AFTER_STEP = f"Where a {STEP_TAG} line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it."
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StepUp:
|
||||
"""An interrupt's or a quoted answer's escalation stepping the route within a cycle: the route the worker ran on until the ruling, and the one it runs on after."""
|
||||
before: Route
|
||||
after: Route
|
||||
|
||||
|
||||
def stamped(verdict: Verdict, entries_read: int) -> Verdict:
|
||||
"""The verdict with how many transcript entries the judge read, where it may carry an escalation."""
|
||||
return dataclasses.replace(verdict, entries_read=entries_read) if isinstance(verdict, Escalating) else verdict
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Opens claude on the terminal for the human. It sits outside cycle/, since loop-inbox's /talk and the loop's routing calls open claude too."""
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeCommand:
|
||||
"""How claude opens on a terminal: its arguments, its folder and what it adds to the environment."""
|
||||
args: list[str]
|
||||
cwd: str
|
||||
env: dict[str, str]
|
||||
|
||||
|
||||
def claude_args(rung: Rung, args: list[str]) -> list[str]:
|
||||
return [*rung.flags(), "--permission-mode", "bypassPermissions", *args]
|
||||
|
||||
|
||||
# CLAUDE_CODE_SANDBOXED, which Claude Code doesn't document, skips its trust dialog without writing ~/.claude.json:
|
||||
# docs/decisions.md → `loop-claude: every claude it or loop-inbox opens on a terminal has CLAUDE_CODE_SANDBOXED set`.
|
||||
def hand_over(command: ClaudeCommand, effects: Effects) -> Failure | None:
|
||||
"""Runs claude on the terminal as command says, with CLAUDE_CODE_SANDBOXED=1 added to its environment; the failure is why claude could not start."""
|
||||
try:
|
||||
effects.claude_on_terminal(command.args, command.cwd, {**command.env, "CLAUDE_CODE_SANDBOXED": "1"})
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
@@ -0,0 +1,90 @@
|
||||
"""How a cycle starts: the route it runs on, from the archive or the plan, the facts chunk-preflight finds for a fresh chunk, and the items loop-inbox lists."""
|
||||
import pathlib
|
||||
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 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.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
|
||||
|
||||
# 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]:
|
||||
"""A function that lists in loop-inbox the items a chunk takes, given the IDs the judge found taken in. routed is the item the chunk was routed on, 0 for none. shown_items reads todo.md once, as the cycle starts, and the function shows those taglines."""
|
||||
todo = fetched_todo(root)
|
||||
return lambda taken_in: show(taken_items(todo, routed, taken_in))
|
||||
|
||||
|
||||
def fetched_todo(root: str) -> str | Failure:
|
||||
"""todo.md on the default branch, as last fetched. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which the listing doesn't need."""
|
||||
ref = default_ref(root, ORIGIN_TIMEOUT)
|
||||
return ref if isinstance(ref, Failure) else file_at(ref, "todo.md", root)
|
||||
|
||||
|
||||
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
"""The route the cycle runs on. project is the project's rung, and model the project's model.
|
||||
|
||||
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
|
||||
"""
|
||||
if project is None:
|
||||
return Route(Rung(model))
|
||||
route = route or archived()
|
||||
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)
|
||||
worker = latest_worker(archive_folder, transcript) if transcript else None
|
||||
if isinstance(worker, Failure):
|
||||
say(f"routing the chunk afresh: {worker.reason}", 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)
|
||||
return route
|
||||
|
||||
|
||||
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> 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)
|
||||
|
||||
|
||||
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> 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)
|
||||
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:
|
||||
"""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)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk, release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
elif isinstance(plan.todo, Failure):
|
||||
item = plan.todo
|
||||
else:
|
||||
item = routed_item(plan.todo, plan.cut)
|
||||
if isinstance(item, Failure):
|
||||
say(f"routing on the project's rung: {item.reason}", effects)
|
||||
return None
|
||||
return item
|
||||
@@ -0,0 +1,47 @@
|
||||
"""How a cycle closes: the loop run the next cycle starts from, the step-up an unfinished verdict makes archived, and the stop once a chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
|
||||
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.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
|
||||
|
||||
# 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:
|
||||
"""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)):
|
||||
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 after
|
||||
|
||||
|
||||
def reached_limit(loop_run: LoopRun) -> Stop | None:
|
||||
"""The stop that needs the human once the loop run holds UNFINISHED_LIMIT unfinished verdicts running."""
|
||||
if loop_run.unfinished_run < UNFINISHED_LIMIT:
|
||||
return None
|
||||
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
|
||||
|
||||
|
||||
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route, its run of unfinished verdicts and the items it took in. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; the evidence the judge gave for the verdict and the items it found taken in; and counts the verdict."""
|
||||
verdict = concluded.verdict
|
||||
if isinstance(verdict, Finished):
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0, items_taken_in=())
|
||||
route = next_route(project, concluded.route, verdict)
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1, items_taken_in=verdict.taken_in.items)
|
||||
+50
-239
@@ -1,148 +1,27 @@
|
||||
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
||||
worker prompt also quotes the premises. They, with code health
|
||||
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
|
||||
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
|
||||
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
||||
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
|
||||
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
|
||||
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
|
||||
writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the
|
||||
worker made that the premises or the records settle is not asked about. When the worker asks a
|
||||
question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes
|
||||
with it. A quote they do not hold word for word is dropped, and the question goes to the human. So
|
||||
does a question asked again after its answer. The fourth question they answer in one cycle goes to
|
||||
the human too, with the quote. An unfinished chunk resumes its session next cycle, and the worker
|
||||
is shown the passage the judge quoted as the work remaining. The next chunk starts a fresh session.
|
||||
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question and reads a one-line answer on its terminal. The worker resumes
|
||||
headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the
|
||||
answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session
|
||||
on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits,
|
||||
the judge rules on what was typed there. A release ready to cut opens that session at once, since
|
||||
only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
prompts.preflight_facts in bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A
|
||||
preflight that fails, or is still running after 600 s and is stopped, leaves the worker to find the
|
||||
facts itself.
|
||||
|
||||
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
||||
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
|
||||
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is available
|
||||
(bin/machine_load/memory.py).
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
||||
entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the
|
||||
judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing
|
||||
is asked.
|
||||
|
||||
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
||||
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
||||
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
|
||||
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
|
||||
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
|
||||
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
|
||||
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
||||
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
||||
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
without it.
|
||||
|
||||
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
|
||||
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
|
||||
on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls
|
||||
are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the
|
||||
calls are said on stderr, the loop goes on, and they are raised again at the next measurement.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- README.md, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
||||
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
|
||||
- README.md holds no premises
|
||||
- the models file cannot be read or written
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
- claude cannot start for an interrupt
|
||||
- python cannot start for a reload
|
||||
- a reload cannot read the state the running script handed it, likely because the edit changed that
|
||||
handover
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
||||
mistypes a field, interrupts or quotes an answer without a question, or quotes a passage the
|
||||
transcript does not hold; it holds an elided passage when each fragment appears in order.
|
||||
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
|
||||
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
|
||||
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
||||
always retried every 10 minutes. stderr says when the next try is due.
|
||||
|
||||
Exit 2, when the human is needed and cannot answer:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, or for a release ready to cut, ends with nothing typed
|
||||
Rerunning resumes any open session.
|
||||
|
||||
"""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.routing import after_unfinished, first_route, kept, routed_item
|
||||
from transcript_archive.write import archive
|
||||
from transcript_archive.location import archive_root, project_archive
|
||||
from loop_claude.loop.chunk_start import archived_route, chunk_start, routed, shown_items
|
||||
from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.cycle.run import Concluded, Cycle, run_cycle
|
||||
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 chunk_pick import default_plan, DefaultPlan
|
||||
from git_repo import default_ref
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Unfinished
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from todo_table import Item
|
||||
from transcript_archive.read import latest_worker
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.loop.usage import HELP
|
||||
from loop_claude.running_loops import Listed, shown_running
|
||||
from loop_claude.paths import Paths
|
||||
from project_key import project_key
|
||||
from model_routing.ladder import project_rung, Rung
|
||||
from loop_claude.cycle import prompts
|
||||
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 model_routing.route import Route, route_from
|
||||
from claude_code.session import Session, session_named, session_open, transcript_file
|
||||
from claude_code.session import Session, session_named
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
# 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 main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
@@ -151,7 +30,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
if stop.reason:
|
||||
print(stop.reason, file=sys.stderr if stop.code else sys.stdout)
|
||||
say(stop.reason, effects, stdout=not stop.code)
|
||||
return stop.code
|
||||
|
||||
|
||||
@@ -160,123 +39,55 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
if isinstance(loop_run, Stop):
|
||||
return loop_run
|
||||
baseline = fingerprint(launcher)
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
archive_folder = project_archive(loop_run.root, paths.home, env)
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
session = session_named(f"A {key} loop-claude", paths.claude_code_transcripts)
|
||||
while True:
|
||||
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||
return stop
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
premises = read_premises(loop_run.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
records = read_records(loop_run.root, paths.claude_dir)
|
||||
if isinstance(records, Stop):
|
||||
return records
|
||||
models = get_or_ask_models(key, paths, env, effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
# After the reads above, so a loop that stops on one makes no worktree.
|
||||
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
project = project_rung(models.worker)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session), item)
|
||||
print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True)
|
||||
concluded = run_cycle(Cycle(effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
loop_run = after_verdict(loop_run, project, concluded)
|
||||
if stop := archive_step(archive_folder, session, loop_run.task, concluded.route, loop_run.route, effects):
|
||||
return stop
|
||||
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
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:
|
||||
while True:
|
||||
if stop := exec_if_edited(launcher, baseline, loop_run, effects):
|
||||
return stop
|
||||
loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1)
|
||||
cycle = next_cycle(loop_run, session, listed, paths, env, launcher, effects)
|
||||
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)
|
||||
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):
|
||||
return stop
|
||||
|
||||
|
||||
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
"""The route the cycle runs on. project is the project's rung, and model the project's model.
|
||||
|
||||
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
|
||||
"""
|
||||
if project is None:
|
||||
return Route(Rung(model))
|
||||
route = route or archived()
|
||||
return route if route and kept(route, project) else first_route(project, item())
|
||||
|
||||
|
||||
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route. An unfinished one takes the route stepped_route makes, and the evidence the judge gave for the verdict."""
|
||||
verdict = concluded.verdict
|
||||
if isinstance(verdict, Finished):
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
|
||||
return dataclasses.replace(loop_run, route=stepped_route(project, concluded.route, verdict), unfinished_evidence=verdict.evidence)
|
||||
|
||||
|
||||
def stepped_route(project: Rung | None, ended_on: Route, verdict: Unfinished) -> Route:
|
||||
"""The route an unfinished chunk's next cycle starts on: the route after_unfinished makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised. Off the ladder there is no rung to step, and it keeps that route."""
|
||||
return after_unfinished(project, ended_on, verdict) if project else ended_on
|
||||
|
||||
|
||||
def archive_step(archive_folder: pathlib.Path, session: Session, task: str, before: Route, after: Route | None, effects: Effects) -> Stop | None:
|
||||
"""Archives the route after an unfinished verdict as a step-up, where its worker line differs from the one before it: a higher rung, or a higher E + I taken in. The verdict itself names the route before, which its cycle ran on."""
|
||||
if after is None or after.worker_line() == before.worker_line():
|
||||
return None
|
||||
path = transcript_file(session)
|
||||
failure = archive(archive_folder, path, task, outcomes.stepped_up(after.worker_line()), effects.now()) if path else None
|
||||
return Stop(1, failure.reason) if failure else None
|
||||
|
||||
|
||||
def archived_route(archive_folder: pathlib.Path, session: Session) -> 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)
|
||||
worker = latest_worker(archive_folder, transcript) if transcript else None
|
||||
if isinstance(worker, Failure):
|
||||
print(f"routing the chunk afresh: {worker.reason}", file=sys.stderr)
|
||||
return None
|
||||
route = route_from(worker) if worker else None
|
||||
if worker and route is None:
|
||||
print(f"routing the chunk afresh: the archive's latest Worker: line names no route loop-claude can read: {worker}", file=sys.stderr)
|
||||
return route
|
||||
|
||||
|
||||
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> 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))
|
||||
|
||||
|
||||
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
|
||||
"""What chunk-preflight printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
|
||||
done = effects.python([str(preflight)], 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:
|
||||
"""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)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure) -> Item | None:
|
||||
"""The item that routes a chunk, chunk_pick.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
elif isinstance(plan.todo, Failure):
|
||||
item = plan.todo
|
||||
else:
|
||||
item = routed_item(plan.todo, plan.cut)
|
||||
if isinstance(item, Failure):
|
||||
print(f"routing on the project's rung: {item.reason}", file=sys.stderr)
|
||||
return None
|
||||
return item
|
||||
def next_cycle(loop_run: LoopRun, session: Session, listed: Listed, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> 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)
|
||||
if isinstance(premises, Failure):
|
||||
return Stop(1, premises.reason)
|
||||
records = read_records(loop_run.root, 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)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
archive_folder = project_archive(loop_run.root, paths.home, 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)
|
||||
project = project_rung(models.worker)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, session, effects), item)
|
||||
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", effects, stdout=True)
|
||||
show_taken_in = shown_items(listed.show, loop_run.root, route.item)
|
||||
show_taken_in(loop_run.items_taken_in)
|
||||
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)
|
||||
|
||||
|
||||
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
|
||||
if argv[:1] != [RELOAD_FLAG]:
|
||||
task = " ".join(argv)
|
||||
if task in ("", "-h", "--help"):
|
||||
return Stop(0 if task else 1, __doc__.strip())
|
||||
return Stop(0 if task else 1, HELP)
|
||||
root = checkout_root(cwd, effects)
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "")
|
||||
loop_run = decode_handed(argv[1], LoopRun) if len(argv) == 2 else None
|
||||
|
||||
@@ -6,7 +6,7 @@ import sys
|
||||
import types
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.effects import Effects, say
|
||||
from model_routing.route import Route
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
@@ -24,6 +24,10 @@ class LoopRun:
|
||||
unfinished_evidence: str
|
||||
# Set by each unfinished verdict; None before the chunk's first one, and once it finishes.
|
||||
route: Route | None = None
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
# The IDs of the items the last unfinished verdict found the chunk takes, which loop-inbox lists until the next ruling.
|
||||
items_taken_in: tuple[int, ...] = ()
|
||||
|
||||
|
||||
def decode_handed(handed: str, kind: type[T]) -> T | None:
|
||||
@@ -41,7 +45,7 @@ RETIRED = object()
|
||||
|
||||
|
||||
def decoded_as(value: object, kind: typing.Any) -> typing.Any:
|
||||
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, else a value of exactly kind."""
|
||||
"""value as kind, REJECTED or RETIRED: a dataclass from an object holding its fields, a union's first member that fits, a tuple of one type from a list, else a value of exactly kind."""
|
||||
if isinstance(kind, types.UnionType):
|
||||
found = [decoded_as(value, option) for option in typing.get_args(kind)]
|
||||
fits = [each for each in found if each is not REJECTED and each is not RETIRED]
|
||||
@@ -62,6 +66,10 @@ def decoded_as(value: object, kind: typing.Any) -> typing.Any:
|
||||
if any(field in (REJECTED, RETIRED) for field in fields.values()) or not getattr(kind, "fits", lambda _: True)(fields):
|
||||
return REJECTED
|
||||
return kind(**fields)
|
||||
if typing.get_origin(kind) is tuple:
|
||||
element = typing.get_args(kind)[0]
|
||||
found = [decoded_as(each, element) for each in value] if isinstance(value, list) else [REJECTED]
|
||||
return REJECTED if REJECTED in found or RETIRED in found else tuple(found)
|
||||
return value if type(value) is kind else REJECTED
|
||||
|
||||
|
||||
@@ -82,7 +90,7 @@ def exec_if_edited(launcher: pathlib.Path, baseline: str, loop_run: LoopRun, eff
|
||||
return None
|
||||
trial = effects.python([str(launcher), "--help"], loop_run.root)
|
||||
if trial.returncode != 0:
|
||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||
say(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", effects)
|
||||
return None
|
||||
try:
|
||||
effects.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(loop_run))])
|
||||
|
||||
@@ -1,59 +1,68 @@
|
||||
"""Every CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`."""
|
||||
"""Every state.CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing: loop-claude measures review rounds…`."""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from routing_figures import archive
|
||||
from routing_figures.measure import calls, due, render, totals
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.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 failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
from loop_claude.waiting.listing import listed
|
||||
from loop_claude.paths import Paths
|
||||
from routing_figures.render import render
|
||||
from model_routing.ladder import Rung
|
||||
from routing_figures import state
|
||||
from loop_claude.stop import Stop
|
||||
from utc_stamp import utc
|
||||
from records.utc_stamp import utc
|
||||
|
||||
|
||||
def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. rung is the rung of the claude that puts the calls to the human."""
|
||||
def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, 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."""
|
||||
with archive.locked(root) as held:
|
||||
new = new_calls(root, paths, effects) if held else []
|
||||
if isinstance(new, Failure):
|
||||
print(f"routing figures: {new.reason}", file=sys.stderr)
|
||||
say(f"routing figures: {new.reason}", effects)
|
||||
return None
|
||||
return raise_calls(root, new, rung, paths, effects) if new else None
|
||||
return raise_calls(root, checkout, session, new, rung, paths, questions, effects) if new else None
|
||||
|
||||
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call] | Failure:
|
||||
"""Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due."""
|
||||
cycle = archive.cycles(root)
|
||||
last = archive.last_measured(root)
|
||||
if isinstance(cycle, Failure) or isinstance(last, Failure) or not due(cycle, last):
|
||||
return cycle if isinstance(cycle, Failure) else last if isinstance(last, Failure) else []
|
||||
kept = archive.raised(root)
|
||||
if isinstance(kept, Failure):
|
||||
return kept
|
||||
print(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", flush=True)
|
||||
measured = archive.measure_archive(root, str(paths.home), kept.since)
|
||||
if isinstance(cycle, Failure):
|
||||
return cycle
|
||||
kept = state.read_state(root)
|
||||
if isinstance(kept, Failure) or not state.due(cycle, kept.measured_at):
|
||||
return kept if isinstance(kept, Failure) else []
|
||||
raised = state.raised(root)
|
||||
if isinstance(raised, Failure):
|
||||
return raised
|
||||
say(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", effects, stdout=True)
|
||||
measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
figures = totals(measured.chunks, measured.skipped)
|
||||
figures = totals(measured.chunks, measured.skipped, measured.unread)
|
||||
found = calls(figures)
|
||||
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, kept.since)):
|
||||
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
|
||||
return unwritten
|
||||
return [call for call in found if call not in kept.calls]
|
||||
return [call for call in found if call not in raised.calls]
|
||||
|
||||
|
||||
def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
listed = "".join(f"- {call}\n" for call in new)
|
||||
print(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", file=sys.stderr)
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[Call], rung: Rung, paths: Paths, questions: pathlib.Path, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's development clone, where the routing decision is changed; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
bullets = "".join(f"- {call.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():
|
||||
print("Not on a terminal: the calls are raised again at the next measurement.", file=sys.stderr)
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
|
||||
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
|
||||
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)
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls in {paths.config_clone}, the setup's development clone: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
print(f"routing figures: {unmarked.reason}", file=sys.stderr)
|
||||
if unmarked := state.mark_raised(root, new, utc(effects.now())):
|
||||
say(f"routing figures: {unmarked.reason}", effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
HELP = """Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
||||
worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md → "Shared goal")
|
||||
ranked first unless README.md voids it, choose between ways to deliver the chunk's todo.md items, or
|
||||
else the task, and never widen them. A judge then reads the transcript's end, the premises, and the
|
||||
records: the project's AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md,
|
||||
~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where they exist. It rules
|
||||
whether the chunk, the work of one PR, is finished. A chunk stays unfinished until each answer the
|
||||
human typed in it that a later chunk could need is recorded: the premises or the records hold it, or
|
||||
the transcript shows the worker writing it into the premises, AGENTS.md, docs/decisions.md, todo.md
|
||||
or a code comment. A choice the worker made that the premises or the records settle is not asked
|
||||
about. When the worker asks a question they answer, the judge quotes the answer, loop-claude prints
|
||||
it, and the worker resumes with it. A quote they do not hold word for word is dropped, and the
|
||||
question goes to the human. So does a question asked again after its answer. The fourth question
|
||||
they answer in one cycle goes to the human too, with the quote. An unfinished chunk resumes its
|
||||
session next cycle, and the worker is shown the passage the judge quoted as the work remaining. The
|
||||
next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words:
|
||||
~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the
|
||||
interrupts of every loop on the machine. The first answer counts, from either place:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
chunk stays unfinished until the answer is recorded.
|
||||
- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or
|
||||
discuss first. Once that claude exits, the judge rules on what was typed there.
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
||||
as bin/loop_claude/running_loops.py describes.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
||||
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
||||
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
|
||||
after 600 s and is stopped, leaves the worker to find the facts itself.
|
||||
|
||||
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
||||
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
|
||||
Before each worker starts, loop-claude waits until at least a quarter of the machine's memory is
|
||||
available (bin/machine_load/memory.py).
|
||||
|
||||
Each worker's claude, the session /talk opens and the subagents either launches run with a 200k
|
||||
auto-compact window (CLAUDE_CODE_AUTO_COMPACT_WINDOW, bin/loop_claude/cycle/worker.py), so each
|
||||
compacts its context at about 170k tokens.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the session /talk opens and the judge on another rung, a model at an effort. A project without an
|
||||
entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that
|
||||
question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for
|
||||
the worker and the session /talk opens; with both set, nothing is asked.
|
||||
|
||||
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
||||
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
||||
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, or when
|
||||
the judge finds in the transcript an escalation trigger that fired and the worker asked for a higher
|
||||
rung. The rules are in bin/loop_claude/routing.py and bin/model_routing/ladder.py, the choice of
|
||||
each review's rung in bin/model_routing/review_choice.py, and the prompts' wording in
|
||||
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
||||
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
||||
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
without it.
|
||||
|
||||
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/). Each call the figures make for a
|
||||
routing change, unless raised before, is an interrupt: claude, on the project's model, on the
|
||||
terminal in the setup's development clone, ~/code/claude-config, asked to put the calls to the
|
||||
human; loop-inbox lists it too. Once that claude ends, the calls are listed in
|
||||
routing-calls-raised.md beside the figures, kept in routing-state.json, and not raised again. Off a
|
||||
terminal, the calls are said on stderr, the loop goes on, and they are raised again at the next
|
||||
measurement.
|
||||
|
||||
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- README.md, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
||||
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
|
||||
- README.md holds no premises
|
||||
- the models file cannot be read or written
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
- claude cannot start for an interrupt
|
||||
- python cannot start for a reload
|
||||
- a reload cannot read the state the running script handed it, likely because the edit changed that
|
||||
handover
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
||||
mistypes a field, interrupts or quotes an answer without a question, or quotes a passage the
|
||||
transcript does not hold; it holds an elided passage when each fragment appears in order.
|
||||
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
|
||||
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
|
||||
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
||||
always retried every 10 minutes. stderr says when the next try is due.
|
||||
|
||||
Exit 2, when the human is needed to go on:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
||||
nothing typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session."""
|
||||
@@ -6,10 +6,13 @@ import pathlib
|
||||
class Paths:
|
||||
claude_code_transcripts: pathlib.Path
|
||||
claude_dir: pathlib.Path
|
||||
claude_json: pathlib.Path
|
||||
# The development clone of this setup, where a change to it is made: claude_dir holds only a release, docs/decisions.md → `deploy:`.
|
||||
config_clone: pathlib.Path
|
||||
home: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
# Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting/).
|
||||
waiting: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home: pathlib.Path) -> Paths:
|
||||
@@ -17,8 +20,9 @@ def paths_from(home: pathlib.Path) -> Paths:
|
||||
return Paths(
|
||||
claude_code_transcripts=claude / "projects",
|
||||
claude_dir=claude,
|
||||
claude_json=home / ".claude.json",
|
||||
config_clone=home / "code" / "claude-config",
|
||||
home=home,
|
||||
model_catalog=claude / "cache" / "model-catalog",
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
waiting=home / ".local" / "state" / "loop-claude",
|
||||
)
|
||||
|
||||
@@ -11,7 +11,3 @@ def checkout_root(cwd: pathlib.Path, effects: Effects) -> str | Stop:
|
||||
return Stop(1, found.reason) if isinstance(found, Failure) else found.strip()
|
||||
|
||||
|
||||
def worktrees(root: str, effects: Effects) -> list[str]:
|
||||
listing = effects.git("worktree", "list", "--porcelain", cwd=root)
|
||||
listed = [] if isinstance(listing, Failure) else [line.split(" ", 1)[1] for line in listing.splitlines() if line.startswith("worktree ")]
|
||||
return sorted({root, *listed})
|
||||
|
||||
@@ -5,11 +5,11 @@ import sys
|
||||
import typing
|
||||
|
||||
from claude_code.model_catalog import catalog_models
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.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 file_writes import replace_json
|
||||
from records.file_writes import replace_json
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -31,8 +31,8 @@ def get_or_ask_models(project_key: str, paths: Paths, env: typing.Mapping[str, s
|
||||
def get_or_ask_model(project_key: str, paths: Paths, effects: Effects) -> str | Stop:
|
||||
saved = paths.models_file
|
||||
models = read_models_file(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if isinstance(models, Failure):
|
||||
return Stop(1, models.reason)
|
||||
if kept := models.get(project_key):
|
||||
return kept
|
||||
chosen = ask_for_model(project_key, saved, paths.model_catalog, effects)
|
||||
@@ -40,24 +40,25 @@ def get_or_ask_model(project_key: str, paths: Paths, effects: Effects) -> str |
|
||||
return chosen
|
||||
# Reread: another loop may have saved its project while this one waited on the human.
|
||||
models = read_models_file(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if isinstance(models, Failure):
|
||||
return Stop(1, models.reason)
|
||||
if failure := replace_json(saved, {**models, project_key: chosen}, indent="\t", sort_keys=True):
|
||||
return Stop(1, f"could not save the model in {saved}: {failure.reason}")
|
||||
print(f"{project_key} runs on {chosen}", file=sys.stderr)
|
||||
say(f"{project_key} runs on {chosen}", effects)
|
||||
return chosen
|
||||
|
||||
|
||||
def read_models_file(saved: pathlib.Path) -> dict[str, str] | Stop:
|
||||
def read_models_file(saved: pathlib.Path) -> dict[str, str] | Failure:
|
||||
"""Each project's model, as the models file at saved maps them; none where there is no such file. loop-claude and the replay tools read it."""
|
||||
try:
|
||||
with open(saved, encoding="utf-8") as handle:
|
||||
models = json.load(handle)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except (OSError, ValueError) as failure:
|
||||
return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
|
||||
return Failure(f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
|
||||
if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()):
|
||||
return Stop(1, f"could not read {saved}: not an object mapping projects to model names")
|
||||
return Failure(f"could not read {saved}: not an object mapping projects to model names")
|
||||
return models
|
||||
|
||||
|
||||
@@ -65,20 +66,17 @@ def ask_for_model(project_key: str, saved: pathlib.Path, folder: pathlib.Path, e
|
||||
if stop := needs_terminal(f"pick {project_key}'s model, or merge {{\"{project_key}\": \"<model>\"}} into {saved}", effects.on_terminal()):
|
||||
return stop
|
||||
offered = catalog_models(folder)
|
||||
print(f"\nThe model to run {project_key} on, saved in {saved}:", file=sys.stderr)
|
||||
for number, (model_id, label) in enumerate(offered, 1):
|
||||
print(f" {number}. {label} ({model_id})", file=sys.stderr)
|
||||
if not offered:
|
||||
print(f" no model catalog cached in {folder}", file=sys.stderr)
|
||||
choices = [f" {number}. {label} ({model_id})" for number, (model_id, label) in enumerate(offered, 1)] or [f" no model catalog cached in {folder}"]
|
||||
say("\n".join([f"\nThe model to run {project_key} on, saved in {saved}:", *choices]), effects)
|
||||
while True:
|
||||
try:
|
||||
answer = effects.input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ")
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time.
|
||||
return needs_human(f"pick {project_key}'s model", "the input ended")
|
||||
picked = model_picked(answer, offered)
|
||||
if isinstance(picked, Failure):
|
||||
print(picked.reason, file=sys.stderr)
|
||||
say(picked.reason, effects)
|
||||
elif picked:
|
||||
return picked
|
||||
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
from failure import Failure
|
||||
from loop_claude.project.text_file import read_utf8
|
||||
from markdown_text import sections
|
||||
from loop_claude.stop import Stop
|
||||
from records.markdown_text import sections
|
||||
|
||||
|
||||
def read_premises(root: str) -> str | Stop:
|
||||
def read_premises(root: str) -> str | Failure:
|
||||
"""README.md's ## Goals and ## Audience in root; a Failure where README.md cannot be read or lacks either, or holds one twice or empty."""
|
||||
text = read_utf8(root, "README.md", "no premises")
|
||||
if isinstance(text, Stop):
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
found = sections(text)
|
||||
for name in ("Goals", "Audience"):
|
||||
bodies = found.get(name, [])
|
||||
if not bodies:
|
||||
return Stop(1, f"README.md has no ## {name} heading - no premises.")
|
||||
return Failure(f"README.md has no ## {name} heading - no premises.")
|
||||
if len(bodies) > 1:
|
||||
return Stop(1, f"README.md has ## {name} more than once - no premises.")
|
||||
return Failure(f"README.md has ## {name} more than once - no premises.")
|
||||
if not bodies[0]:
|
||||
return Stop(1, f"README.md has nothing under ## {name} - no premises.")
|
||||
return Failure(f"README.md has nothing under ## {name} - no premises.")
|
||||
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
from loop_claude.project.text_file import read_utf8
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
# The records the judge reads beside the README's premises: these project files, then the human's rules below.
|
||||
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
|
||||
@@ -11,7 +11,7 @@ HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards")
|
||||
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS))
|
||||
|
||||
|
||||
def read_records(root: str, claude_dir: pathlib.Path) -> str | Stop:
|
||||
def read_records(root: str, claude_dir: pathlib.Path) -> str | Failure:
|
||||
"""The project's record files, then the human's rules for every project, CLAUDE.md first, each headed by its name; a file that does not exist is left out."""
|
||||
rules = [claude_dir / HUMAN_RULES_FILE] + [rule for folder in HUMAN_RULE_DIRS for rule in sorted((claude_dir / folder).glob("*.md"))]
|
||||
sources = [(root, name, name) for name in RECORD_FILES]
|
||||
@@ -21,7 +21,7 @@ def read_records(root: str, claude_dir: pathlib.Path) -> str | Stop:
|
||||
if not pathlib.Path(folder, name).exists():
|
||||
continue
|
||||
text = read_utf8(folder, name, "the judge cannot read the records")
|
||||
if isinstance(text, Stop):
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
records.append(f"From {heading}:\n{text.strip()}")
|
||||
return "\n\n".join(records)
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.stop import Stop
|
||||
from failure import Failure
|
||||
|
||||
|
||||
def read_utf8(folder: str, name: str, consequence: str) -> str | Stop:
|
||||
def read_utf8(folder: str, name: str, consequence: str) -> str | Failure:
|
||||
"""The text of the file name in folder; a Failure naming consequence where it cannot be read or is not UTF-8."""
|
||||
try:
|
||||
return pathlib.Path(folder, name).read_text(encoding="utf-8")
|
||||
except OSError as failure:
|
||||
return Stop(1, f"{name} in {folder}: {failure.strerror} - {consequence}.")
|
||||
return Failure(f"{name} in {folder}: {failure.strerror} - {consequence}.")
|
||||
except UnicodeDecodeError as failure:
|
||||
line = failure.object.count(b"\n", 0, failure.start) + 1
|
||||
return Stop(1, f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.")
|
||||
return Failure(f"{name} in {folder} is not UTF-8 on line {line} - {consequence}.")
|
||||
|
||||
+38
-36
@@ -4,17 +4,17 @@ 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. after_unfinished raises the route after an unfinished verdict, after_ruling after 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. 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.
|
||||
- Judge. judge_rung picks the rung of the judge of a JUDGE_REPLAYED model.
|
||||
"""
|
||||
import dataclasses
|
||||
|
||||
from chunk_pick import chunk_item, LastCut, Next
|
||||
from release_plan.release_standing import chunk_item, LastCut, Next
|
||||
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
|
||||
from todo_table import Item, items, NoItemsTable
|
||||
from release_plan.todo_table import Item, items, NoItemsTable
|
||||
from model_routing.route import Route
|
||||
|
||||
UNFINISHED_PER_STEP = 2
|
||||
@@ -25,7 +25,7 @@ JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(todo: str, cut: LastCut) -> Item | Failure | None:
|
||||
"""The item chunk_pick.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
"""The item release_standing.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
found = items(todo)
|
||||
if isinstance(found, NoItemsTable):
|
||||
return None
|
||||
@@ -45,12 +45,7 @@ def first_route(project: Rung, item: Item | None) -> Route:
|
||||
|
||||
def kept(route: Route, project: Rung) -> bool:
|
||||
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
|
||||
return kept_rung(project, route) == route.rung
|
||||
|
||||
|
||||
def kept_rung(project: Rung, route: Route) -> Rung:
|
||||
"""The route's rung, raised to item_rung where it is lower or off the ladder."""
|
||||
return highest(route.rung, item_rung(project, route))
|
||||
return floor_rung(project, route) == route.rung
|
||||
|
||||
|
||||
def item_rung(project: Rung, route: Route) -> Rung:
|
||||
@@ -58,6 +53,12 @@ def item_rung(project: Rung, route: Route) -> Rung:
|
||||
return worker_rung(project, route.likelihood) if route.item else project
|
||||
|
||||
|
||||
def floor_rung(project: Rung, route: Route, likelihood_taken_in: int = 0) -> Rung:
|
||||
"""The lowest rung the worker may run on: the route's own, raised to item_rung where it is lower or off the ladder, and to the rung likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, 0 for none."""
|
||||
floor = highest(route.rung, item_rung(project, route))
|
||||
return highest(floor, worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else floor
|
||||
|
||||
|
||||
def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]:
|
||||
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
|
||||
if route.rung not in LADDER:
|
||||
@@ -73,27 +74,38 @@ def escalation_cap(project: Rung, route: Route) -> Rung:
|
||||
return climbed(item_rung(project, route), ESCALATION_CAP)
|
||||
|
||||
|
||||
def after_unfinished(project: Rung, route: Route, verdict: Unfinished) -> Route:
|
||||
"""The route the next cycle runs on after an unfinished verdict.
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StepUp:
|
||||
"""A verdict changing the route's worker line: the route the worker ran on until the verdict, and the one it runs on after. The archive names both, so the figures charge each stretch of work to its own rung."""
|
||||
before: Route
|
||||
after: Route
|
||||
|
||||
Its rung never falls. It first rises to the rung that the verdict's highest L taken in picks, where that is higher. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the mark, as loop_claude/escalation_mark.py says; a step on the count of unfinished verdicts alone keeps it. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
|
||||
|
||||
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.
|
||||
"""
|
||||
rung = raised(project, route, verdict.highest_likelihood_taken_in)
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(project, route, rung)):
|
||||
after = one_rung_up(route, rung, route.escalated_at if mark is None else mark)
|
||||
else:
|
||||
after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
|
||||
return after.taking_in(verdict.highest_escape_and_impact_taken_in)
|
||||
|
||||
|
||||
def after_ruling(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
|
||||
"""The route after the judge's interrupt or quoted answer: unchanged without an escalation. With one, raised to the rung the highest L taken in picks, and one rung up from there while below escalation_cap, moving the mark as after_unfinished does. Neither is an unfinished verdict, so the count of those restarts only with a step."""
|
||||
if project is None:
|
||||
return route
|
||||
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)
|
||||
if mark is None:
|
||||
return route
|
||||
rung = raised(project, route, verdict.highest_likelihood_taken_in)
|
||||
return one_rung_up(route, rung, mark) if below_cap(project, route, rung) else dataclasses.replace(route, rung=rung)
|
||||
return one_rung_up(route, floor, escalated_at) if escalates else dataclasses.replace(route, rung=floor)
|
||||
|
||||
|
||||
def step_up(before: Route, after: Route) -> StepUp | None:
|
||||
"""The step-up from before to after; None where the worker line holds, as when only the count of unfinished verdicts changed."""
|
||||
return StepUp(before, after) if after.worker_line() != before.worker_line() else None
|
||||
|
||||
|
||||
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
|
||||
@@ -101,16 +113,6 @@ def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
|
||||
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
|
||||
|
||||
|
||||
def below_cap(project: Rung, route: Route, rung: Rung) -> bool:
|
||||
"""Whether an escalation trigger may take the worker one rung up from rung without the human's yes: rung is below escalation_cap, two rungs above item_rung."""
|
||||
return position(rung) < position(escalation_cap(project, route))
|
||||
|
||||
|
||||
def raised(project: Rung, route: Route, likelihood_taken_in: int) -> Rung:
|
||||
"""kept_rung, raised to the rung that likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, or 0 for none."""
|
||||
return highest(kept_rung(project, route), worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else kept_rung(project, route)
|
||||
|
||||
|
||||
def judge_rung(judge_model: str, route: Route) -> Rung:
|
||||
"""The rung the route's reviewed_on E + I picks for a review, counted from the judge model's cheapest rung and never below it, whatever rung the worker stepped to.
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""The files by which a loop-claude shows loop-inbox that it runs, and the todo.md items its chunk takes.
|
||||
|
||||
A running loop holds its session's lock (session_lock.py) in Paths.waiting for its whole run. Beside the lock it keeps
|
||||
<session>.running, which holds the loop's checkout and each item its chunk takes, by ID and by its tagline on the default
|
||||
branch as last fetched. The items are the one the chunk was routed on, then those the judge's latest ruling found the
|
||||
worker took in, each listed once. loop-inbox lists a loop, and its question (waiting/), 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
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from loop_claude.session_lock import ended, held, running
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import items
|
||||
from records.file_writes import replace_json
|
||||
|
||||
# How many times, 0.1 s apart, a loop tries to take its lock: loop-inbox takes it for a moment each time it checks whether the loop has ended.
|
||||
LOCK_TRIES = 10
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Taken:
|
||||
"""A todo.md item a chunk takes."""
|
||||
id: int
|
||||
# The item's tagline without its bold marks; empty where the default branch's todo.md can't be read or holds no such item.
|
||||
tagline: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class RunningLoop:
|
||||
session: str
|
||||
# The checkout the loop runs in.
|
||||
root: str
|
||||
# The routed item first; empty until the chunk has an item.
|
||||
items: tuple[Taken, ...]
|
||||
|
||||
|
||||
Show = typing.Callable[[tuple[Taken, ...]], None]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listed:
|
||||
"""How a running loop shows itself in loop-inbox."""
|
||||
# Where the loop keeps its questions: Paths.waiting where it holds its session's lock. Where another loop on the session holds the lock, a folder of its own that loop-inbox doesn't read, so this loop never touches the other's questions.
|
||||
folder: pathlib.Path
|
||||
show: Show
|
||||
|
||||
|
||||
def running_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.running"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def shown_running(folder: pathlib.Path, session: str, root: str, effects: Effects) -> typing.Iterator[Listed]:
|
||||
"""Lists the loop in loop-inbox as running while the with block runs, at first with no item. A failure only warns: the loop runs unlisted, and its questions are answered on its terminal."""
|
||||
with contextlib.ExitStack() as stack:
|
||||
if unlocked := locked_soon(stack, folder, session, effects):
|
||||
say(f"loop-inbox cannot list this loop or its questions: {unlocked.reason}", effects)
|
||||
unlisted = folder / "unlisted" / effects.new_id()
|
||||
try:
|
||||
yield Listed(unlisted, lambda items: None)
|
||||
finally:
|
||||
shutil.rmtree(unlisted, ignore_errors=True)
|
||||
return
|
||||
def show(items: tuple[Taken, ...]) -> None:
|
||||
if unshown := replace_json(running_file(folder, session), {"root": root, "items": [dataclasses.asdict(item) for item in items]}):
|
||||
say(f"loop-inbox cannot list this loop's items: {unshown.reason}", effects)
|
||||
show(())
|
||||
try:
|
||||
yield Listed(folder, show)
|
||||
finally:
|
||||
# A file this fails to remove stays until loop-inbox removes it, once the lock is let go.
|
||||
with contextlib.suppress(OSError):
|
||||
running_file(folder, session).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def locked_soon(stack: contextlib.ExitStack, folder: pathlib.Path, session: str, effects: Effects) -> Failure | None:
|
||||
"""Holds the session's lock until stack closes, trying LOCK_TRIES times; returns None once it holds the lock, else the last try's failure."""
|
||||
for _ in range(LOCK_TRIES):
|
||||
attempt = contextlib.ExitStack()
|
||||
unlocked = attempt.enter_context(held(folder, session))
|
||||
if not unlocked:
|
||||
stack.enter_context(attempt)
|
||||
return None
|
||||
attempt.close()
|
||||
effects.sleep(0.1)
|
||||
return unlocked
|
||||
|
||||
|
||||
def running_loops(folder: pathlib.Path) -> list[RunningLoop]:
|
||||
"""The loops that hold their lock, by checkout. A file that cannot be read or parsed is left out."""
|
||||
try:
|
||||
paths = list(folder.glob("*.running"))
|
||||
except OSError:
|
||||
return []
|
||||
loops = [loop for path in paths if (loop := read_running(path)) and running(folder, loop.session)]
|
||||
return sorted(loops, key=lambda loop: loop.root)
|
||||
|
||||
|
||||
def drop_ended_loops(folder: pathlib.Path) -> None:
|
||||
"""Removes each running file whose session's lock no loop holds: a loop that was killed leaves it behind. A file it cannot remove stays on disk, and running_loops leaves it out all the same."""
|
||||
for session in ended(folder, "*.running"):
|
||||
with contextlib.suppress(OSError):
|
||||
running_file(folder, session).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_running(path: pathlib.Path) -> RunningLoop | None:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
match data:
|
||||
case {"root": str(root), "items": list(items)} if all(is_item(item) for item in items):
|
||||
return RunningLoop(path.name.removesuffix(".running"), root, tuple(Taken(item["id"], item["tagline"]) for item in items))
|
||||
return None
|
||||
|
||||
|
||||
def is_item(item: object) -> bool:
|
||||
match item:
|
||||
# type(), not isinstance(): JSON true is no ID.
|
||||
case {"id": id_, "tagline": str()} if type(id_) is int:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def taken_items(todo: str | Failure, routed: int, taken_in: tuple[int, ...]) -> tuple[Taken, ...]:
|
||||
"""The items a chunk takes, as the module docstring says, with their taglines from todo, the default branch's todo.md. routed, the item the chunk was routed on, is 0 for none."""
|
||||
found = items(todo) if isinstance(todo, str) else []
|
||||
taglines = {item.id: item.tagline.removeprefix("**").removesuffix("**") for item in found} if isinstance(found, list) else {}
|
||||
ids = dict.fromkeys(([routed] if routed else []) + list(taken_in))
|
||||
return tuple(Taken(id_, taglines.get(id_, "")) for id_ in ids)
|
||||
@@ -0,0 +1,66 @@
|
||||
"""The lock by which loop-inbox tells whether a loop-claude still runs.
|
||||
|
||||
A loop holds <session>.lock for its whole run (running_loops.py), with flock, which the kernel frees however the loop
|
||||
ends, killed included. The lock file stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why.
|
||||
"""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from records.file_writes import make_private
|
||||
|
||||
|
||||
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.lock"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def held(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]:
|
||||
"""Holds the session's lock while the with block runs, or yields a Failure where it cannot. loop-inbox takes the lock for a moment through ended, on each session whose files are still on disk, so a loop may find it held."""
|
||||
path = lock_file(folder, session)
|
||||
try:
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot make {folder}: {failure.strerror}")
|
||||
return
|
||||
try:
|
||||
handle = open(path, "a")
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot open {path}: {failure.strerror}")
|
||||
return
|
||||
with handle:
|
||||
try:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
yield Failure(f"another process holds {path}")
|
||||
return
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot lock {path}: {failure.strerror}")
|
||||
return
|
||||
yield None
|
||||
|
||||
|
||||
def ended(folder: pathlib.Path, pattern: str) -> typing.Iterator[str]:
|
||||
"""Each session with a file in folder that matches pattern, such as "*.json", and whose lock no loop holds. It yields each while holding that lock, so a loop that starts meanwhile keeps its files."""
|
||||
try:
|
||||
sessions = {path.stem for path in folder.glob(pattern)}
|
||||
except OSError:
|
||||
return
|
||||
for session in sessions:
|
||||
with held(folder, session) as unlocked:
|
||||
if not unlocked:
|
||||
yield session
|
||||
|
||||
|
||||
def running(folder: pathlib.Path, session: str) -> bool:
|
||||
"""Whether a loop holds the session's lock; False also where the lock file cannot be opened or locked."""
|
||||
try:
|
||||
with open(lock_file(folder, session)) as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
return False
|
||||
@@ -18,6 +18,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
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
TASK = "Do the next chunk."
|
||||
@@ -36,7 +39,9 @@ argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role, "ctrl_c_ignored": signal.getsignal(signal.SIGINT) == signal.SIG_IGN, "sandboxed": os.environ.get("CLAUDE_CODE_SANDBOXED")}}
|
||||
# The items each loop lists in loop-inbox as this claude starts.
|
||||
call["running"] = [json.loads(path.read_text())["items"] for path in sorted((pathlib.Path.home() / ".local" / "state" / "loop-claude").glob("*.running"))]
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
@@ -97,8 +102,12 @@ if role == "worker":
|
||||
elif role == "judge":
|
||||
print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}}))
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
elif "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
else:
|
||||
if step.get("ctrl_c"):
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. kill returns once the signal is pending in loop-claude, before this process exits and loop-claude stops waiting for it.
|
||||
os.kill(os.getppid(), signal.SIGINT)
|
||||
if "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
if step.get("unreadable"):
|
||||
transcript().chmod(0)
|
||||
if step.get("vanish"):
|
||||
@@ -138,8 +147,8 @@ def worker(**step):
|
||||
return {"role": "worker", **step}
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
|
||||
verdict = {"answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", items_taken_in=(), highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=0, escalation="", release_ready=False, **step):
|
||||
verdict = {"items_taken_in": list(items_taken_in), "answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -157,8 +166,11 @@ class Run:
|
||||
code: int
|
||||
sleeps: list
|
||||
starts: list
|
||||
# stderr and stdout are without the local time that opens each message loop-claude prints; raw_stderr and raw_stdout keep it.
|
||||
stderr: str
|
||||
stdout: str
|
||||
raw_stderr: str
|
||||
raw_stdout: str
|
||||
|
||||
def roles(self):
|
||||
return [call["role"] for call in self.calls]
|
||||
@@ -228,8 +240,10 @@ class Checkout:
|
||||
code=code,
|
||||
sleeps=[event["sleep"] for event in started if "sleep" in event],
|
||||
starts=[event["argv"] for event in started if "argv" in event],
|
||||
stderr=stderr,
|
||||
stdout=stdout,
|
||||
stderr=unstamped(stderr),
|
||||
stdout=unstamped(stdout),
|
||||
raw_stderr=stderr,
|
||||
raw_stdout=stdout,
|
||||
)
|
||||
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing, typed_early):
|
||||
@@ -247,7 +261,7 @@ class Checkout:
|
||||
os.write(controller, typed.encode())
|
||||
output, deadline = b"", time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if select.select([controller], [], [], 1)[0]:
|
||||
if select.select([controller], [], [], 0.05)[0]:
|
||||
try:
|
||||
chunk = os.read(controller, 4096)
|
||||
except OSError:
|
||||
@@ -295,6 +309,13 @@ class Checkout:
|
||||
return outcomes
|
||||
|
||||
|
||||
STAMP = r"\d{4}-\d\d-\d\d \d\d:\d\d:\d\d"
|
||||
|
||||
|
||||
def unstamped(text):
|
||||
return re.sub(rf"(?m)^{STAMP} ", "", text)
|
||||
|
||||
|
||||
def argument(call, flag):
|
||||
return call["argv"][call["argv"].index(flag) + 1] if flag in call["argv"] else None
|
||||
|
||||
@@ -311,7 +332,7 @@ class Premises(unittest.TestCase):
|
||||
outside.mkdir()
|
||||
run = checkout.run([], cwd=outside)
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("not a git repository", run.stderr)
|
||||
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} .*not a git repository")
|
||||
readmes = {
|
||||
None: "README.md in {root}: No such file or directory - no premises.",
|
||||
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.",
|
||||
@@ -396,6 +417,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertNotIn("landed-it", run.calls[5]["stdin"])
|
||||
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
|
||||
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
|
||||
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
|
||||
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
|
||||
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
@@ -452,6 +474,16 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("item 6, L 4, E + I 5", prompt)
|
||||
self.assertTrue((checkout.home / "code" / "proj-item-6").is_dir())
|
||||
|
||||
def test_lists_itself_in_loop_inbox_with_its_routed_item_then_those_the_judge_finds_taken_in_until_the_chunk_finishes(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([worker(), judge(items_taken_in=[7, 4]), worker(), judge(finished=True), worker()])
|
||||
self.assertEqual(run.code, 130)
|
||||
routed, taken_in = {"id": 4, "tagline": "Do it."}, {"id": 7, "tagline": ""}
|
||||
self.assertEqual([call["running"] for call in run.calls], [[[routed]], [[routed]], [[routed, taken_in]], [[routed, taken_in]], [[routed]], [[routed]]])
|
||||
self.assertEqual(list((checkout.home / ".local" / "state" / "loop-claude").glob("*.running")), [])
|
||||
|
||||
def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
@@ -584,7 +616,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker"] * 5 + ["judge"] * 2 + ["worker"])
|
||||
self.assertEqual([round(seconds, -1) for seconds in run.sleeps], [60, 60, 3720, 60, 600])
|
||||
self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {datetime.datetime.fromtimestamp(resets_at + 120, datetime.timezone.utc):%Y-%m-%d %H:%M} UTC\n", run.stderr)
|
||||
self.assertIn(f"the worker hit a usage limit (You've hit your session limit); retrying at {datetime.datetime.fromtimestamp(resets_at + 120, datetime.timezone.utc):%Y-%m-%d %H:%M:%S}\n", run.stderr)
|
||||
self.assertIn("the judge hit a usage limit (You've hit your session limit); retrying at ", run.stderr)
|
||||
|
||||
def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self):
|
||||
@@ -647,6 +679,36 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
|
||||
self.assertIn("claude left no transcript for session", run.stderr)
|
||||
|
||||
def test_exits_2_after_six_unfinished_verdicts_running_and_a_rerun_gets_six_more(self):
|
||||
checkout = Checkout(self)
|
||||
six = [step for _ in range(6) for step in (worker(), judge())]
|
||||
run = checkout.run(six + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"] * 6))
|
||||
self.assertIn("the judge ruled it unfinished 6 cycles running", run.stderr.strip().splitlines()[-1])
|
||||
self.assertIn("rerun loop-claude to give it 6 more cycles", run.stderr.strip().splitlines()[-1])
|
||||
stops = [outcome for outcome in checkout.archived().values() if "Stopped: " in outcome]
|
||||
self.assertEqual(len(stops), 1)
|
||||
self.assertIn(f"\n\nWorker: {OFF_LADDER}\n", stops[0])
|
||||
run = checkout.run(six[:-2] + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 6))
|
||||
|
||||
def test_archives_the_stop_on_the_route_the_sixth_verdict_stepped_to_and_a_rerun_resumes_there(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
|
||||
self.assertEqual(run.code, 2)
|
||||
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
|
||||
self.assertEqual(len([outcome for outcome in checkout.archived().values() if stepped in outcome]), 1)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-opus-5-5", "xhigh")])
|
||||
|
||||
def test_five_unfinished_verdicts_and_a_finished_one_do_not_add_up_to_six(self):
|
||||
checkout = Checkout(self)
|
||||
five = [step for _ in range(5) for step in (worker(), judge())]
|
||||
run = checkout.run(five + [worker(), judge(finished=True)] + five + [worker()])
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
|
||||
|
||||
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
@@ -661,6 +723,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} transcript: ")
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
run = checkout.run(steps, terminal_input="", stdout_on_terminal=False)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
@@ -682,12 +745,39 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertNotIn("stray", run.calls[3]["stdin"])
|
||||
|
||||
def test_resumes_the_worker_headless_with_the_answer_typed_in_loop_inbox(self):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
def answered_in_inbox():
|
||||
[ask] = waiting(folder)
|
||||
send(folder, ask, Typed("B"))
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
|
||||
self.assertIn("Answer (/talk opens claude, Enter stops the loop): \nAnswered in loop-inbox: B\n", run.stderr)
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertEqual([path for path in folder.iterdir() if path.suffix != ".lock"], [])
|
||||
|
||||
def test_a_second_loop_on_the_session_runs_unlisted_and_keeps_its_question_out_of_the_first_loops_folder(self):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
session = argument(checkout.run(asked).calls[0], "--session-id")
|
||||
# The first loop on the session, still running.
|
||||
self.enterContext(session_lock.held(folder, session))
|
||||
asks = []
|
||||
run = checkout.run(asked, terminal_input="\n", before_typing=("Answer (", lambda: asks.extend(folder.glob("*.json"))))
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(folder, session)}", run.stderr)
|
||||
self.assertEqual((asks, run.calls[0]["running"]), ([], []))
|
||||
self.assertFalse((folder / "unlisted").exists() and any((folder / "unlisted").iterdir()))
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
|
||||
checkout.git("worktree", "add", "--quiet", str(checkout.home / "code" / "proj-wt"))
|
||||
checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}}))
|
||||
checkout.claude_json().chmod(0o644)
|
||||
claude_json = json.dumps({"projects": {str(checkout.root): {"kept": True}}})
|
||||
checkout.claude_json().write_text(claude_json)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
@@ -699,12 +789,8 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(argument(run.calls[2], "--model"), "worker-model")
|
||||
self.assertNotIn("-p", handed)
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
trusted = json.loads(checkout.claude_json().read_text())
|
||||
self.assertEqual(trusted["other"], 1)
|
||||
self.assertEqual(trusted["projects"][str(checkout.root)], {"hasTrustDialogAccepted": True, "kept": True})
|
||||
self.assertEqual(trusted["projects"][str(checkout.home / "code" / "proj-wt")], {"hasTrustDialogAccepted": True})
|
||||
self.assertEqual(stat.S_IMODE(checkout.claude_json().stat().st_mode), 0o644)
|
||||
self.assertIn(f"trusted for the interrupt: {checkout.root}, {checkout.home / 'code' / 'proj-wt'}\n", run.stderr)
|
||||
self.assertEqual(run.calls[2]["sandboxed"], "1")
|
||||
self.assertEqual(checkout.claude_json().read_text(), claude_json)
|
||||
|
||||
for transcript in checkout.transcripts():
|
||||
transcript.unlink()
|
||||
@@ -716,46 +802,13 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
def test_leaves_ctrl_c_to_the_claude_open_for_talk(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
root = json.dumps(str(checkout.root))
|
||||
shapes = {
|
||||
None: "No such file or directory",
|
||||
"{": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)",
|
||||
"[]": 'not an object whose "projects" is an object',
|
||||
'{"projects": []}': 'not an object whose "projects" is an object',
|
||||
f'{{"projects": {{{root}: 1}}}}': f"projects[{root}] is not an object",
|
||||
}
|
||||
for text, said in shapes.items():
|
||||
with self.subTest(said=said):
|
||||
checkout.claude_json().unlink(missing_ok=True)
|
||||
if text is not None:
|
||||
checkout.claude_json().write_text(text)
|
||||
run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text)
|
||||
|
||||
trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}})
|
||||
checkout.claude_json().write_text(trusted)
|
||||
run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertNotIn(str(checkout.claude_json()), run.stderr)
|
||||
self.assertNotIn("trusted for the interrupt", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), trusted)
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_says_why_the_trust_file_cannot_be_written(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.claude_json().write_text("{}")
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
checkout.run(asked[:2])
|
||||
checkout.home.chmod(0o500)
|
||||
self.addCleanup(checkout.home.chmod, 0o700)
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), "{}")
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, interrupt(type="B", ctrl_c=True), judge(evidence="B")], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "interrupt", "judge", "worker"]))
|
||||
self.assertFalse(run.calls[2]["ctrl_c_ignored"])
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
|
||||
def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self):
|
||||
@@ -861,14 +914,14 @@ class Reload(unittest.TestCase):
|
||||
worker(append=["loop-claude", "\ndef\n"]), judge(),
|
||||
worker(replace=["loop-claude", "\ndef\n", "\n# edited\n"]), judge(),
|
||||
worker(append=["loop_claude/nested/edited.py", "# edited\n"]), judge(),
|
||||
worker(append=["file_writes.py", "# edited\n"]), judge(),
|
||||
worker(append=["records/file_writes.py", "# edited\n"]), judge(),
|
||||
worker(),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
|
||||
self.assertIn("keeping the running script", run.stderr)
|
||||
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE} for cycle in (2, 3, 4)])
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "items_taken_in": []} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
|
||||
+563
-246
File diff suppressed because it is too large
Load Diff
@@ -2,17 +2,29 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TakenIn:
|
||||
"""What the judge read in the transcript about the todo.md items the worker took into the chunk, the item the chunk was routed on included."""
|
||||
# Their IDs; loop-inbox lists them.
|
||||
items: tuple[int, ...] = ()
|
||||
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
|
||||
highest_likelihood: int = 0
|
||||
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's judge and reviewers.
|
||||
highest_escape_and_impact: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
||||
escalation: str = ""
|
||||
# The highest L the judge saw the worker take into the chunk, 0 for none: an escalation steps up from the rung that L picks.
|
||||
highest_likelihood_taken_in: int = 0
|
||||
taken_in: TakenIn = TakenIn()
|
||||
release_ready: bool = False
|
||||
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
|
||||
entries_read: int | None = None
|
||||
# What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -23,26 +35,28 @@ class QuotedAnswer:
|
||||
answer: str
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
highest_likelihood_taken_in: int = 0
|
||||
taken_in: TakenIn = TakenIn()
|
||||
entries_read: int | None = None
|
||||
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finished:
|
||||
evidence: str
|
||||
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unfinished:
|
||||
evidence: str
|
||||
# As on Interrupt; the worker also rises to the rung that L picks.
|
||||
highest_likelihood_taken_in: int = 0
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
# The highest E + I the judge saw the worker take into the chunk, 0 for none.
|
||||
highest_escape_and_impact_taken_in: int = 0
|
||||
# As on Interrupt.
|
||||
taken_in: TakenIn = TakenIn()
|
||||
entries_read: int | None = None
|
||||
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
|
||||
|
||||
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
|
||||
<session> is the worker's session id, so a loop lists one question at a time. The loop removes the ask once the question
|
||||
is answered or the loop stops. loop-inbox lists an ask only while the loop holds the session's lock (running_loops.py),
|
||||
and removes one whose lock is free. loop-inbox answers by replacing <session>.answer, which names the
|
||||
ask's id. So an answer meant for an earlier question, or sent as the loop took an answer on its terminal,
|
||||
never answers a later one.
|
||||
|
||||
Its modules import only those before them: ask, answers, listing, talk.
|
||||
"""
|
||||
@@ -0,0 +1,68 @@
|
||||
"""What loop-inbox sends to a waiting ask, in <session>.answer, and how the loop reads it.
|
||||
|
||||
The message types stay here beside `received`, which reads them back, so that a change to one meets the other."""
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
from loop_claude.waiting.ask import Ask, tagged
|
||||
from failure import Failure
|
||||
from records.file_writes import replace_json
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Typed:
|
||||
text: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeOpening:
|
||||
"""loop-inbox, whose process is pid, asks the loop to make way for the claude it opens for /talk."""
|
||||
pid: int
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeEnded:
|
||||
"""The claude loop-inbox opened for the ask has ended."""
|
||||
|
||||
|
||||
# What answers a waiting ask.
|
||||
Answer = Typed | ClaudeOpening
|
||||
Message = Answer | ClaudeEnded
|
||||
|
||||
|
||||
def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.answer"
|
||||
|
||||
|
||||
def send(folder: pathlib.Path, ask: Ask, message: Message) -> Failure | None:
|
||||
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **tagged(message)})
|
||||
|
||||
|
||||
def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
|
||||
"""The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session."""
|
||||
message = received(folder, ask)
|
||||
return message if isinstance(message, Typed | ClaudeOpening) else None
|
||||
|
||||
|
||||
def claude_ended(folder: pathlib.Path, ask: Ask) -> bool:
|
||||
"""Whether loop-inbox said the claude it opened for this ask has ended."""
|
||||
return isinstance(received(folder, ask), ClaudeEnded)
|
||||
|
||||
|
||||
def received(folder: pathlib.Path, ask: Ask) -> Message | None:
|
||||
try:
|
||||
data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(data, dict) or data.get("ask") != ask.id:
|
||||
return None
|
||||
match data:
|
||||
case {"kind": "Typed", "text": str(text)}:
|
||||
return Typed(text)
|
||||
# alive is always True for a pid of 0 or below, which names a process group or every process, so the loop would wait for claude forever.
|
||||
case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0:
|
||||
return ClaudeOpening(pid)
|
||||
case {"kind": "ClaudeEnded"}:
|
||||
return ClaudeEnded()
|
||||
return None
|
||||
@@ -0,0 +1,79 @@
|
||||
"""An interrupt's question as loop-inbox lists it, and how its file is read; `tagged` writes the kind that `ask_state` reads.
|
||||
|
||||
The ask's state says whether the loop waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox."""
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from records.utc_stamp import seconds, utc
|
||||
|
||||
if typing.TYPE_CHECKING:
|
||||
from _typeshed import DataclassInstance
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Asking:
|
||||
"""The ask waits for an answer; talk opens the worker's claude session for /talk."""
|
||||
talk: ClaudeCommand
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class OpenOnTerminal:
|
||||
"""claude is open for the ask on the loop's own terminal; the loop takes no answer from loop-inbox."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class OpenInInbox:
|
||||
"""claude is open for the ask in the loop-inbox whose process is pid."""
|
||||
pid: int
|
||||
|
||||
|
||||
AskState = Asking | OpenOnTerminal | OpenInInbox
|
||||
|
||||
|
||||
def tagged(value: "DataclassInstance") -> dict[str, object]:
|
||||
"""value's fields, with its kind, which ask_state and answers.received read it back by."""
|
||||
return dataclasses.asdict(value) | {"kind": type(value).__name__}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ask:
|
||||
"""An interrupt's question, as loop-inbox lists it."""
|
||||
id: str
|
||||
session: str
|
||||
# The checkout the loop runs in.
|
||||
root: str
|
||||
question: str
|
||||
# When the loop asked, in seconds since the epoch; its file holds it as an ISO UTC datetime, as ask_fields writes it.
|
||||
asked: float
|
||||
state: AskState
|
||||
|
||||
|
||||
def ask_fields(ask: Ask) -> dict[str, object]:
|
||||
"""ask as its file holds it, which read_ask reads back to the second."""
|
||||
return dataclasses.asdict(ask) | {"asked": utc(ask.asked), "state": tagged(ask.state)}
|
||||
|
||||
|
||||
def read_ask(path: pathlib.Path) -> Ask | None:
|
||||
"""The ask in path. None where a field has the wrong type, where utc_stamp.seconds cannot read asked, or where the ask names another session than path does."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
ask = Ask(**{**data, "asked": seconds(data["asked"]), "state": ask_state(data["state"])})
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return None
|
||||
texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question))
|
||||
return ask if texts and ask.session == path.stem else None
|
||||
|
||||
|
||||
def ask_state(data: object) -> AskState:
|
||||
match data:
|
||||
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}} if all(isinstance(text, str) for text in [*args, *env.values()]):
|
||||
return Asking(ClaudeCommand(args, cwd, env))
|
||||
case {"kind": "OpenOnTerminal"}:
|
||||
return OpenOnTerminal()
|
||||
case {"kind": "OpenInInbox", "pid": int(pid)}:
|
||||
return OpenInInbox(pid)
|
||||
raise ValueError(f"not an ask's state: {data!r}")
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""The ask's file in the folder loop-inbox reads, and which asks it lists."""
|
||||
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 failure import Failure
|
||||
from records.file_writes import make_private, replace_json
|
||||
|
||||
|
||||
def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
return folder / f"{session}.json"
|
||||
|
||||
|
||||
def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
|
||||
try:
|
||||
make_private(folder)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot make {folder}: {failure.strerror}")
|
||||
return replace_json(ask_file(folder, ask.session), ask_fields(ask))
|
||||
|
||||
|
||||
def withdraw(folder: pathlib.Path, session: str) -> Failure | None:
|
||||
"""Removes the session's ask and any answer to it."""
|
||||
for path in (ask_file(folder, session), answer_file(folder, session)):
|
||||
try:
|
||||
path.unlink(missing_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot remove {path}: {failure.strerror}")
|
||||
return None
|
||||
|
||||
|
||||
def shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
|
||||
"""Lists ask in loop-inbox, in its state. A failure only warns: the question is still answered on the loop's terminal."""
|
||||
if unshown := publish(folder, ask):
|
||||
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
|
||||
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to list it only warns: the question is still answered on the loop's terminal.
|
||||
|
||||
listed doesn't take the session's lock, which loop-inbox needs held to list the ask. Pass the folder running_loops.shown_running yields: shown_running holds the lock for the loop's whole run.
|
||||
"""
|
||||
shown(folder, ask, effects)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
# An ask this fails to remove is left to loop-inbox, which stops listing it once the lock is let go, and removes it.
|
||||
withdraw(folder, ask.session)
|
||||
|
||||
|
||||
def waiting(folder: pathlib.Path) -> list[Ask]:
|
||||
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
|
||||
try:
|
||||
paths = sorted(folder.glob("*.json"))
|
||||
except OSError:
|
||||
return []
|
||||
asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)]
|
||||
return sorted(asks, key=lambda ask: ask.asked)
|
||||
|
||||
|
||||
def drop_ended(folder: pathlib.Path) -> None:
|
||||
"""Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. An ask it cannot remove stays on disk, and waiting leaves it out all the same."""
|
||||
for session in ended(folder, "*.json"):
|
||||
withdraw(folder, session)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
|
||||
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
|
||||
2. The loop stops reading its terminal, and its make_way lists the ask as OpenInInbox with that pid. claim_talk
|
||||
returns True once it reads that, and loop-inbox opens claude.
|
||||
3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with answers.claude_ended. The loop also stops waiting
|
||||
if loop-inbox's process is gone.
|
||||
"""
|
||||
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 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.
|
||||
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
|
||||
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
|
||||
TALK = "/talk"
|
||||
|
||||
|
||||
def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure:
|
||||
"""loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS. False where the ask is gone or replaced, its state is no longer Asking (answered first, claude open on the loop's own terminal, or the loop made way for another loop-inbox), or the loop didn't make way in time."""
|
||||
if unsent := send(folder, ask, ClaudeOpening(pid)):
|
||||
return unsent
|
||||
deadline = now() + MAKE_WAY_SECONDS
|
||||
while now() < deadline:
|
||||
current = read_ask(ask_file(folder, ask.session))
|
||||
if current is None or current.id != ask.id:
|
||||
return False
|
||||
if current.state == OpenInInbox(pid):
|
||||
return True
|
||||
if not isinstance(current.state, Asking):
|
||||
return False
|
||||
sleep(0.1)
|
||||
# Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait.
|
||||
send(folder, ask, ClaudeEnded())
|
||||
return False
|
||||
|
||||
|
||||
def make_way(folder: pathlib.Path, ask: Ask, pid: int, effects: Effects) -> None:
|
||||
"""The loop's side of /talk from loop-inbox, once it has stopped reading its terminal: lists ask as having claude open in the loop-inbox whose process is pid, which claim_talk waits for. A failure only warns: claim_talk then gives up, and the loop stops."""
|
||||
shown(folder, dataclasses.replace(ask, state=OpenInInbox(pid)), effects)
|
||||
@@ -0,0 +1,179 @@
|
||||
"""What loop-inbox shows, and what each key does there: the core that main.py's curses screen runs.
|
||||
|
||||
How it shows the loops and a question was picked on 2026-10-28 by a bench of three readers seated as the README's
|
||||
audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it: a block per
|
||||
loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone doesn't stop the loop.
|
||||
A second bench, on 2026-10-29, picked the running loops' section: below the waiting loops, a line per loop with its
|
||||
checkout and its number in the list above where it waits for an answer, then a line per item its chunk takes, with its ID and tagline.
|
||||
"""
|
||||
import dataclasses
|
||||
import textwrap
|
||||
import typing
|
||||
|
||||
from loop_claude.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.running_loops import RunningLoop, Taken
|
||||
from loop_claude.waiting.talk import TALK
|
||||
|
||||
ENTER = "enter"
|
||||
BACKSPACE = "backspace"
|
||||
ESCAPE = "escape"
|
||||
# Lines of a question the list shows; the answer screen shows as much as fits.
|
||||
SHOWN_LINES = 2
|
||||
QUIT = "q"
|
||||
ANSWER_PROMPT = f"Answer ({TALK} opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting):"
|
||||
INDENT = " "
|
||||
ELLIPSIS = "…"
|
||||
NARROWEST = 20
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listing:
|
||||
"""The waiting and running loops as they were when the human began typing a number, so a loop's number doesn't change while they type it."""
|
||||
shown: tuple[Ask, ...] = ()
|
||||
typed: str = ""
|
||||
note: str = ""
|
||||
running: tuple[RunningLoop, ...] = ()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Answering:
|
||||
ask: Ask
|
||||
typed: str = ""
|
||||
|
||||
|
||||
Screen = Listing | Answering
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Send:
|
||||
ask: Ask
|
||||
text: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Open:
|
||||
"""Opens the worker's claude session for /talk."""
|
||||
ask: Ask
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Quit:
|
||||
pass
|
||||
|
||||
|
||||
def pressed(screen: Screen, key: str) -> Screen | Send | Open | Quit:
|
||||
"""What follows key, which is ENTER, BACKSPACE, ESCAPE or one character typed."""
|
||||
match screen:
|
||||
case Listing(shown, typed):
|
||||
if key == QUIT and not typed:
|
||||
return Quit()
|
||||
if key == ENTER:
|
||||
return picked(shown, typed)
|
||||
if key == BACKSPACE:
|
||||
return dataclasses.replace(screen, typed=typed[:-1], note="")
|
||||
# isdigit would also take "²", which int() rejects.
|
||||
return dataclasses.replace(screen, typed=typed + key, note="") if key.isdecimal() else screen
|
||||
case Answering(ask, typed):
|
||||
if key == ESCAPE or (key == ENTER and not typed.strip()):
|
||||
return Listing()
|
||||
if key == ENTER:
|
||||
return Open(ask) if typed.strip() == TALK else Send(ask, typed.strip())
|
||||
if key == BACKSPACE:
|
||||
return Answering(ask, typed[:-1])
|
||||
return Answering(ask, typed + key) if len(key) == 1 and key.isprintable() else screen
|
||||
case _:
|
||||
typing.assert_never(screen)
|
||||
|
||||
|
||||
def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering:
|
||||
if not typed:
|
||||
return Listing()
|
||||
number = int(typed)
|
||||
if not 1 <= number <= len(shown):
|
||||
return Listing(note=f"No loop has the number {number}.")
|
||||
ask = shown[number - 1]
|
||||
if not isinstance(ask.state, Asking):
|
||||
return Listing(note=f"{ask.root}: claude is open {where_open(ask.state)}; answer there.")
|
||||
return Answering(ask)
|
||||
|
||||
|
||||
def where_open(state: OpenOnTerminal | OpenInInbox) -> str:
|
||||
return "in loop-inbox" if isinstance(state, OpenInInbox) else "on its terminal"
|
||||
|
||||
|
||||
def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]:
|
||||
"""The list, in lines of at most width characters, and its foot: the note, what the keys do, and the prompt for a number."""
|
||||
count = len(screen.shown)
|
||||
head = "No loop waits for you." if not count else "1 loop waits for you." if count == 1 else f"{count} loops wait for you, oldest first."
|
||||
lines = [*wrapped(head, width), ""]
|
||||
for number, ask in enumerate(screen.shown, 1):
|
||||
state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}"
|
||||
lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width)
|
||||
lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES)
|
||||
lines.append("")
|
||||
lines += running_lines(screen.running, screen.shown, width)
|
||||
ask_for = "Type a number and Enter to answer that loop; " if count else ""
|
||||
return lines, [*wrapped(screen.note, width), *wrapped(f"{ask_for}{QUIT} quits loop-inbox, and the loops keep waiting.", width), *typed_after(">", screen.typed, width)]
|
||||
|
||||
|
||||
def running_lines(running: tuple[RunningLoop, ...], shown: tuple[Ask, ...], width: int) -> list[str]:
|
||||
"""Each running loop's checkout, with its number in the waiting list where it waits for an answer, and a line per item its chunk takes."""
|
||||
if not running:
|
||||
return ["No loop runs."]
|
||||
numbers = {ask.session: number for number, ask in enumerate(shown, 1)}
|
||||
lines = wrapped(f"Running: {len(running)} loop{'s' if len(running) > 1 else ''}", width)
|
||||
for loop in running:
|
||||
waits_as = f", waiting as [{numbers[loop.session]}]" if loop.session in numbers else ""
|
||||
lines += wrapped(f"- {loop.root}{waits_as}", width)
|
||||
for item in loop.items or (None,):
|
||||
lines += cut(wrapped(item_line(item), width - len(INDENT) - len(ELLIPSIS)), 1)
|
||||
return lines
|
||||
|
||||
|
||||
def item_line(item: Taken | None) -> str:
|
||||
if item is None:
|
||||
return "no todo.md item yet"
|
||||
return f"item {item.id}: {item.tagline}" if item.tagline else f"item {item.id}"
|
||||
|
||||
|
||||
def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]:
|
||||
"""The question, in lines of at most width characters, and its foot, the prompt for the answer."""
|
||||
ask = screen.ask
|
||||
head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):"
|
||||
return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width)
|
||||
|
||||
|
||||
def fitted(lines: list[str], foot: list[str], height: int) -> list[str]:
|
||||
"""lines, then foot, cut to height: lines lose their end first, and the cut is marked with an ellipsis."""
|
||||
if len(lines) + len(foot) <= height:
|
||||
return [*lines, *foot]
|
||||
return [*lines[: max(height - len(foot) - 1, 0)], ELLIPSIS, *foot][-height:]
|
||||
|
||||
|
||||
def wrapped(text: str, width: int) -> list[str]:
|
||||
return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, NARROWEST)) or [""]]
|
||||
|
||||
|
||||
def typed_after(prompt: str, typed: str, width: int) -> list[str]:
|
||||
"""prompt wrapped to width, then what the human typed after it, cut every width characters so that each space typed shows."""
|
||||
*lines, last = wrapped(prompt, width)
|
||||
line = f"{last} {typed}"
|
||||
step = max(width, NARROWEST)
|
||||
return [*lines, *(line[start : start + step] for start in range(0, len(line), step))]
|
||||
|
||||
|
||||
def cut(lines: list[str], count: int) -> list[str]:
|
||||
"""The first count lines, indented; a cut is marked with an ellipsis."""
|
||||
shown = [f"{INDENT}{line}" for line in lines[:count]]
|
||||
return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown
|
||||
|
||||
|
||||
def waited(seconds: float) -> str:
|
||||
minutes = int(seconds // 60)
|
||||
if minutes < 60:
|
||||
return f"{minutes} min"
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
if hours < 24:
|
||||
return f"{hours} h {minutes} min"
|
||||
days, hours = divmod(hours, 24)
|
||||
return f"{days} d {hours} h"
|
||||
@@ -0,0 +1,189 @@
|
||||
"""Show the interrupts of every loop-claude on this machine, oldest first, and answer each one here.
|
||||
Below them, list every loop-claude that runs and the todo.md items its chunk takes.
|
||||
|
||||
usage: loop-inbox
|
||||
|
||||
Each loop-claude lists its interrupt here, as well as on its own terminal, until it is answered or
|
||||
the loop stops. The list shows each loop's checkout, when it asked and how long it has waited, and
|
||||
the question's first lines; it refreshes every second. Type a loop's number and Enter to see as much
|
||||
of its question as fits; the loop's terminal shows it whole. Answer as on the loop's terminal:
|
||||
|
||||
- A line and Enter sends it to that loop, which goes on with it. Of a pasted answer, only the first
|
||||
line is sent, and the rest is dropped; a longer answer goes through /talk.
|
||||
- /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's
|
||||
terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what
|
||||
you typed; if you typed nothing, the loop stops.
|
||||
- Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop.
|
||||
|
||||
The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no
|
||||
loop-inbox running. A loop with claude open, for a release ready to cut, the routing calls or a
|
||||
/talk, says where, and is answered there. A loop whose process is gone drops off the list. A loop
|
||||
asking for its project's model, as on a project's first run, asks on its own terminal only. q quits
|
||||
loop-inbox; the loops keep waiting.
|
||||
|
||||
Below the questions, loop-inbox lists each running loop: its checkout, its number in the list
|
||||
above where it waits for an answer, and a line per todo.md item its chunk takes, with the item's
|
||||
tagline on the default branch. A loop whose process is gone drops off this list too.
|
||||
|
||||
The loops' questions are files in ~/.local/state/loop-claude, read and written as
|
||||
bin/loop_claude/waiting/ describes; the running loops are files beside them, as
|
||||
bin/loop_claude/running_loops.py describes.
|
||||
|
||||
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
|
||||
"""
|
||||
import contextlib
|
||||
import curses
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
|
||||
from loop_claude.waiting.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 failure import Failure
|
||||
from loop_claude.hand_over import hand_over
|
||||
from loop_claude.paths import Paths, paths_from
|
||||
from loop_claude.session_lock import running
|
||||
|
||||
USAGE = "usage: loop-inbox"
|
||||
# Milliseconds between refreshes of the list while no key is pressed.
|
||||
REFRESH_MS = 1000
|
||||
KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE}
|
||||
|
||||
|
||||
def main(argv: list[str], home: pathlib.Path) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if argv:
|
||||
print(f"loop-inbox: unknown argument {argv[0]}; {USAGE}", file=sys.stderr)
|
||||
return 2
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr)
|
||||
return 2
|
||||
# curses may hold keys it has read ahead, which only flushinp drops.
|
||||
effects = dataclasses.replace(system_effects(), discard_typed=curses.flushinp)
|
||||
try:
|
||||
curses.wrapper(lambda window: run(window, lambda: off_screen(window), paths_from(home), effects))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, effects: Effects) -> None:
|
||||
folder = paths.waiting
|
||||
window.timeout(REFRESH_MS)
|
||||
screen: Screen = Listing()
|
||||
while True:
|
||||
drop_ended(folder)
|
||||
drop_ended_loops(folder)
|
||||
screen = entered(screen, refreshed(screen, folder), effects)
|
||||
draw(window, screen, effects)
|
||||
try:
|
||||
key = window.get_wch()
|
||||
except curses.error:
|
||||
continue # No key within REFRESH_MS.
|
||||
after: Screen
|
||||
match pressed(screen, key_name(key)):
|
||||
case Quit():
|
||||
return
|
||||
case Send(ask, text):
|
||||
after = Listing(note=sent(folder, ask, text))
|
||||
case Open(ask):
|
||||
after = Listing(note=opened(screen_off, paths, ask, effects))
|
||||
case Listing() | Answering() as next_screen:
|
||||
after = next_screen
|
||||
screen = entered(screen, after, effects)
|
||||
|
||||
|
||||
def entered(before: Screen, after: Screen, effects: Effects) -> Screen:
|
||||
"""after, the screen that follows before. Leaving the answer screen drops the keys typed ahead, since on the list the rest of a pasted answer would pick a loop and answer it."""
|
||||
if isinstance(before, Answering) and isinstance(after, Listing):
|
||||
effects.discard_typed()
|
||||
return after
|
||||
|
||||
|
||||
def key_name(key: str | int) -> str:
|
||||
"""inbox's name for a key curses read; an empty string for a key loop-inbox has no use for, such as an arrow."""
|
||||
return KEYS.get(key, key if isinstance(key, str) else "")
|
||||
|
||||
|
||||
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
|
||||
"""screen with the loops as they wait and run now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
|
||||
match screen:
|
||||
case Listing(_, "", note):
|
||||
return Listing(tuple(waiting(folder)), "", note, tuple(running_loops(folder)))
|
||||
case Answering(ask) if not still_waits(folder, ask):
|
||||
return Listing(note=no_longer_waits(ask))
|
||||
return screen
|
||||
|
||||
|
||||
def draw(window: curses.window, screen: Screen, effects: Effects) -> None:
|
||||
height, columns = window.getmaxyx()
|
||||
# The screen's last cell cannot be written without an error, so lines leave the last column empty.
|
||||
width = columns - 1
|
||||
now = effects.now()
|
||||
lines, foot = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width)
|
||||
window.erase()
|
||||
for row, line in enumerate(fitted(lines, foot, height)):
|
||||
# addnstr counts characters, not cells, so a line of wide characters, such as emoji, can still run into the last cell.
|
||||
with contextlib.suppress(curses.error):
|
||||
window.addnstr(row, 0, line, width)
|
||||
window.refresh()
|
||||
|
||||
|
||||
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
|
||||
"""Whether ask's loop still runs and still waits for an answer from loop-inbox."""
|
||||
now = read_ask(ask_file(folder, ask.session))
|
||||
return now is not None and now.id == ask.id and isinstance(now.state, Asking) and running(folder, ask.session)
|
||||
|
||||
|
||||
def no_longer_waits(ask: Ask) -> str:
|
||||
return f"{ask.root} no longer waits for that answer: it was answered elsewhere, or stopped."
|
||||
|
||||
|
||||
def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
|
||||
"""Sends text to the loop that asked ask, and says what came of it."""
|
||||
if not still_waits(folder, ask):
|
||||
return no_longer_waits(ask)
|
||||
if unsent := send(folder, ask, Typed(text)):
|
||||
return f"Could not send the answer to {ask.root}: {unsent.reason}"
|
||||
return f"Sent to {ask.root}."
|
||||
|
||||
|
||||
def opened(screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, ask: Ask, effects: Effects) -> str:
|
||||
"""Opens the worker's claude session on this terminal, inside screen_off, once the loop has made way for it, and says what came of it."""
|
||||
folder = paths.waiting
|
||||
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
|
||||
return no_longer_waits(ask)
|
||||
claimed = claim_talk(folder, ask, effects.pid(), effects.now, effects.sleep)
|
||||
if isinstance(claimed, Failure):
|
||||
return f"Could not open claude for {ask.root}: {claimed.reason}"
|
||||
if not claimed:
|
||||
return f"Could not open claude for {ask.root}: the loop was answered elsewhere or stopped, or didn't respond within {MAKE_WAY_SECONDS:g} s. If it is still listed, pick it again."
|
||||
with screen_off():
|
||||
try:
|
||||
unstarted = hand_over(ask.state.talk, effects)
|
||||
finally:
|
||||
unsent = send(folder, ask, ClaudeEnded())
|
||||
# The loop goes on only where the human typed in the worker's session, as interrupt.human_typed checks.
|
||||
said = f"Could not start claude for {ask.root}: {unstarted.reason}. The loop stops." if unstarted else f"claude for {ask.root} has ended; the loop goes on if you typed there, and stops if you didn't."
|
||||
# The loop also stops waiting for claude once loop-inbox's process ends.
|
||||
return f"{said} Could not tell the loop that claude ended: {unsent.reason}; it waits until you quit loop-inbox." if unsent else said
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def off_screen(window: curses.window) -> typing.Iterator[None]:
|
||||
"""Hands the terminal to another program, and draws loop-inbox again once it ends."""
|
||||
curses.def_prog_mode()
|
||||
curses.endwin()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
curses.reset_prog_mode()
|
||||
window.refresh()
|
||||
@@ -0,0 +1,610 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.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 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
|
||||
|
||||
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
|
||||
# The pid of this loop-inbox.
|
||||
INBOX = 4343
|
||||
ANSWERED_ON_TERMINAL = object()
|
||||
|
||||
|
||||
def asked(session, root, question="Which one?", at=100.0, state=ASKING):
|
||||
return Ask(f"ask-{session}", session, root, question, at, state)
|
||||
|
||||
|
||||
def loops_hold(test, folder, *sessions):
|
||||
"""Holds each session's lock until the test ends, as a running loop does."""
|
||||
for session in sessions:
|
||||
test.enterContext(session_lock.held(folder, session))
|
||||
|
||||
|
||||
def asks_and_answers(folder):
|
||||
return sorted(path.name for path in folder.iterdir() if path.suffix != ".lock")
|
||||
|
||||
|
||||
def keyed(screen, *keys):
|
||||
for key in keys:
|
||||
screen = inbox.pressed(screen, key)
|
||||
return screen
|
||||
|
||||
|
||||
class OutOfKeys(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Window:
|
||||
"""A curses window that records the lines drawn on it, and hands out keys in turn, running each callable among them as it comes."""
|
||||
|
||||
def __init__(self, keys=(), height=24, width=80):
|
||||
self.keys, self.height, self.width = list(keys), height, width
|
||||
self.lines = {}
|
||||
|
||||
def getmaxyx(self):
|
||||
return self.height, self.width
|
||||
|
||||
def timeout(self, milliseconds):
|
||||
pass
|
||||
|
||||
def get_wch(self):
|
||||
while self.keys and callable(self.keys[0]):
|
||||
self.keys.pop(0)()
|
||||
if not self.keys:
|
||||
raise OutOfKeys
|
||||
return self.keys.pop(0)
|
||||
|
||||
def drop_typed(self):
|
||||
"""Drops the keys not yet read, as curses.flushinp does."""
|
||||
self.keys.clear()
|
||||
|
||||
def erase(self):
|
||||
self.lines = {}
|
||||
|
||||
def addnstr(self, row, column, text, count):
|
||||
self.lines[row] = text[:count]
|
||||
|
||||
def refresh(self):
|
||||
pass
|
||||
|
||||
|
||||
class Answers(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
loops_hold(self, self.folder, "s1", "s2")
|
||||
|
||||
def answer(self, number, text):
|
||||
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
|
||||
action = keyed(Listing(tuple(waiting(self.folder))), *number, ENTER, *text, ENTER)
|
||||
self.assertIsInstance(action, Send)
|
||||
return main.sent(self.folder, action.ask, action.text)
|
||||
|
||||
def test_two_waiting_loops_each_get_their_own_answer(self):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
for ask in (bender, log):
|
||||
publish(self.folder, ask)
|
||||
self.assertEqual(self.answer("2", "Use B."), "Sent to /code/bender.")
|
||||
self.assertEqual(self.answer("1", "Use A."), "Sent to /code/log.")
|
||||
self.assertEqual((answered(self.folder, log), answered(self.folder, bender)), (Typed("Use A."), Typed("Use B.")))
|
||||
|
||||
def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
for ask in (log, bender):
|
||||
publish(self.folder, ask)
|
||||
picked = keyed(Listing(tuple(waiting(self.folder))), "1", ENTER, "A", ENTER)
|
||||
# log is answered on its terminal before the answer typed here is sent; bender is now first.
|
||||
withdraw(self.folder, "s1")
|
||||
self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
|
||||
self.assertEqual(asks_and_answers(self.folder), ["s2.json"])
|
||||
|
||||
def test_the_list_shows_the_loops_still_waiting_and_keeps_its_note(self):
|
||||
log = asked("s1", "/code/log")
|
||||
for ask in (log, asked("s3", "/code/bender")):
|
||||
publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder), Listing((log,), "", "Sent to /a."))
|
||||
|
||||
def test_the_list_shows_the_loops_running_now(self):
|
||||
self.enterContext(running_loops.shown_running(self.folder, "s9", "/code/web", system_effects()))
|
||||
self.assertEqual(main.refreshed(Listing(), self.folder), Listing(running=(RunningLoop("s9", "/code/web", ()),)))
|
||||
|
||||
def test_a_number_picks_the_loop_it_had_when_the_human_began_typing_it(self):
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
typing = keyed(Listing((log, bender)), "2")
|
||||
publish(self.folder, bender)
|
||||
self.assertEqual(main.refreshed(typing, self.folder), typing)
|
||||
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
|
||||
|
||||
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
|
||||
for state, where in ((OpenOnTerminal(), "on its terminal"), (OpenInInbox(7), "in loop-inbox")):
|
||||
with self.subTest(where=where):
|
||||
self.assertEqual(keyed(Listing((asked("s1", "/code/log", state=state),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there."))
|
||||
|
||||
def test_an_ask_file_says_when_the_loop_asked_as_an_iso_utc_datetime(self):
|
||||
ask = asked("s1", "/code/log", at=100)
|
||||
publish(self.folder, ask)
|
||||
self.assertEqual(json.loads(ask_file(self.folder, "s1").read_text())["asked"], "1970-01-01T00:01:40Z")
|
||||
self.assertEqual(read_ask(ask_file(self.folder, "s1")), ask)
|
||||
|
||||
def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us"))
|
||||
publish(self.folder, dataclasses.replace(ask, id="a later ask"))
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped."))
|
||||
|
||||
def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self):
|
||||
ask = asked("s3", "/code/bender")
|
||||
publish(self.folder, ask)
|
||||
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped."))
|
||||
|
||||
def claim(self, ask, loop_does):
|
||||
"""claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait."""
|
||||
tenths = [0]
|
||||
def sleep(seconds):
|
||||
if not tenths[0]:
|
||||
loop_does()
|
||||
tenths[0] += round(seconds * 10)
|
||||
return claim_talk(self.folder, ask, INBOX, lambda: tenths[0] / 10, sleep), tenths[0] / 10
|
||||
|
||||
def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
def made_way_for_the_claim():
|
||||
claim = answered(self.folder, ask)
|
||||
if isinstance(claim, ClaudeOpening):
|
||||
publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid)))
|
||||
for loop_does, claimed in (
|
||||
(made_way_for_the_claim, (True, 0.1)),
|
||||
(lambda: withdraw(self.folder, "s1"), (False, 0.1)),
|
||||
(lambda: publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)),
|
||||
(lambda: publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)),
|
||||
(lambda: None, (False, MAKE_WAY_SECONDS)),
|
||||
):
|
||||
with self.subTest(claimed=claimed):
|
||||
publish(self.folder, ask)
|
||||
self.assertEqual(self.claim(ask, loop_does), claimed)
|
||||
|
||||
def test_a_claim_the_loop_did_not_make_way_for_in_time_is_taken_back(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
publish(self.folder, ask)
|
||||
self.claim(ask, lambda: None)
|
||||
# A loop that reads it late ends its wait at once, as for a claude that has ended.
|
||||
self.assertEqual((answered(self.folder, ask), claude_ended(self.folder, ask)), (None, True))
|
||||
|
||||
|
||||
def never_opens(args, cwd, env):
|
||||
raise AssertionError("claude opened")
|
||||
|
||||
|
||||
class Opens(unittest.TestCase):
|
||||
def setUp(self):
|
||||
home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, home)
|
||||
self.paths = paths_from(home)
|
||||
self.ask = asked("s1", "/code/log")
|
||||
loops_hold(self, self.paths.waiting, "s1")
|
||||
publish(self.paths.waiting, self.ask)
|
||||
|
||||
def open(self, claude, loop_shows=OpenInInbox(INBOX)):
|
||||
"""What /talk in loop-inbox says for self.ask, whose loop shows loop_shows once claim_talk has asked it to make way; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended."""
|
||||
def loop_looks(_):
|
||||
publish(self.paths.waiting, dataclasses.replace(self.ask, state=loop_shows))
|
||||
effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=loop_looks)
|
||||
try:
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
return main.opened(contextlib.nullcontext, self.paths, self.ask, effects)
|
||||
finally:
|
||||
self.ended = claude_ended(self.paths.waiting, self.ask)
|
||||
|
||||
def test_tells_the_loop_once_claude_ends_or_cannot_start_and_says_what_the_loop_does(self):
|
||||
def unstarted(args, cwd, env):
|
||||
raise OSError(2, "No such file or directory")
|
||||
for claude, said in (
|
||||
(lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't."),
|
||||
(unstarted, "Could not start claude for /code/log: No such file or directory. The loop stops."),
|
||||
):
|
||||
with self.subTest(said=said):
|
||||
publish(self.paths.waiting, self.ask)
|
||||
self.assertEqual(self.open(claude), said)
|
||||
self.assertTrue(self.ended)
|
||||
|
||||
def test_says_the_loop_waits_for_loop_inbox_to_quit_where_it_cannot_tell_it_that_claude_ended(self):
|
||||
def folder_lost(args, cwd, env):
|
||||
shutil.rmtree(self.paths.waiting)
|
||||
self.paths.waiting.write_text("")
|
||||
said = "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't. Could not tell the loop that claude ended: Not a directory; it waits until you quit loop-inbox."
|
||||
self.assertEqual(self.open(folder_lost), said)
|
||||
|
||||
def test_opens_no_claude_for_a_loop_that_takes_talk_on_its_terminal_first(self):
|
||||
said = "Could not open claude for /code/log: the loop was answered elsewhere or stopped, or didn't respond within 5 s. If it is still listed, pick it again."
|
||||
self.assertEqual(self.open(never_opens, loop_shows=OpenOnTerminal()), said)
|
||||
|
||||
def test_opens_no_claude_and_sends_nothing_to_a_loop_that_no_longer_waits(self):
|
||||
withdraw(self.paths.waiting, "s1")
|
||||
self.assertEqual(self.open(never_opens), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
|
||||
self.assertEqual(asks_and_answers(self.paths.waiting), [])
|
||||
|
||||
def test_tells_the_loop_when_claude_is_interrupted(self):
|
||||
def interrupted(args, cwd, env):
|
||||
raise KeyboardInterrupt
|
||||
with self.assertRaises(KeyboardInterrupt):
|
||||
self.open(interrupted)
|
||||
self.assertTrue(self.ended)
|
||||
|
||||
|
||||
class Typing(unittest.TestCase):
|
||||
def typed(self, *keys):
|
||||
"""What the log and bender loops get once keys are typed into loop-inbox, which lists log first. ANSWERED_ON_TERMINAL among the keys stands for log being answered on its terminal. Fails where loop-inbox quits before the keys run out."""
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
paths = paths_from(pathlib.Path(home))
|
||||
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
|
||||
loops_hold(self, paths.waiting, "s1", "s2")
|
||||
for ask in (log, bender):
|
||||
publish(paths.waiting, ask)
|
||||
def answered_on_terminal():
|
||||
withdraw(paths.waiting, "s1")
|
||||
window = Window(answered_on_terminal if key is ANSWERED_ON_TERMINAL else key for key in keys)
|
||||
def made_way(seconds):
|
||||
publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX)))
|
||||
effects = dataclasses.replace(system_effects(), claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way)
|
||||
with self.assertRaises(OutOfKeys), contextlib.redirect_stderr(io.StringIO()):
|
||||
main.run(window, contextlib.nullcontext, paths, effects)
|
||||
return answered(paths.waiting, log), answered(paths.waiting, bender)
|
||||
|
||||
def test_keys_typed_ahead_are_dropped_once_the_answer_screen_is_left(self):
|
||||
# Each case types, after leaving log's answer screen, a line that would pick bender and one that would answer it, or a line that would quit.
|
||||
for case, keys, got in (
|
||||
("a pasted answer", "1\nYes.\nSee item 2.\nThen release.\n", (Typed("Yes."), None)),
|
||||
("a pasted answer with a line that would quit", "1\nOk.\nquick check first\n", (Typed("Ok."), None)),
|
||||
("/talk", "1\n/talk\n2\nUse B.\n", (None, None)),
|
||||
("a paste that opens with an empty line", "1\n\nSee item 2.\nThen release.\n", (None, None)),
|
||||
("an answer typed as log is answered on its terminal", ["1", "\n", "U", "s", "e", ANSWERED_ON_TERMINAL, *" option 1.\nThen release.\n"], (None, None)),
|
||||
):
|
||||
with self.subTest(case):
|
||||
self.assertEqual(self.typed(*keys), got)
|
||||
|
||||
|
||||
class Keys(unittest.TestCase):
|
||||
def test_the_list_takes_a_number_and_quits_on_q(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
for keys, after in (
|
||||
(("q",), Quit()),
|
||||
(("1", "q"), Listing((ask,), "1")),
|
||||
(("1", "2", "3", BACKSPACE), Listing((ask,), "12")),
|
||||
(("x",), Listing((ask,))),
|
||||
(("²",), Listing((ask,))),
|
||||
((ENTER,), Listing()),
|
||||
(("2", ENTER), Listing(note="No loop has the number 2.")),
|
||||
(("1", ENTER), Answering(ask)),
|
||||
):
|
||||
with self.subTest(keys=keys):
|
||||
self.assertEqual(keyed(Listing((ask,)), *keys), after)
|
||||
|
||||
def test_a_number_typed_keeps_the_running_loops_shown_and_clears_the_note(self):
|
||||
running = (RunningLoop("s1", "/code/log", ()),)
|
||||
self.assertEqual(keyed(Listing(note="No loop has the number 7.", running=running), "1", "2", BACKSPACE), Listing((), "1", "", running))
|
||||
self.assertEqual(keyed(Listing(typed="1", note="No loop has the number 7.", running=running), BACKSPACE), Listing((), "", "", running))
|
||||
|
||||
def test_an_answer_is_sent_stripped_talk_opens_claude_and_enter_alone_or_esc_goes_back(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
for keys, after in (
|
||||
((*" Use B. ", ENTER), Send(ask, "Use B.")),
|
||||
((*" /talk", ENTER), Open(ask)),
|
||||
(("U", "s", "e", "x", BACKSPACE), Answering(ask, "Use")),
|
||||
((" ", ENTER), Listing()),
|
||||
(("U", ESCAPE), Listing()),
|
||||
(("\t",), Answering(ask)),
|
||||
):
|
||||
with self.subTest(keys=keys):
|
||||
self.assertEqual(keyed(Answering(ask), *keys), after)
|
||||
|
||||
def test_curses_keys_get_inboxs_names(self):
|
||||
for key, name in (("\n", ENTER), (main.curses.KEY_ENTER, ENTER), ("\x7f", BACKSPACE), (main.curses.KEY_BACKSPACE, BACKSPACE), ("\x1b", ESCAPE), ("a", "a"), (main.curses.KEY_LEFT, "")):
|
||||
with self.subTest(key=key):
|
||||
self.assertEqual(main.key_name(key), name)
|
||||
|
||||
|
||||
class Waiting(unittest.TestCase):
|
||||
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal())
|
||||
loops_hold(self, pathlib.Path(folder), "s1", "s2")
|
||||
for ask in (late, early, stopped):
|
||||
publish(pathlib.Path(folder), ask)
|
||||
pathlib.Path(folder, "s4.json").write_text("{")
|
||||
pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}')
|
||||
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
|
||||
self.assertEqual(waiting(pathlib.Path(folder)), [early, late])
|
||||
|
||||
def test_drops_and_removes_the_ask_a_killed_loop_left_behind(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, session_lock, listed, system_effects\nwith session_lock.held(pathlib.Path(sys.argv[1]), 's1'), listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)"
|
||||
loop = subprocess.Popen([sys.executable, "-c", lists_and_waits, temp], cwd=pathlib.Path(__file__).parent, stdout=subprocess.PIPE)
|
||||
self.addCleanup(loop.wait)
|
||||
self.addCleanup(loop.kill)
|
||||
loop.stdout.readline()
|
||||
send(folder, asked("s1", "/a"), Typed("Use A."))
|
||||
self.assertEqual(waiting(folder), [asked("s1", "/a")])
|
||||
# SIGKILL runs none of the loop's cleanup.
|
||||
loop.kill()
|
||||
loop.wait()
|
||||
self.assertEqual(waiting(folder), [])
|
||||
drop_ended(folder)
|
||||
self.assertEqual(asks_and_answers(folder), [])
|
||||
|
||||
def test_loop_inbox_removes_a_killed_loops_ask_answer_and_running_file_as_it_looks(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
paths = paths_from(pathlib.Path(home))
|
||||
ask = asked("s1", "/a")
|
||||
publish(paths.waiting, ask)
|
||||
send(paths.waiting, ask, Typed("Use A."))
|
||||
running_loops.running_file(paths.waiting, "s1").write_text(json.dumps({"root": "/a", "items": []}))
|
||||
main.run(Window("q"), contextlib.nullcontext, paths, system_effects())
|
||||
self.assertEqual(asks_and_answers(paths.waiting), [])
|
||||
|
||||
def test_removes_only_the_asks_answers_and_running_files_whose_loop_has_ended_each_by_its_own_module(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp)
|
||||
loops_hold(self, folder, "s1")
|
||||
for ask in (asked("s1", "/a"), asked("s2", "/b")):
|
||||
publish(folder, ask)
|
||||
send(folder, ask, Typed("Use A."))
|
||||
for session in ("s1", "s2", "s3"):
|
||||
running_loops.running_file(folder, session).write_text(json.dumps({"root": "/a", "items": []}))
|
||||
drop_ended(folder)
|
||||
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running", "s2.running", "s3.running"])
|
||||
running_loops.drop_ended_loops(folder)
|
||||
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json", "s1.running"])
|
||||
|
||||
def test_a_talk_claim_from_pid_0_or_below_is_no_answer_since_it_would_name_a_process_group(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
ask = asked("s1", "/a")
|
||||
for pid in (0, -1):
|
||||
with self.subTest(pid=pid):
|
||||
send(pathlib.Path(temp), ask, ClaudeOpening(pid))
|
||||
self.assertIsNone(answered(pathlib.Path(temp), ask))
|
||||
|
||||
def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
path = ask_file(pathlib.Path(temp), "s1")
|
||||
publish(path.parent, asked("s1", "/a"))
|
||||
good = json.loads(path.read_text())
|
||||
self.assertEqual(read_ask(path), asked("s1", "/a"))
|
||||
for field, value in (
|
||||
("id", 1),
|
||||
("session", "s2"),
|
||||
("root", None),
|
||||
("question", 3),
|
||||
("asked", "noon"),
|
||||
("asked", 100.0),
|
||||
("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}),
|
||||
("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}),
|
||||
):
|
||||
with self.subTest(field=field, value=value):
|
||||
path.write_text(json.dumps(good | {field: value}))
|
||||
self.assertIsNone(read_ask(path))
|
||||
|
||||
def test_withdraw_says_what_it_cannot_remove(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder = pathlib.Path(temp, "a file")
|
||||
folder.write_text("")
|
||||
self.assertEqual(withdraw(folder, "s1"), Failure(f"cannot remove {folder / 's1.json'}: Not a directory"))
|
||||
|
||||
def test_a_message_reaches_only_the_ask_it_names(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
folder, ask = pathlib.Path(temp), asked("s1", "/a")
|
||||
another = dataclasses.replace(ask, id="another")
|
||||
for message, answer, ended in ((Typed("A"), Typed("A"), False), (ClaudeOpening(7), ClaudeOpening(7), False), (ClaudeEnded(), None, True)):
|
||||
with self.subTest(message=message):
|
||||
send(folder, ask, message)
|
||||
self.assertEqual((answered(folder, ask), claude_ended(folder, ask)), (answer, ended))
|
||||
self.assertEqual((answered(folder, another), claude_ended(folder, another)), (None, False))
|
||||
|
||||
|
||||
class RunningLoops(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.folder = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.folder)
|
||||
self.effects = dataclasses.replace(system_effects(), sleep=lambda seconds: None)
|
||||
|
||||
def test_lists_a_loop_with_the_items_it_shows_until_it_ends(self):
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as listed:
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
|
||||
listed.show((Taken(255, "Have loop-inbox list every running loop."),))
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", (Taken(255, "Have loop-inbox list every running loop."),))])
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [])
|
||||
|
||||
def test_lists_the_loops_by_checkout_and_leaves_out_one_that_was_killed_or_whose_file_cannot_be_read(self):
|
||||
# Five, so the order the files are found in is unlikely to be the order by checkout.
|
||||
for session, root in (("s1", "/code/web"), ("s2", "/code/c"), ("s7", "/code/a"), ("s8", "/code/z"), ("s9", "/code/m")):
|
||||
self.enterContext(running_loops.shown_running(self.folder, session, root, self.effects))
|
||||
# A killed loop leaves its file behind, and its lock free.
|
||||
(self.folder / "s3.running").write_text(json.dumps({"root": "/code/old", "items": []}))
|
||||
for session, content in (("s4", "{"), ("s5", json.dumps({"root": "/code/x", "items": [{"id": "1", "tagline": ""}]})), ("s6", json.dumps({"root": "/code/x"})), ("s10", json.dumps({"root": "/code/x", "items": [{"id": True, "tagline": ""}]}))):
|
||||
self.enterContext(session_lock.held(self.folder, session))
|
||||
(self.folder / f"{session}.running").write_text(content)
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s7", "/code/a", ()), RunningLoop("s2", "/code/c", ()), RunningLoop("s9", "/code/m", ()), RunningLoop("s1", "/code/web", ()), RunningLoop("s8", "/code/z", ())])
|
||||
|
||||
def test_a_second_loop_on_the_session_warns_and_leaves_the_first_listed_with_its_question(self):
|
||||
ask = asked("s1", "/code/log")
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as first:
|
||||
publish(first.folder, ask)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", self.effects) as second:
|
||||
second.show((Taken(1, "Do it."),))
|
||||
with listed(second.folder, asked("s1", "/code/log", question="Mine?"), self.effects):
|
||||
self.assertEqual(waiting(self.folder), [ask])
|
||||
self.assertIn(f"loop-inbox cannot list this loop or its questions: another process holds {session_lock.lock_file(self.folder, 's1')}", said.getvalue())
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
|
||||
self.assertEqual(waiting(self.folder), [ask])
|
||||
self.assertEqual(list((self.folder / "unlisted").iterdir()), [])
|
||||
|
||||
def test_takes_the_lock_once_loop_inbox_lets_go_of_it(self):
|
||||
# loop-inbox holds the lock for a moment as it checks whether the loop runs.
|
||||
looking = contextlib.ExitStack()
|
||||
looking.enter_context(session_lock.held(self.folder, "s1"))
|
||||
with running_loops.shown_running(self.folder, "s1", "/code/log", dataclasses.replace(self.effects, sleep=lambda seconds: looking.close())):
|
||||
self.assertEqual(running_loops.running_loops(self.folder), [RunningLoop("s1", "/code/log", ())])
|
||||
|
||||
|
||||
class Shown(unittest.TestCase):
|
||||
def drawn(self, screen, window):
|
||||
"""The lines draw puts on window for screen, 3700 s after the epoch."""
|
||||
main.draw(window, screen, dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: 3700))
|
||||
return [window.lines[row] for row in range(len(window.lines))]
|
||||
|
||||
def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self):
|
||||
log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0)
|
||||
cut = asked("s2", "/code/c", "Cut 0.4.0?\nIts changelog is ready.", at=3600 * 25, state=OpenInInbox(INBOX))
|
||||
lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 50)
|
||||
self.assertEqual(lines, ([
|
||||
"2 loops wait for you, oldest first.",
|
||||
"",
|
||||
"[1] /code/log, waiting since <0> (1 d 2 h)",
|
||||
" Which store should the cache use: Redis or",
|
||||
" SQLite? Redis is already deployed for…",
|
||||
"",
|
||||
"[2] /code/c, waiting since <90000> (1 h 2 min);",
|
||||
"claude is open in loop-inbox",
|
||||
" Cut 0.4.0?",
|
||||
" Its changelog is ready.",
|
||||
"",
|
||||
"No loop runs.",
|
||||
], [
|
||||
"Type a number and Enter to answer that loop; q",
|
||||
"quits loop-inbox, and the loops keep waiting.",
|
||||
"> 1",
|
||||
]))
|
||||
|
||||
def test_the_running_loops_follow_the_waiting_ones_each_with_the_items_its_chunk_takes(self):
|
||||
log = asked("s1", "/code/log", "Which one?", at=0)
|
||||
running = (
|
||||
RunningLoop("s2", "/code/c", (Taken(12, "Accept undefined in MetadataValue and drop such keys on output."), Taken(14, ""))),
|
||||
RunningLoop("s1", "/code/log", (Taken(255, "Have loop-inbox list every running loop-claude on the machine."),)),
|
||||
RunningLoop("s3", "/code/web", ()),
|
||||
)
|
||||
lines, _ = inbox.listing_lines(Listing((log,), running=running), 120, lambda seconds: f"<{seconds}>", 50)
|
||||
self.assertEqual(lines, [
|
||||
"1 loop waits for you.",
|
||||
"",
|
||||
"[1] /code/log, waiting since <0> (2 min)",
|
||||
" Which one?",
|
||||
"",
|
||||
"Running: 3 loops",
|
||||
"- /code/c",
|
||||
" item 12: Accept undefined in MetadataValue…",
|
||||
" item 14",
|
||||
"- /code/log, waiting as [1]",
|
||||
" item 255: Have loop-inbox list every running…",
|
||||
"- /code/web",
|
||||
" no todo.md item yet",
|
||||
])
|
||||
|
||||
def test_the_running_section_counts_one_loop(self):
|
||||
lines, _ = inbox.listing_lines(Listing(running=(RunningLoop("s1", "/code/log", ()),)), 0, str, 79)
|
||||
self.assertEqual(lines, ["No loop waits for you.", "", "Running: 1 loop", "- /code/log", " no todo.md item yet"])
|
||||
|
||||
def test_an_empty_list_says_no_loop_waits_or_runs(self):
|
||||
self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 79), (["No loop waits for you.", "", "No loop runs."], ["Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "]))
|
||||
|
||||
def test_the_answer_screen_at_80_columns_shows_every_character_of_each_line_and_says_what_enter_alone_does(self):
|
||||
# The question's first line has 80 characters, one more than a line drawn at 80 columns holds.
|
||||
ask = asked("s1", "/code/log", "The changelog lists four fixes and three new tools, so the next release is 0.6.0\n\nCut it?", at=100)
|
||||
self.assertEqual(self.drawn(Answering(ask, "Yes"), Window(width=80)), [
|
||||
"/code/log, waiting since <100> (1 h 0 min):",
|
||||
"",
|
||||
"The changelog lists four fixes and three new tools, so the next release is",
|
||||
"0.6.0",
|
||||
"",
|
||||
"Cut it?",
|
||||
"",
|
||||
"Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps",
|
||||
"waiting): Yes",
|
||||
])
|
||||
|
||||
def test_an_answer_longer_than_its_line_goes_on_below_it_with_every_space_typed(self):
|
||||
typed = "Use B, as the cache then runs next to the sessions it serves and then cut 0.6.0."
|
||||
lines = self.drawn(Answering(asked("s1", "/code/log", "A or B?", at=100), typed), Window(width=80))
|
||||
self.assertEqual(lines[-2:], ["waiting): Use B, as the cache then runs next to the sessions it serves and then", " cut 0.6.0."])
|
||||
|
||||
def test_a_line_that_runs_into_the_screens_last_cell_leaves_the_screen_drawn(self):
|
||||
class Refusing(Window):
|
||||
"""Refuses the screen's last row, as curses refuses a line of wide characters, such as emoji, that runs into the last cell."""
|
||||
|
||||
def addnstr(self, row, column, text, count):
|
||||
super().addnstr(row, column, text, count)
|
||||
if row == self.height - 1:
|
||||
raise main.curses.error("addnwstr() returned ERR")
|
||||
self.assertEqual(self.drawn(Listing(), Refusing(height=3)), ["…", "q quits loop-inbox, and the loops keep waiting.", "> "])
|
||||
|
||||
def test_a_screen_too_short_keeps_the_foot_and_marks_the_cut(self):
|
||||
for lines, foot, height, shown in (
|
||||
(["a", "b", "c"], ["> "], 4, ["a", "b", "c", "> "]),
|
||||
(["a", "b", "c"], ["> "], 3, ["a", "…", "> "]),
|
||||
(["a", "b", "c"], ["n", "> "], 4, ["a", "…", "n", "> "]),
|
||||
(["a", "b", "c", "d"], ["n", "h", "> "], 2, ["h", "> "]),
|
||||
):
|
||||
with self.subTest(lines=lines, foot=foot, height=height):
|
||||
self.assertEqual(inbox.fitted(lines, foot, height), shown)
|
||||
|
||||
def test_a_wait_reads_in_minutes_under_an_hour_and_in_hours_under_a_day(self):
|
||||
for seconds, read in ((3599, "59 min"), (3600, "1 h 0 min"), (86399, "23 h 59 min"), (86400, "1 d 0 h")):
|
||||
with self.subTest(seconds=seconds):
|
||||
self.assertEqual(inbox.waited(seconds), read)
|
||||
|
||||
|
||||
class Terminal(io.StringIO):
|
||||
def isatty(self):
|
||||
return True
|
||||
|
||||
|
||||
class Starts(unittest.TestCase):
|
||||
def started(self, argv, stdin, stdout):
|
||||
"""What main returns for argv, run with stdin and stdout, and what it writes to stderr."""
|
||||
stderr = io.StringIO()
|
||||
with unittest.mock.patch.object(sys, "stdin", stdin), contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
|
||||
code = main.main(argv, pathlib.Path("/no home"))
|
||||
return code, stderr.getvalue()
|
||||
|
||||
def test_help_prints_the_docstring(self):
|
||||
for flag in ("-h", "--help"):
|
||||
with self.subTest(flag):
|
||||
stdout = io.StringIO()
|
||||
self.assertEqual(self.started([flag], io.StringIO(), stdout), (0, ""))
|
||||
self.assertEqual(stdout.getvalue(), f"{main.__doc__.strip()}\n")
|
||||
|
||||
def test_exits_2_on_an_unknown_argument_or_off_a_terminal(self):
|
||||
off_a_terminal = "loop-inbox: stdin or stdout is not a terminal; run it on one\n"
|
||||
for case, argv, stdin, stdout, said in (
|
||||
("an unknown argument", ["--x"], Terminal(), Terminal(), "loop-inbox: unknown argument --x; usage: loop-inbox\n"),
|
||||
("stdout off a terminal", [], Terminal(), io.StringIO(), off_a_terminal),
|
||||
("stdin off a terminal", [], io.StringIO(), Terminal(), off_a_terminal),
|
||||
):
|
||||
with self.subTest(case):
|
||||
self.assertEqual(self.started(argv, stdin, stdout), (2, said))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,7 +4,7 @@ import dataclasses
|
||||
import os
|
||||
import statistics
|
||||
|
||||
from comprehension_history import Place
|
||||
from review_rules.comprehension_history import Place
|
||||
from metric_bench.python_units import Unit
|
||||
|
||||
METRICS: dict[str, Callable[[Unit, dict[str, int]], int]] = {
|
||||
|
||||
@@ -36,9 +36,9 @@ import statistics
|
||||
import sys
|
||||
|
||||
from metric_bench.bench import bench, co_changed, medians, METRICS, RunScores, Score, tracked_places
|
||||
from comprehension_history import entries, Entry
|
||||
from review_rules.comprehension_history import entries, Entry
|
||||
from failure import Failure
|
||||
from git_repo import git
|
||||
from git_cli.git_repo import git
|
||||
from metric_bench.python_units import measured, python_units, Unit
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from metric_bench.bench import auc, bench, co_changed, top_k, tracked_places
|
||||
from metric_bench.python_units import cognitive, measured, python_units, Unit
|
||||
from comprehension_history import entries, Place
|
||||
from review_rules.comprehension_history import entries, Place
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from metric_bench.main import scored_runs
|
||||
|
||||
@@ -3,7 +3,7 @@ import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from review_passes import ReviewedPass, REVIEWERS
|
||||
from review_rules.review_passes import ReviewedPass
|
||||
|
||||
# How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back.
|
||||
WORDING = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort")
|
||||
@@ -36,7 +36,7 @@ class Rung:
|
||||
return Rung(model, effort)
|
||||
return Rung(family.model, effort) if effort else family
|
||||
|
||||
# The one spelling of a rung. loop-claude hands it to rule-hook in environment variables, and archive lines written before route.Route.worker_line hold it, so parse must keep reading it.
|
||||
# loop-claude hands a rung to rule-hook in environment variables in this spelling, so parse must keep reading it.
|
||||
def __str__(self) -> str:
|
||||
return f"{self.model} at {self.effort} effort" if self.effort else self.model
|
||||
|
||||
@@ -49,11 +49,6 @@ class Rung:
|
||||
|
||||
# Least competent first.
|
||||
LADDER = (
|
||||
Rung("claude-haiku-5-5", "low"),
|
||||
Rung("claude-haiku-5-5", "medium"),
|
||||
Rung("claude-haiku-5-5", "high"),
|
||||
Rung("claude-haiku-5-5", "xhigh"),
|
||||
Rung("claude-haiku-5-5", "max"),
|
||||
Rung("claude-sonnet-5-5", "high"),
|
||||
Rung("claude-opus-5-5", "medium"),
|
||||
Rung("claude-opus-5-5", "high"),
|
||||
@@ -65,8 +60,6 @@ LADDER = (
|
||||
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
|
||||
# The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none.
|
||||
REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4}
|
||||
# The rung a pass's replay chose for the projects on a model: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
|
||||
REPLAYED: dict[tuple[ReviewedPass, str], Rung] = {}
|
||||
|
||||
|
||||
def project_rung(model: str) -> Rung | None:
|
||||
@@ -99,24 +92,16 @@ def stepped_up(rung: Rung) -> Rung:
|
||||
return climbed(rung, 1)
|
||||
|
||||
|
||||
def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[ReviewKind, Rung]:
|
||||
"""The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I.
|
||||
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.
|
||||
|
||||
A pass's reviewer runs on reviewers_rung. Where the E + I steps no review up and the worker runs no higher than the project's rung, a pass whose replay chose a rung for the project's model runs on that rung instead, even below the worker's: the replay compared reviews on the project's rung only, never on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. 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.
|
||||
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.
|
||||
"""
|
||||
rungs: dict[ReviewKind, Rung] = {**dict.fromkeys(REVIEWERS, reviewers_rung(project, worker, escape_and_impact)), "seat": project, "security": project}
|
||||
if replay_applies(project, worker, escape_and_impact):
|
||||
rungs |= {kind: rung for (kind, model), rung in REPLAYED.items() if model == project.model}
|
||||
return rungs
|
||||
|
||||
|
||||
def replay_applies(project: Rung, worker: Rung, escape_and_impact: int) -> bool:
|
||||
"""Whether a pass's replay chose its rung for a chunk like this: only where the E + I steps no review up and the worker runs no higher than the project's rung."""
|
||||
return escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project)
|
||||
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact)
|
||||
|
||||
|
||||
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung of each pass's reviewer that no replay lowered: the higher of the worker's rung and review_floor's."""
|
||||
"""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))
|
||||
|
||||
|
||||
|
||||
@@ -2,16 +2,13 @@
|
||||
import dataclasses
|
||||
|
||||
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
|
||||
from model_routing.ladder import replay_applies, review_rungs, reviewers_rung, Rung
|
||||
from review_passes import ReviewedPass, REVIEWERS
|
||||
from model_routing.ladder import reviewers_rung, Rung
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ReviewChoice:
|
||||
# The rung of each pass's reviewer that no replay lowered.
|
||||
# The rung of each pass's reviewer.
|
||||
reviewers: Rung
|
||||
# The passes whose replay chose another rung, with that rung.
|
||||
lowered: dict[ReviewedPass, 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.
|
||||
@@ -20,13 +17,10 @@ class ReviewChoice:
|
||||
|
||||
def chosen(project: Rung, route: Route) -> ReviewChoice:
|
||||
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
|
||||
rungs = review_rungs(project, route.rung, route.reviewed_on())
|
||||
reviewers = reviewers_rung(project, route.rung, route.reviewed_on())
|
||||
lowered = {kind: rungs[kind] for kind in REVIEWERS if rungs[kind] != reviewers}
|
||||
higher: dict[Rung, int] = {}
|
||||
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
|
||||
# A higher E + I changes a review by moving the reviewers' rung, or by ending the replay that lowered a pass.
|
||||
rung = reviewers_rung(project, route.rung, escape_and_impact)
|
||||
if rung != reviewers or (lowered and not replay_applies(project, route.rung, escape_and_impact)):
|
||||
if (rung := reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
|
||||
higher.setdefault(rung, escape_and_impact)
|
||||
return ReviewChoice(reviewers, lowered, rungs["seat"], rungs["security"], higher)
|
||||
# A seat and the security pass run on the project's rung, as ladder.review_rung says.
|
||||
return ReviewChoice(reviewers, project, project, higher)
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each outcome."""
|
||||
"""A chunk's route: its worker's rung and the plan item that picked it. The archive keeps the route as JSON on the Worker: line that ends each verdict, interrupt, quoted answer, stop and step-up."""
|
||||
import dataclasses
|
||||
import json
|
||||
import re
|
||||
import typing
|
||||
|
||||
from todo_table import LEVELS
|
||||
from release_plan.todo_table import LEVELS
|
||||
from model_routing.ladder import REVIEW_STEPS, Rung
|
||||
|
||||
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
ESCALATION_MARKER = "Escalation trigger"
|
||||
# What Route.worker_line writes. The outcome writers take only this as the worker, so mypy refuses a str(route) there.
|
||||
WorkerLine = typing.NewType("WorkerLine", str)
|
||||
# A worker line loop-claude wrote before it archived the route as JSON. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
|
||||
LEGACY_WORKER = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?(?:, escalated at transcript entry (?P<escalated_at>[0-9]+))?")
|
||||
|
||||
|
||||
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
|
||||
@@ -82,8 +79,8 @@ WORKER_LINE_FIELDS = tuple(field.name for field in dataclasses.fields(Route) if
|
||||
|
||||
|
||||
def route_from(worker: str) -> Route | None:
|
||||
"""The route an archived worker line names, whether JSON or a line written before JSON. None where it names no model, holds fields Route.worker_line never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
|
||||
fields = json_fields(worker) if worker.startswith("{") else legacy_fields(worker)
|
||||
"""The route an archived worker line names; None for a line Route.worker_line could not have written, such as text that isn't JSON."""
|
||||
fields = json_fields(worker)
|
||||
if fields is None or not Route.fits(fields):
|
||||
return None
|
||||
return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in WORKER_LINE_FIELDS})
|
||||
@@ -99,12 +96,3 @@ def json_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
return None
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in WORKER_LINE_FIELDS) else None
|
||||
|
||||
|
||||
def legacy_fields(line: str) -> dict[str, typing.Any] | None:
|
||||
"""The fields of a LEGACY_WORKER line, as json_fields gives them; None for any other text."""
|
||||
found = LEGACY_WORKER.fullmatch(line)
|
||||
rung = Rung.parse(found["rung"]) if found else None
|
||||
if not (found and rung):
|
||||
return None
|
||||
return {"model": rung.model, "effort": rung.effort, **{name: int(value or 0) for name, value in found.groupdict().items() if name != "rung"}}
|
||||
|
||||
@@ -1,23 +1,22 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, position, project_rung, review_floor, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
from model_routing import ladder
|
||||
from todo_table import LEVELS
|
||||
from review_passes import REVIEWERS
|
||||
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
from release_plan.todo_table import LEVELS
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
|
||||
|
||||
class Ladder(unittest.TestCase):
|
||||
def test_runs_from_haiku_at_low_effort_to_fable_at_max_with_opus_at_medium_between(self):
|
||||
self.assertEqual(LADDER[0], Rung("claude-haiku-5-5", "low"))
|
||||
def test_runs_from_sonnet_at_high_effort_to_fable_at_max_with_opus_at_medium_between(self):
|
||||
self.assertEqual(LADDER[0], Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER[1], OPUS)
|
||||
self.assertEqual(LADDER[-1], Rung("claude-fable-5-1", "max"))
|
||||
self.assertEqual(len(LADDER), 11)
|
||||
self.assertEqual(len(LADDER), 6)
|
||||
self.assertEqual(len(set(LADDER)), len(LADDER))
|
||||
|
||||
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
|
||||
@@ -53,7 +52,7 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(planning_rung(OPUS, 4), Rung("claude-opus-5-5", "high"))
|
||||
|
||||
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model haiku", "model sonnet", "model opus", "model fable"})
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model sonnet", "model opus", "model fable"})
|
||||
|
||||
def test_ranks_a_rung_off_the_ladder_below_every_rung_on_it(self):
|
||||
self.assertEqual(highest(OPUS, LADDER[-1], LADDER[0]), LADDER[-1])
|
||||
@@ -96,33 +95,11 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
|
||||
|
||||
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
|
||||
haiku, fable = LADDER[4], LADDER[-1]
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 4)["stability"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 5)["stability"], Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rungs(OPUS, fable, 5)["stability"], fable)
|
||||
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["stability"], Rung("claude-opus-5-5", "max"))
|
||||
sonnet, fable = LADDER[0], LADDER[-1]
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 4, "stability"), OPUS)
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rung(OPUS, fable, 5, "stability"), fable)
|
||||
self.assertEqual(review_rung(OPUS, Rung("claude-opus-5-5", "high"), 7, "stability"), Rung("claude-opus-5-5", "max"))
|
||||
|
||||
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
|
||||
|
||||
def test_runs_a_replayed_pass_on_its_replays_rung_below_the_workers_where_the_e_plus_i_steps_no_review_up_and_the_worker_runs_no_higher_than_the_project(self):
|
||||
sonnet, haiku, opus_high = Rung("claude-sonnet-5-5", "high"), LADDER[0], Rung("claude-opus-5-5", "high")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku, ("stability", "claude-sonnet-5-5"): haiku}):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[4], 4), {**dict.fromkeys(REVIEWERS, OPUS), "prose": haiku, "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, OPUS, 4)["prose"], haiku)
|
||||
self.assertEqual(review_rungs(OPUS, opus_high, 4)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 5)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 5)["prose"], LADDER[-1])
|
||||
self.assertEqual((review_rungs(sonnet, sonnet, 4)["prose"], review_rungs(sonnet, sonnet, 4)["stability"]), (sonnet, haiku))
|
||||
|
||||
def test_holds_each_replayed_rung_below_its_models_project_rung_on_the_ladder(self):
|
||||
for (kind, model), rung in ladder.REPLAYED.items():
|
||||
with self.subTest(kind=kind, model=model):
|
||||
project = project_rung(model)
|
||||
self.assertIn(kind, REVIEWERS)
|
||||
self.assertIsNotNone(project)
|
||||
self.assertLess(position(rung), position(project) if project else 0)
|
||||
self.assertIn(rung, LADDER)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS])
|
||||
|
||||
@@ -1,26 +1,13 @@
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
from model_routing.review_choice import chosen, ReviewChoice
|
||||
from model_routing import ladder
|
||||
from model_routing.review_choice import chosen
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
HAIKU = Rung("claude-haiku-5-5", "low")
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
OPUS_MAX = Rung("claude-opus-5-5", "max")
|
||||
FABLE = Rung("claude-fable-5-1", "max")
|
||||
SONNET = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
|
||||
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_names_the_e_plus_i_that_ends_a_replay_even_where_the_reviewers_are_on_the_top_rung(self):
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-fable-5-1"): HAIKU}):
|
||||
self.assertEqual(chosen(FABLE, Route(OPUS_MAX, 3, 4, 4)), ReviewChoice(FABLE, {"prose": HAIKU}, FABLE, FABLE, {FABLE: 5}))
|
||||
|
||||
def test_puts_every_pass_on_the_reviewers_rung_once_an_e_plus_i_steps_a_review_up(self):
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): HAIKU}):
|
||||
self.assertEqual(chosen(OPUS, Route(SONNET, 3, 2, 5)).lowered, {})
|
||||
|
||||
@@ -7,15 +7,15 @@ from model_routing.ladder import Rung
|
||||
|
||||
class Environment(unittest.TestCase):
|
||||
PROJECT = Rung("claude-opus-5-5", "medium")
|
||||
WORKER = Rung("claude-haiku-5-5", "max")
|
||||
WORKER = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "0")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "6")
|
||||
|
||||
def test_a_project_off_the_ladder_is_handed_an_empty_rung_so_none_is_inherited(self):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
|
||||
def test_handed_reads_back_what_environment_named(self):
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, 5))
|
||||
|
||||
@@ -8,7 +8,7 @@ from model_routing.route import Route
|
||||
|
||||
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
|
||||
WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG"
|
||||
# The E + I the chunk's reviews are routed on, from which review_rungs works out each review's rung.
|
||||
# The E + I the chunk's reviews are routed on, from which review_rung works out each review's rung.
|
||||
ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT"
|
||||
|
||||
|
||||
|
||||
+3
-538
@@ -81,58 +81,11 @@ docs/decisions.md that breaks the rules above, a scoring run on docs/comprehensi
|
||||
newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring
|
||||
under the bar, or --check finding the file unranked.
|
||||
"""
|
||||
import ast
|
||||
import dataclasses
|
||||
import decimal
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from 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, version
|
||||
from failure import Failure
|
||||
from comprehension_history import FLOOR, HISTORY, latest_overall
|
||||
from markdown_text import listed, sections
|
||||
from file_writes import replace_file
|
||||
|
||||
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
|
||||
GOAL_STEP = 0.97
|
||||
# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records.
|
||||
UNDER_FLOOR = 4
|
||||
# Any **Void:** line of README.md's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
|
||||
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}
|
||||
# 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"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Scoring:
|
||||
shape: Shape
|
||||
formula: ast.Expression
|
||||
bar: float
|
||||
next_id: int
|
||||
# Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. In OLD_SHAPE an item may name only the goals weights holds.
|
||||
goals: dict[str, Mark]
|
||||
# The weight of each goal an item may name: in OLD_SHAPE each of README.md's goals, at the weight todo.md states; else each goal goal_weights weighs.
|
||||
weights: dict[str, float]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ranked:
|
||||
text: str
|
||||
under_bar: list[str]
|
||||
# What ranking prints and --check does not: an old-shape table's call to reshape, a README that voids code health and marks no goal **Achieve:**, and each dropped blocker ID, since a mistyped ID drops the same way.
|
||||
notes: list[str]
|
||||
from release_plan import ranking
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -144,43 +97,16 @@ def main(argv: list[str]) -> int:
|
||||
return fail(args)
|
||||
check, todo = args
|
||||
if check:
|
||||
failures = check_failures(todo)
|
||||
failures = ranking.check_failures(todo)
|
||||
for line in failures:
|
||||
print(line, file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
ranked = rank_file(todo)
|
||||
ranked = ranking.rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return fail(ranked)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
|
||||
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 fail(failure: Failure) -> int:
|
||||
print(failure.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -193,466 +119,5 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure:
|
||||
return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md")
|
||||
|
||||
|
||||
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)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
shape = shape_of(table.columns)
|
||||
scoring = read_scoring(text, lines, readme, decisions, history, shape)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
items = read_items(table, scoring)
|
||||
if isinstance(items, Failure):
|
||||
return items
|
||||
if uncited := check_citations(items, decisions):
|
||||
return uncited
|
||||
if isinstance(marked := renames(text), Failure):
|
||||
return marked
|
||||
if live := next((item for item in items if item.release in marked), None):
|
||||
return Failure(f"todo.md marks release {version(live.release)} renamed but files item {live.id} under it; drop the mark or move the item")
|
||||
scored = ordered(items, scoring)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored])
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
return Ranked(ranked, under_bar, notes(items, scoring))
|
||||
|
||||
|
||||
# The columns ranking fills itself, so a table without one gains it.
|
||||
WRITTEN = (BLOCKED_BY, "R", "Score")
|
||||
|
||||
|
||||
def rewrite_table(lines: list[str], table: Table, shape: Shape, scored: list[tuple[Item, float]]) -> str:
|
||||
"""lines with the table's rows in scored's order, under a header naming, in shape's order, each column the table holds and each of WRITTEN."""
|
||||
columns = tuple(column for column in shape.columns if column in table.columns or column in WRITTEN)
|
||||
header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
|
||||
rows = [render_item(item, value, shape, columns) for item, value in scored]
|
||||
return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):])
|
||||
|
||||
|
||||
def notes(items: list[Item], scoring: Scoring) -> list[str]:
|
||||
held = {item.id for item in items}
|
||||
dropped = [f"item {item.id}: dropped {', '.join(map(str, gone))} from its {BLOCKED_BY}; the table no longer holds {'it' if len(gone) == 1 else 'them'}" for item in items if (gone := sorted(set(item.blocked_by) - held))]
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
return [RESHAPE] + dropped
|
||||
# Printed so the under-bar lines it causes do not read as items of low value.
|
||||
unweighed = [] if any(scoring.weights.values()) else ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"]
|
||||
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 = []
|
||||
for item in items:
|
||||
value = score(scoring.formula, item, scoring)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
by_score.append((item, value))
|
||||
by_score.sort(key=lambda pair: (pair[0].release, FIRST.get(pair[0].exempt, len(FIRST)), -pair[1], pair[0].id))
|
||||
return blockers_first(by_score)
|
||||
|
||||
|
||||
def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> str:
|
||||
blocks = [str(id_) for id_ in sorted(blocked_through(item.id, items))]
|
||||
blocked = f" and the items it blocks, directly or through another ({', '.join(blocks)})" if blocks else ""
|
||||
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], readme: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = ranked_goals(readme, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
if isinstance(bar, Failure):
|
||||
return bar
|
||||
next_id = stated(text, "Next ID")
|
||||
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
|
||||
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
|
||||
weights = weigh(lines, history, goals, shape)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
|
||||
|
||||
|
||||
def ranked_goals(readme: str, decisions: str) -> list[tuple[str, Mark]] | Failure:
|
||||
"""Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. A **Void:** line other than `**Void:** code health, since <reason>.` fails, and so does a docs/decisions.md that opts out of the comprehension check where README.md keeps code health, since the goal then has no signal."""
|
||||
goals = readme_goals(readme)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
voids = VOID.findall("".join(sections(readme).get("Goals", [])))
|
||||
if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]:
|
||||
if other[0].lower().startswith(CODE_HEALTH):
|
||||
return Failure(f"README.md's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since <reason>.`")
|
||||
return Failure(f"README.md's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since <reason>.`")
|
||||
if voids:
|
||||
return goals
|
||||
if OPTED_OUT.search(decisions):
|
||||
return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** {CODE_HEALTH}, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says")
|
||||
return [(CODE_HEALTH, "Achieve"), *goals]
|
||||
|
||||
|
||||
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure:
|
||||
"""Each goal's weight. In OLD_SHAPE, README.md's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health."""
|
||||
if shape is OLD_SHAPE:
|
||||
return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH])
|
||||
if WEIGHTS_HEADER in lines:
|
||||
return Failure(f"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")
|
||||
overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None
|
||||
if isinstance(overall, Failure):
|
||||
return overall
|
||||
return goal_weights(goals, overall)
|
||||
|
||||
|
||||
def read_table(lines: list[str]) -> Table | Failure:
|
||||
"""The items table, held to its shape's columns and alone under ## Items."""
|
||||
if "## Items" not in lines:
|
||||
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
table = items_table(lines)
|
||||
if table is None:
|
||||
return Failure(f"## Items holds no table whose header opens {HEADER_START}; rank_todo.py --help shows a valid one")
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
shape = shape_of(table.columns)
|
||||
if missing := [column for column in shape.risk_columns if column not in table.columns]:
|
||||
old = older_columns(table, shape)
|
||||
dropped = f", and drop {listed(old, 'and')}" if old else ""
|
||||
columns = f"{listed(missing, 'and')} column; add it" if len(missing) == 1 else f"{listed(missing, 'and')} columns; add them"
|
||||
return Failure(f"todo.md's items table has no {columns}, scoring each item's {listed(shape.risk_columns, 'and')} as rank_todo.py --help shows{dropped}")
|
||||
return unknown_columns(table, shape) or outside_items(lines, table) or table
|
||||
|
||||
|
||||
def unknown_columns(table: Table, shape: Shape) -> Failure | None:
|
||||
"""Why ranking, which writes only the columns of the table's shape, would drop one of the table's columns; None when it would drop none."""
|
||||
unknown = [column for column in table.columns if column not in shape.columns]
|
||||
if old := older_columns(table, shape):
|
||||
kind = "a column of an older shape; drop it" if len(old) == 1 else "columns of an older shape; drop them"
|
||||
return Failure(f"todo.md's items table has {listed(old, 'and')}, {kind}, as rank_todo.py --help shows")
|
||||
if unknown:
|
||||
return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(shape.columns)}. Rename it, or move this machine to the release that added it")
|
||||
return None
|
||||
|
||||
|
||||
def older_columns(table: Table, shape: Shape) -> list[str]:
|
||||
"""The table's columns that only OLD_SHAPE knows, where the table is in SHAPE."""
|
||||
return [column for column in table.columns if column not in SHAPE.columns and column in OLD_SHAPE.columns] if shape is SHAPE else []
|
||||
|
||||
|
||||
def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure:
|
||||
items = []
|
||||
for row in table.rows:
|
||||
item = parse_item(row, scoring, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
items.append(item)
|
||||
ids = {item.id for item in items}
|
||||
if len(ids) < len(items):
|
||||
return Failure("two items share an ID")
|
||||
if ids and max(ids) >= scoring.next_id:
|
||||
return Failure(f"item {max(ids)} is not under Next ID {scoring.next_id}; raise Next ID past every ID")
|
||||
for item in items:
|
||||
if unheld := [blocker for blocker in item.blocked_by if blocker >= scoring.next_id]:
|
||||
return Failure(f"item {item.id} is blocked by item {unheld[0]}, which is not under Next ID {scoring.next_id}; name an item the table holds or held")
|
||||
return items
|
||||
|
||||
|
||||
def outside_items(lines: list[str], table: Table) -> Failure | None:
|
||||
"""Why the table does not stand alone under ## Items: the table's order is todo.md's only order."""
|
||||
heading = max((index for index in range(table.header) if lines[index].startswith("## ")), default=None)
|
||||
if heading is None:
|
||||
return Failure("the items table sits under no ## heading; move it under ## Items")
|
||||
if lines[heading] != "## Items":
|
||||
return Failure(f"the items table sits under {lines[heading]}, not ## Items; move it under ## Items")
|
||||
after = lines[table.start + len(table.rows):]
|
||||
section = after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))]
|
||||
if any(line.strip() for line in lines[heading + 1:table.header] + section):
|
||||
return Failure(f"## 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")
|
||||
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")
|
||||
result: list[tuple[Item, float]] = []
|
||||
for item, _ in scored:
|
||||
placed = place(item.id, held, position, {placed.id for placed, _ in result}, [])
|
||||
if isinstance(placed, Failure):
|
||||
return placed
|
||||
result += placed
|
||||
return result
|
||||
|
||||
|
||||
def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int], path: list[int]) -> list[tuple[Item, float]] | Failure:
|
||||
"""The item id_ preceded by those of its blockers not yet placed, each in score order, and theirs before them; path holds the items waiting on this one, to find a loop."""
|
||||
if id_ in path:
|
||||
loop = sorted(path[path.index(id_):])
|
||||
return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers")
|
||||
if id_ in placed:
|
||||
return []
|
||||
item, value = held[id_]
|
||||
blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__)
|
||||
added: list[tuple[Item, float]] = []
|
||||
for blocker in blockers:
|
||||
before = place(blocker, held, position, placed | {entry.id for entry, _ in added}, [*path, id_])
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
added += before
|
||||
return [*added, (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))
|
||||
if gone := sorted(cited - {item.id for item in items}):
|
||||
return Failure(f"docs/decisions.md cites \"`todo.md` item {gone[0]}\", which todo.md no longer holds; revise that decision to say what holds now")
|
||||
for item in sorted(items, key=lambda item: item.id):
|
||||
if item.id in cited and not item.exempt:
|
||||
return Failure(f"docs/decisions.md cites \"`todo.md` item {item.id}\"; mark it decision, or another reason the bar does not apply")
|
||||
if item.exempt == "decision" and item.id not in cited:
|
||||
return Failure(f"item {item.id} is marked decision, but docs/decisions.md does not cite \"`todo.md` item {item.id}\"; cite it there, or mark it with another reason the bar does not apply")
|
||||
return None
|
||||
|
||||
|
||||
def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure:
|
||||
"""README.md's goals in reading order: each one's number, a sub-goal as 4.1, and its mark, Maintain, Achieve or None."""
|
||||
found = sections(readme).get("Goals", [])
|
||||
if len(found) != 1:
|
||||
return Failure(f"README.md has ## Goals {len(found)} times; it needs it once")
|
||||
goals: list[tuple[str, Mark]] = []
|
||||
path: list[tuple[int, str]] = []
|
||||
for indent, position, mark in re.findall(r"^([ \t]*)(\d+)\. (?:\*\*(Maintain|Achieve):\*\*)?", found[0].expandtabs(4), re.M):
|
||||
while path and path[-1][0] >= len(indent):
|
||||
path.pop()
|
||||
path.append((len(indent), position))
|
||||
goals.append((".".join(part for _, part in path), typing.cast(Mark, mark or None)))
|
||||
numbers = [number for number, _ in goals]
|
||||
if not goals:
|
||||
return Failure("README.md's ## Goals has no numbered goal")
|
||||
if len(set(numbers)) < len(numbers):
|
||||
return Failure(f"README.md's ## Goals numbers {', '.join(numbers)}; number each goal by its position")
|
||||
return goals
|
||||
|
||||
|
||||
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure:
|
||||
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where goals holds no achieve goal, as where README.md voids code health and marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
|
||||
if unmarked := [number for number, mark in goals if mark is None]:
|
||||
return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
|
||||
achieve = [number for number, mark in goals if mark == "Achieve"]
|
||||
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
|
||||
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
|
||||
if CODE_HEALTH in weights and (overall is None or overall < FLOOR):
|
||||
weights[CODE_HEALTH] *= UNDER_FLOOR
|
||||
heaviest = max(weights.values(), default=0.0)
|
||||
return weights | {number: heaviest for number, mark in goals if mark == "Maintain"}
|
||||
|
||||
|
||||
def cited_items(decisions: str) -> list[int]:
|
||||
return [int(id_) for cited in re.findall(r"`todo\.md` items? (\d+(?:(?:, | and )\d+)*)", decisions) for id_ in re.findall(r"\d+", cited)]
|
||||
|
||||
|
||||
def stated(text: str, name: str) -> str | Failure:
|
||||
found = re.findall(rf"^`{name} = ([^`]+)`$", text, re.M)
|
||||
if len(found) != 1:
|
||||
return Failure(f"todo.md states `{name} = ...` {len(found)} times; state it once, on a line of its own under ## Scoring")
|
||||
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"
|
||||
|
||||
|
||||
def variables(shape: Shape) -> tuple[str, ...]:
|
||||
"""The names the formula may use: the shape's scores but C, which stays out of the formula, and its goal term."""
|
||||
return tuple(sorted({*shape.score_columns} - {"C"} | {goal_term(shape)}))
|
||||
|
||||
|
||||
def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure:
|
||||
if goal_term(scoring.shape) == "W":
|
||||
# The old shape weighs an item by its heaviest cited goal.
|
||||
term = max(scoring.weights[goal] for goal, _ in item.moves)
|
||||
else:
|
||||
# Only an OLD_SHAPE item names a goal without a move.
|
||||
term = sum(scoring.weights[goal] * (by or 0) for goal, by in item.moves)
|
||||
value = evaluate(formula, {**item.scores, goal_term(scoring.shape): term})
|
||||
return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score")
|
||||
|
||||
|
||||
def number(text: str | Failure, what: str) -> float | Failure:
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
try:
|
||||
value = float(text)
|
||||
except ValueError:
|
||||
value = math.nan
|
||||
return value if math.isfinite(value) else Failure(f"{what} {text!r} is not a finite number")
|
||||
|
||||
|
||||
def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Failure:
|
||||
table = table_rows(lines, WEIGHTS_HEADER)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
weights: dict[str, float] = {}
|
||||
for row in table.rows:
|
||||
found = cells(row, 2)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
weight = number(found[1], f"goal {found[0]}'s weight")
|
||||
if isinstance(weight, Failure):
|
||||
return weight
|
||||
if found[0] in weights:
|
||||
return Failure(f"the goal weights list goal {found[0]} twice")
|
||||
weights[found[0]] = weight
|
||||
if list(weights) != goals:
|
||||
default = "\n".join(f"| {goal} | {(len(goals) - index) / len(goals):.2f} |" for index, goal in enumerate(goals))
|
||||
return Failure(f"the goal weights list {', '.join(weights) or 'no goal'}, but README.md's goals are {', '.join(goals)}; by position they weigh:\n{WEIGHTS_HEADER}\n|---|---|\n{default}")
|
||||
return weights
|
||||
|
||||
|
||||
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
"""The row as an item, refused where it names a goal it may not; in SHAPE, with the R its L, E and I give."""
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if broken := cited_goals_failure(item, scoring):
|
||||
return broken
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
return item
|
||||
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
|
||||
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
for goal, _ in item.moves:
|
||||
if goal == CODE_HEALTH and goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md")
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
|
||||
if scoring.goals[goal] == "Maintain" and item.exempt != "defect":
|
||||
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves")
|
||||
return None
|
||||
|
||||
|
||||
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
|
||||
"""The item's row, each cell under its column."""
|
||||
written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in columns) + " |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
section = DETAILS.search(text)
|
||||
details = item_details(text)
|
||||
if section is None or isinstance(details, Failure):
|
||||
return details if isinstance(details, Failure) else text
|
||||
if unknown := sorted(set(details) - {item.id for item in items}):
|
||||
return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
|
||||
headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details]
|
||||
ranked = "\n" + "\n".join(headed) if headed else "\n"
|
||||
tail = "\n" if section.end() < len(text) else ""
|
||||
return text[:section.start(1)] + ranked + tail + text[section.end():]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user